Detail rows tell you what happened once. Summaries tell you what keeps happening. GROUP BY is the SQL tool that folds many rows into one row per group, and aggregate functions such as COUNT, SUM, and AVG do the maths inside each group. HAVING then filters those finished groups, the way WHERE filters raw rows. Together, sql group by having answers questions like sales per city, orders per customer, and average spend per month.
The examples use an orders table with id, customer_id, city, product_name, quantity, total_price, status, and order_date, plus a customers table with id and first_name. Every query follows the same written order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Keeping that order in your head prevents most errors, because each clause works on the output of the step before it. If grouping feels completely new, skim our sql select query examples first for the filtering basics it builds on.
What GROUP BY Actually Does
GROUP BY collects rows that share the same values in the named columns and treats each collection as a single unit. The result has one row per distinct combination. Any column in your SELECT list must either be one of the grouping columns or be wrapped in an aggregate function, because the database needs to know which single value represents the whole group.
SELECT city, COUNT(*) AS orders_count FROM orders GROUP BY city ORDER BY orders_count DESC;
This query counts orders per city. The database gathers all Paris rows into one group, all Berlin rows into another, and COUNT(*) counts the rows inside each group. The city column is allowed in the SELECT list because it is the grouping column, so every row in a group agrees on it. The alias orders_count lets ORDER BY sort groups from busiest city to quietest. Without GROUP BY, COUNT(*) would return one number for the whole table; with it, you get one number per city, which is the entire point.
Grouping by several columns creates a group per combination. Grouping orders by city and status gives one row for Paris paid, one for Paris pending, one for Berlin paid, and so on. Each extra grouping column makes the summary more detailed and the row count larger. Choose the combination that matches the question exactly, no more and no less.
SELECT city, status, COUNT(*) AS orders_count, SUM(total_price) AS revenue FROM orders GROUP BY city, status ORDER BY city, status;
Here each row reports how many orders a city has in a given status and how much revenue those orders represent. SUM(total_price) adds prices within the group only, resetting for every new group. Reading multi-column groups top to bottom, sorted by city then status, makes the pattern easy to scan in a report.
The Main Aggregate Functions
Five aggregates cover nearly all summaries. COUNT counts rows or values, SUM adds numbers, AVG averages them, and MIN and MAX return the smallest and largest values in the group. Aggregates ignore NULL inputs except for COUNT(*), which counts rows whether or not any particular column has a value. That difference between COUNT(*) and COUNT(column) causes real confusion, so it deserves a direct example.
SELECT COUNT(*) AS all_rows,
COUNT(email) AS rows_with_email,
COUNT(DISTINCT city) AS cities_served
FROM customers;
Run against customers without any GROUP BY, this returns a single summary row for the whole table. COUNT(*) counts every customer. COUNT(email) skips rows where email is NULL, so the gap between the two numbers is exactly how many customers have no email stored. COUNT(DISTINCT city) counts unique cities, ignoring repeats and NULLs. These three forms look similar but answer different questions, and picking the right one is a core grouping skill.
SELECT customer_id,
COUNT(*) AS order_count,
SUM(total_price) AS total_spent,
AVG(total_price) AS average_order,
MIN(order_date) AS first_order,
MAX(order_date) AS latest_order
FROM orders
GROUP BY customer_id
ORDER BY total_spent DESC
LIMIT 10;
This is a compact customer profile: how often each customer ordered, how much they spent in total, their typical order value, and the span from first to latest order. MIN and MAX work on dates as happily as on numbers, returning the earliest and latest values. Limiting to ten after sorting by total spent gives a top-customers list. When customers join the picture by name instead of id, the technique from sql joins explained slots straight in before the GROUP BY step.
Filtering Before and After Grouping: WHERE Versus HAVING
WHERE and HAVING look similar but act at different stages. WHERE filters individual rows before any grouping happens, so it can use ordinary column values but cannot use aggregates. HAVING filters complete groups after aggregation, so it can test COUNT, SUM, and other aggregate results. Many real queries use both: WHERE trims the input cheaply, HAVING applies the business rule to the summary.
SELECT city, COUNT(*) AS orders_count, SUM(total_price) AS revenue FROM orders WHERE status = 'paid' GROUP BY city HAVING SUM(total_price) > 1000 ORDER BY revenue DESC;
Follow the flow. First, WHERE keeps only paid orders, so pending and cancelled rows never reach the grouping step. Next, GROUP BY city forms one group per city from those paid rows. Then HAVING keeps only cities whose summed revenue exceeds 1000. Finally, ORDER BY sorts the survivors. If you tried to write the revenue test in WHERE, the database would reject it, because at WHERE time there is no group total yet. Conversely, writing status = ‘paid’ in HAVING would also fail in standard SQL, because status differs within a group and is not an aggregate. Each condition belongs to its own stage.
Filtering Groups With HAVING on Counts
The most common HAVING job is finding repeat behaviour: customers with more than five orders, products sold at least once a week, or cities with a meaningful number of signups. Counts in HAVING turn a raw summary into a shortlist someone can act on.
SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id HAVING COUNT(*) >= 5 ORDER BY order_count DESC; SELECT product_name, SUM(quantity) AS units_sold FROM orders WHERE status = 'paid' GROUP BY product_name HAVING SUM(quantity) >= 100;
The first query lists loyal customers with five or more orders, busiest first. There is no WHERE clause because every order row should count toward loyalty. The second query lists products that sold at least 100 units among paid orders only; the WHERE removes unpaid rows before summing, and HAVING applies the threshold to the finished sums. Some databases let HAVING refer to the SELECT alias, such as HAVING units_sold >= 100, but repeating the aggregate expression works everywhere and reads clearly, so prefer the explicit form in shared code.
A useful check while learning is to remove the HAVING clause and add the threshold value as a plain output column. Run the query, confirm the column shows what you think it shows, then move that expression into HAVING. This two-step habit prevents the silent disappointment of a filter that was stricter or looser than intended, especially when NULLs are involved.
Grouping by Dates and Time Periods
Reports usually roll up by day, month, or year. Databases provide date functions for extracting parts of a date, and the exact names vary by system. In MySQL you will see YEAR(), MONTH(), and DATE(); in PostgreSQL, DATE_TRUNC and EXTRACT are common; SQLite uses strftime. The grouping idea is identical, only the function spelling changes.
SELECT DATE(order_date) AS order_day,
COUNT(*) AS orders_count,
SUM(total_price) AS daily_revenue
FROM orders
GROUP BY DATE(order_date)
ORDER BY order_day;
SELECT YEAR(order_date) AS order_year,
MONTH(order_date) AS order_month,
COUNT(*) AS orders_count
FROM orders
GROUP BY YEAR(order_date), MONTH(order_date)
ORDER BY order_year, order_month;
The first query groups by calendar day, turning a timestamp column into daily totals, which suits a sales chart. The second groups by year and month together; grouping by month alone would merge January 2025 with January 2026, a classic reporting bug. Whenever a period repeats across years, group by the full period key. For month labels in a chart, format after grouping rather than grouping by a formatted text label, because text months sort alphabetically instead of chronologically.
Grouping Mistakes and How to Spot Them
The first mistake is selecting a column that is neither grouped nor aggregated. Some databases reject this outright; MySQL with certain settings historically returned an arbitrary value from the group, which produced plausible-looking wrong reports. The safe rule is simple: group by every non-aggregated column you select, or aggregate it deliberately, for example with MAX when any representative value will do and you understand why.
The second mistake is filtering groups in WHERE, which raises an error, or filtering rows in HAVING with a non-aggregate condition, which also raises an error in strict systems. When a query fails near grouping, ask which stage the condition belongs to. The third mistake is double counting after a join: if you join a one-to-many table before grouping, SUM over a parent column repeats once per child row. Aggregate the child data in a subquery first, or verify totals against a count you trust. The fourth mistake is forgetting that aggregates skip NULLs, so AVG over a column full of gaps averages only the present values. That is usually desired, but state it in the report so readers interpret the average correctly. After producing summaries, teams often store a snapshot with the statements covered in sql insert update delete, and routine database housekeeping leans on the checks collected in mysql common queries.
A Practical Workflow for Summary Queries
Build summaries in layers. Start with the detail query and its WHERE filter, and run it. Add GROUP BY with one aggregate and confirm the row count equals the number of distinct groups you expect. Add the remaining aggregates one by one, checking a single group by hand against the detail rows. Only then add HAVING, and finally ORDER BY and LIMIT for presentation. Spot-check the largest and smallest groups, because errors hide at the extremes. Save the final query with a comment stating the question it answers and the date range it assumes, so a future reader does not reuse a partial-period summary as if it covered a full month.
Conclusion
GROUP BY folds rows into one summary row per group, aggregates do the maths inside each group, and HAVING filters groups after that maths is done, while WHERE filters rows before it starts. Keep every selected column either grouped or aggregated, group dates by their full period, and test each layer as you build. With that discipline, summaries stop being guesswork and become answers you can defend.
Tagged: aggregate functions count sum avg database queries sql group by sql having sql summaries



3 thoughts on “SQL GROUP BY and HAVING: Summaries That Make Sense”