Beginner Topic 13 of 51 Databases
GROUP BY and HAVING
Grouping rows and filtering the groups.
How it works
GROUP BY partitions rows into groups that share the same values in the listed columns, and aggregate functions then compute one result per group. HAVING filters groups after aggregation, whereas WHERE filters rows before it. Every selected column must be either in GROUP BY or inside an aggregate. Grouping sets, ROLLUP and CUBE produce subtotals.
Step-by-step walkthrough
- All orders are read.
- Rows are grouped by customer.
- An aggregate such as SUM is computed per group.
- HAVING filters the groups, WHERE filters rows before grouping.
- The output has one row per surviving group.
Where it is used
Sales by region, orders per customer, error counts per hour and finding duplicates with HAVING COUNT(*) greater than one use grouping.
Common pitfall
Putting an aggregate condition in WHERE gives an error; it belongs in HAVING. Filtering early with WHERE is faster than filtering later with HAVING. Grouping by too many or unindexed columns is slow and memory hungry. Joins before grouping can multiply rows and distort counts and sums, so aggregate in a subquery first when needed.
Where it fits in the course
GROUP BY and HAVING is topic 13 of 51 in Databases, rated Beginner. It follows Aggregate Functions. The next topic is Joins.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Databases quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Databases quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is GROUP BY and HAVING?
Where do people use GROUP BY and HAVING?
What is the most common mistake with GROUP BY and HAVING?
What should I learn before this topic?
How can I practice it?
Is GROUP BY and HAVING hard to learn?
How long does it take to learn GROUP BY and HAVING?
Which topics are related to GROUP BY and HAVING?
What should I study after GROUP BY and HAVING?
Related topics
- Aggregate Functions (Databases)
- Joins (Databases)
- INSERT, UPDATE, DELETE (Databases)
- Inner and Outer Joins (Databases)