In our AWS re/Start Databases module today, we covered grouping data in our query outputs. We looked at how to use the GROUP BY clause alongside aggregate functions like COUNT() and SUM() .
If you are coming from a frontend or backend background, you probably think of query results as individual rows. But here is the catch: when you collapse rows into groups, standard column selection stops working. If you don't understand how aggregation works, you will constantly run into errors like "column must appear in the GROUP BY clause or be used in an aggregate function."
Here is how SQL actually processes grouped data:
1. FROM
The database first figures out which table to pull the data from.
2. WHERE
It filters the individual rows before they are grouped. This is why you cannot use an alias you defined in the SELECT step inside a WHERE clause. The SELECT hasn't happened yet.
3. GROUP BY
It takes the remaining rows and collapses them into buckets based on your criteria. For example, if you group by continent , all the countries in South America are squeezed into a single row bucket.
4. HAVING
It filters the groups created in the previous step. Just like WHERE filters rows, HAVING filters the buckets. This is where you are allowed to use aggregate functions to filter your results (e.g., HAVING COUNT(*) > 5 ).
5. SELECT
The database now calculates the final columns. If you grouped by continent , you can select continent . But you cannot just select name anymore because there are multiple country names in the bucket. You have to use an aggregate function like COUNT(name) to tell the database how to summarize that bucket.
6. ORDER BY
Finally, it sorts the output. Because this runs after SELECT, it is the only clause where you can use your column aliases.
Practical Example
If we want to know how many countries are in specific regions, querying the raw table gives us a long list of individual rows.
Instead, we use GROUP BY to collapse the buckets, and COUNT() to count what is inside them:
sql
SELECT continent, COUNT(name) AS 'countries'
FROM country
WHERE continent = 'South America' OR continent = 'Antarctica'
GROUP BY continent;
The Bottom Line
Understanding how GROUP BY and COUNT() work together is a game-changer. It explains why you cannot select raw text columns without aggregating them, and how to turn thousands of individual rows into a clean summary table.
Have you ever run into a "GROUP BY" error while writing reports? Let me know below!
#sql
#databases
#aws-restart
#cloud-practitioner
#data
Loading article