Problem solve Get help with specific problems with your technologies, process and projects.

Calculating a percentage for a group

I have Member table with a Nationality column, and I want to get the percentage breakdown of members by Nationality,...

for example:

  • American 29%
  • Canadian 14%
  • Mexican 11%
  • ...

Is there an efficient way to do this in a single query? If I were to do this:

SELECT nationality, 
  ((COUNT(*) * 100)/(select count(*) from member)) as percentage
 FROM member 
GROUP BY nationality 
ORDER BY nationality;

Wouldn't this repeatedly execute the inner query over and over?

That's a very good question, and shows you're thinking. No, the database optimizer is smart enough to recognize that select count(*) from member is independent of the outer query, and will execute it only once, before the outer query. Then it will just use the result in the calculation of the percentage for each group.

As far as I can tell, your query will give you exactly the results you require, and efficiently to boot.

Good job.

For More Information

Dig Deeper on Oracle and SQL

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.