Why do I need to use GROUP BY?

I’m working through the final project in the intermediate SQL course:

https://www.codecademy.com/paths/data-science/tracks/sql-intermediate/modules/dspath-sql-cumulative-project/projects/cadcademy-milestone

and I’m on Task #9: Find patients that have come in for a lipid panel more than once. Use the panels table. You only need to list the patient_ID s for this.

I get no results when I use this code:
‘’’
SELECT patient_ID
FROM panels
HAVING COUNT(patient_ID) > 1;
‘’’

It only works when I add a GROUP BY statement:
‘’’
SELECT patient_ID
FROM panels
GROUP BY patient_ID
HAVING COUNT(patient_ID) > 1;
‘’’

Why? Why doesn’t SQL return any results if I don’t require the results to be grouped?

1 Like

That is because HAVING has to be used either with GROUP BY or with aggregate functions (like COUNT).
This means that for the above to work, you need to add the GROUP BY like you did or do something like this:

SELECT COUNT(patient_ID)
FROM panels
HAVING COUNT(patient_ID) > 1;
1 Like

Do you also know why the having needs a group by or aggregate function ?

1 Like