Skip to content
Advertisement

How to count occurrences of a column value efficiently in SQL?

I have a table of students:

I want to query for all students, and an additional column that counts how many students are of the same age:

What’s the most efficient way of doing this? I fear that a sub-query will be slow, and I’m wondering if there’s a better way. Is there?

Advertisement

Answer

This should work:

If you need the id as well you could include the above as a sub query like so:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement