GROUP BY and HAVING in SQL, With Examples

6 min read

GROUP BY collapses rows that share a value into one row per value, so that an aggregate such as SUM or COUNT can be calculated for each group. HAVING then filters those groups, the way WHERE filters rows. “Total revenue per hotel” is a GROUP BY; “only hotels above 30,000 rupees” is a HAVING.

The one rule that removes most GROUP BY errors: every column in your SELECT must either be in the GROUP BY or be inside an aggregate function. Everything else in this lesson follows from understanding why.

Syntax

The table shows where GROUP BY and HAVING sit in a query and what each clause does.

Clause What it does Syntax Example
GROUP BY Makes one group per distinct value SELECT col, AGG(col2) FROM t GROUP BY col SELECT hotel, SUM(amount) FROM bookings GROUP BY hotel
GROUP BY, several columns One group per distinct combination GROUP BY col1, col2 GROUP BY hotel, room_type
HAVING Keeps only groups that pass a condition GROUP BY col HAVING condition on aggregate GROUP BY hotel HAVING SUM(amount) > 30000
WHERE with GROUP BY Filters rows before grouping WHERE condition GROUP BY col WHERE nights >= 2 GROUP BY hotel
ORDER BY Sorts the grouped result GROUP BY col ORDER BY AGG(col2) DESC GROUP BY hotel ORDER BY SUM(amount) DESC

The written order is always SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, then LIMIT. Put HAVING before GROUP BY or WHERE after it and the query will not parse.

The data used throughout

The examples follow one scenario: eight October bookings across three properties of a Jaipur hotel chain. Amounts are in rupees for the whole stay.

booking_id hotel room_type nights amount
B1 Amer Palace Deluxe 2 9000
B2 Amer Palace Suite 1 12500
B3 Amer Palace Deluxe 3 13500
B4 Pink City Inn Standard 2 5000
B5 Pink City Inn Deluxe 1 4800
B6 Lake View Standard 4 10400
B7 Lake View Standard 1 2600
B8 Lake View Suite 2 21000

Example 1: one row per hotel

The question: how many bookings, nights and how much revenue did each hotel have?

Query: SELECT hotel, COUNT(*) AS bookings, SUM(nights) AS nights, SUM(amount) AS revenue FROM bookings GROUP BY hotel ORDER BY revenue DESC

hotel bookings nights revenue
Amer Palace 3 6 35000
Lake View 3 7 34000
Pink City Inn 2 3 9800

Eight rows became three. The database sorted the bookings into a pile per hotel, then ran COUNT and SUM on each pile. booking_id and room_type have gone because they differ inside each pile, and the query did not ask for them.

That is why the rule exists. If you add room_type to the SELECT without grouping by it, the database has three different room types in the Amer Palace pile and no instruction on which one to show. PostgreSQL and SQL Server refuse with an error saying the column must appear in the GROUP BY clause or be used in an aggregate function. MySQL refuses too by default since version 5.7, through a setting called ONLY_FULL_GROUP_BY. Older MySQL servers, and ones where that setting has been switched off, return an arbitrary room type instead, which is worse than an error because the result looks fine.

Example 2: grouping by two columns

Group by hotel and room_type together and you get one row per combination that exists.

Query: SELECT hotel, room_type, COUNT(*) AS bookings, SUM(amount) AS revenue FROM bookings GROUP BY hotel, room_type ORDER BY hotel, room_type

hotel room_type bookings revenue
Amer Palace Deluxe 2 22500
Amer Palace Suite 1 12500
Lake View Standard 2 13000
Lake View Suite 1 21000
Pink City Inn Deluxe 1 4800
Pink City Inn Standard 1 5000

Six rows, not nine. Combinations with no bookings, such as a Suite at Pink City Inn, do not appear, because GROUP BY only groups rows that exist. If a report needs every combination including zeros, build the full list first and LEFT JOIN the grouped result onto it.

The order of columns in GROUP BY does not change the result, only how you might choose to sort it.

Example 3: HAVING to filter groups

The question: which hotels earned more than 30,000 rupees?

Query: SELECT hotel, SUM(amount) AS revenue FROM bookings GROUP BY hotel HAVING SUM(amount) > 30000

hotel revenue
Amer Palace 35000
Lake View 34000

You cannot write WHERE SUM(amount) > 30000. WHERE runs on individual rows before any grouping, so at that point there is no sum to test. HAVING runs after grouping and sees each group’s totals.

WHERE and HAVING in the same query

They are not alternatives; they filter at different stages and can be used together. The question: counting only stays of two nights or more, which hotels crossed 20,000 rupees?

Query: SELECT hotel, COUNT(*) AS bookings, SUM(amount) AS revenue FROM bookings WHERE nights >= 2 GROUP BY hotel HAVING SUM(amount) > 20000

WHERE first removes the three one-night bookings (B2, B5, B7). Grouping then gives Amer Palace 22,500, Pink City Inn 5,000 and Lake View 31,400. HAVING keeps the two above 20,000.

hotel bookings revenue
Amer Palace 2 22500
Lake View 2 31400

The quick test for which to use: if the condition is about a single booking (its nights, its date, its city), it belongs in WHERE. If it is about a group’s total, count or average, it belongs in HAVING. Putting a row-level condition in HAVING sometimes works, but it groups every row first and throws most away afterwards, which is slower on a large table.

WHERE HAVING
Filters Individual rows Groups
Runs Before GROUP BY After GROUP BY
Can use aggregates No Yes
Works without GROUP BY Yes Technically yes, treating the whole table as one group

The order SQL actually runs a query in

Most GROUP BY confusion goes away once you see that the database does not run the clauses in the order you write them.

Step Clause What happens
1 FROM and JOIN Gather the rows
2 WHERE Drop rows that fail the condition
3 GROUP BY Sort the remaining rows into groups
4 HAVING Drop groups that fail the condition
5 SELECT Calculate the output columns, including aliases
6 ORDER BY Sort the result
7 LIMIT, TOP or FETCH FIRST Keep the first n rows

This explains three things at once. WHERE cannot see aggregates because grouping has not happened. HAVING cannot reliably see a SELECT alias because SELECT runs after it. And ORDER BY can use an alias because it runs last.

Where MySQL, PostgreSQL and SQL Server differ

Grouping is standard, but the dialects are inconsistent about aliases and shortcuts, which is exactly the sort of thing an interviewer asks.

Point MySQL PostgreSQL SQL Server
Column not grouped or aggregated Error by default (ONLY_FULL_GROUP_BY); arbitrary value if that is off Error Error
SELECT alias in GROUP BY, as in GROUP BY revenue_band Allowed Allowed Not allowed
SELECT alias in HAVING, as in HAVING revenue > 30000 Allowed Not allowed Not allowed
Column position, as in GROUP BY 1 Allowed Allowed Not allowed
Subtotal rows GROUP BY hotel, room_type WITH ROLLUP GROUP BY ROLLUP (hotel, room_type) GROUP BY ROLLUP (hotel, room_type)
Top n groups LIMIT 2 at the end LIMIT 2 or FETCH FIRST 2 ROWS ONLY SELECT TOP 2 at the start

The safe habit: repeat the aggregate expression in HAVING (HAVING SUM(amount) > 30000) rather than using an alias, and write out the column names in GROUP BY. That version runs on all three.

ROLLUP is worth a line of its own. It adds subtotal rows for each hotel and a grand total row, with NULL in the columns being totalled. On this data, a rollup by hotel would add one extra row with hotel as NULL and revenue 78,800, which is the chain-wide total.

Mistakes beginners make

Selecting a column that is not grouped. The error message is long but the fix is always one of two: add the column to GROUP BY, or wrap it in an aggregate such as MAX.

Using WHERE for an aggregate condition. WHERE COUNT(*) > 2 always fails. Move it to HAVING.

Averaging averages. The average nightly rate at Amer Palace is total revenue divided by total nights: 35,000 / 6, about 5,833. Writing AVG(amount / nights) instead averages three per-booking rates (4,500, 12,500 and 4,500) and gives about 7,167, because the one-night suite counts as much as the three-night deluxe stay. At Lake View the gap is 4,857 against 5,233. Decide which you mean; for a hotel’s average daily rate, it is the first.

Grouping on a column with inconsistent values. “Amer Palace”, “amer palace” and “Amer Palace ” (with a trailing space) may be one group or three, depending on the database and its collation settings. PostgreSQL treats them as three; MySQL and SQL Server usually ignore the difference in case. Do not rely on either behaviour: clean the column with TRIM and LOWER before grouping, or the same query gives different counts on different systems.

Expecting empty groups to appear. GROUP BY never invents a row for a combination with no data.

GROUP BY is the backbone of most reporting queries, and it sits on top of aggregate functions such as COUNT, SUM and AVG, which have their own NULL behaviour worth knowing. Most real reports also group across more than one table, so the SQL joins guide is the natural next read. If you summarise data in spreadsheets today, a GROUP BY is the query version of a pivot table in Excel. For the questions recruiters ask on this topic, see our SQL interview questions.

Frequently asked questions

What does GROUP BY do in SQL?

GROUP BY combines rows that have the same value in one or more columns into a single row for each value. It is used with aggregate functions such as COUNT, SUM and AVG so that the aggregate is calculated per group, for example total revenue per hotel or number of orders per city.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before they are grouped, and cannot use aggregate functions. HAVING filters groups after GROUP BY has run, and can use aggregates such as SUM(amount) > 30000. A query can use both: WHERE to remove unwanted rows, then HAVING to remove unwanted groups.

Can I use GROUP BY without an aggregate function?

Yes. GROUP BY on its own returns one row per distinct value, which gives the same result as SELECT DISTINCT on those columns. It is more common to use DISTINCT for that purpose, because it states the intent more clearly.

Can I use HAVING without GROUP BY?

Yes, though it is rare. Without GROUP BY the whole table is treated as one group, so HAVING decides whether that single summary row is returned. For example, SELECT COUNT(*) FROM bookings HAVING COUNT(*) > 5 returns the count only if there are more than five bookings.

Why do I get an error saying a column must appear in the GROUP BY clause?

Because the column is in your SELECT but is neither grouped nor aggregated, so the database does not know which of the group’s values to show. Add the column to GROUP BY if you want a row per value of it, or wrap it in an aggregate such as MAX or MIN if you want one value per group.

Does the order of columns in GROUP BY matter?

Not for the result. GROUP BY hotel, room_type and GROUP BY room_type, hotel produce the same groups and the same totals. The order only matters with ROLLUP, where it decides which subtotals are produced, and it can affect which index the database uses on a large table.

Build reports that hold up

GROUP BY is easy to write and easy to get subtly wrong, through an average of averages or a group split by a trailing space. Catching those takes practice on data that is as messy as a real company’s.

SkilloVilla’s SQL: Beginner to Advanced course has a full module on aggregation functions and GROUP BY, alongside joins, conditional logic and advanced SQL statements, taught in live classes with mentor support and practice on SQL playgrounds. To learn SQL inside a full analyst programme with Python and placement support, see the Data Analytics with Python track.

Statistics for Data Analytics: The Topics an Analyst Needs,…

Statistics for data analytics: the topics an analyst uses, grouped into a learning path, with the business question each answers and a study plan.
SkilloVilla Team
6 min read

Standard Deviation and Variance for Data Analysts, With Worked…

Standard deviation and variance for data analysts: population vs sample (n vs n-1), a worked calculation, Excel and SQL functions, and what it means.
SkilloVilla Team
7 min read

Power BI vs Tableau: Which to Learn for an…

Power BI vs Tableau compared for Indian job-seekers: job demand, cost, learning curve, data prep, Mac support and sharing, with a side-by-side table.
SkilloVilla Team
5 min read

Leave a Reply