GROUP BY and HAVING: Summarizing Groups of Rows
How GROUP BY splits rows into groups and computes aggregates for each one, and how HAVING filters the groups: the SELECT-list rule, NULL groups, grouping by expressions and dates, counting with outer joins, WHERE versus HAVING, and finding duplicates.
kvi5hnuCode Sprout team member16 min readOn this page
The previous article's aggregates collapsed a whole table into one row: one count, one total, one average. Most real questions ask for those numbers per something: products per category, orders per customer, revenue per month. GROUP BY does exactly that. It splits the rows into groups that share a value, and runs the aggregates once for each group. HAVING then filters the groups, the way WHERE filters rows.
These two clauses, together with the aggregate functions, are the core of every report written in SQL. This article covers how they work, the rule that decides which columns you can select, and the mistakes that produce errors or, worse, wrong numbers.
The examples use the products table and the shop database from Part 3.
GROUP BY: one row per group
Add GROUP BY category to a summary query, and you get one row per category instead of one row for the table:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- One summary row per category
SELECT category,
COUNT(*) AS products,
SUM(stock) AS units_in_stock,
MIN(price) AS cheapest,
MAX(price) AS dearest,
ROUND(AVG(price), 2) AS avg_price
FROM products
GROUP BY category
ORDER BY category;
category | products | units_in_stock | cheapest | dearest | avg_price
----------+----------+----------------+----------+---------+-----------
clothing | 1 | 75 | 16.00 | 16.00 | 16.00
lighting | 2 | 55 | 27.00 | 34.50 | 30.75
packs | 2 | 22 | 54.00 | 89.95 | 71.98
tents | 2 | 15 | 249.99 | 489.00 | 369.50
(4 rows)
Here's what happens, step by step:
FROMproduces the seven product rows.GROUP BY categorysorts them into groups, one for each different value ofcategory: clothing (1 row), lighting (2), packs (2) and tents (2).- Each aggregate is computed separately for each group:
COUNT(*)counts the group's rows,SUM(stock)adds the group's stock, and so on. SELECTproduces one output row per group.
So a grouped query returns as many rows as there are groups, no matter how many rows each group contains. Four categories, four rows.
The ORDER BY matters. Without it, groups come back in whatever order the database produced them, which depends on whether it grouped by sorting or by hashing. Older MySQL versions sorted grouped results implicitly, but MySQL 8.0 removed that behaviour, and no other database ever promised it. If you need an order, ask for it.
Which columns can you select?
In a grouped query, every output row stands for a whole group. So each value in the SELECT list must have one value per group. That gives the rule:
Every expression in
SELECT(andHAVINGandORDER BY) must be either a grouping column, an aggregate, a constant, or built only from those.
category is fine because it's the grouping column: every row in the tents group has category = 'tents'. COUNT(*) is fine because it's an aggregate. But name isn't, because the tents group contains two names. Which one would SQL show? It refuses to choose, and reports an error, as you'll see in the "Errors" section below.
Expressions built from grouping columns are allowed, so SELECT UPPER(category) ... GROUP BY category works. The reverse doesn't: SELECT category ... GROUP BY UPPER(category) is rejected, because a group like 'TENTS' could, in principle, contain both 'tents' and 'Tents'.
Functional dependence: grouping by a key
There's one important relaxation of the rule. If you group by a table's primary key, every other column of that table has only one value per group, because a key value identifies exactly one row. The SQL standard calls those columns functionally dependent on the key and allows you to select them without grouping by them.
PostgreSQL and MySQL both implement this. So in PostgreSQL you can write:
SELECT c.customer_id, c.name, COUNT(o.order_id)
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id; -- c.name is allowed: customer_id is the primary key
Oracle, SQL Server and SQLite don't recognise functional dependence (SQLite is permissive for a different reason, explained below). In those, list every column: GROUP BY c.customer_id, c.name. That version works everywhere and gives the same groups, so it's the portable choice.
Don't group by c.name alone when you mean "per customer". Two customers with the same name would be merged into one group, and their orders added together. Group by the key, and add the name for display.
The permissive databases
SQLite, and MySQL with ONLY_FULL_GROUP_BY turned off, accept a column that isn't grouped or aggregated and return its value from some row of the group. In SQLite, there's one documented special case: with a single MIN or MAX in the query, the other bare columns come from the row that holds the minimum or maximum. Outside that case, the value is arbitrary. Don't rely on either behaviour in portable code. When you know all the rows in a group share a value and the database doesn't, wrap the column in ANY_VALUE(...) (SQL, PostgreSQL 16 and later, MySQL, Oracle) or in MIN(...) or MAX(...), which work everywhere.
Grouping by several columns
GROUP BY can list several columns. Then a group is a distinct combination of their values:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- NULL brands form one group of their own
SELECT brand, COUNT(*) AS products, COUNT(brand) AS counted_brand
FROM products
GROUP BY brand
ORDER BY brand;
-- Grouping by two columns: one row per distinct (category, brand) pair
SELECT category, brand, COUNT(*) AS products
FROM products
GROUP BY category, brand
ORDER BY category, brand;
brand | products | counted_brand
---------+----------+---------------
Alpina | 2 | 2
Kestrel | 2 | 2
Lumen | 1 | 1
Woolly | 1 | 1
(null) | 1 | 0
(5 rows)
category | brand | products
----------+---------+----------
clothing | Woolly | 1
lighting | Lumen | 1
lighting | (null) | 1
packs | Kestrel | 2
tents | Alpina | 2
(5 rows)
The first query shows how GROUP BY treats NULL: all the NULLs go into one group. That's different from comparisons, where NULL = NULL is unknown, but it's the same as DISTINCT, which also treats NULLs as duplicates of each other. The lantern, with no brand, forms a group of one. Notice that COUNT(brand) is 0 for that group, since its only value is NULL, while COUNT(*) is 1. With ORDER BY brand, PostgreSQL and Oracle put the NULL group last, while MySQL, SQL Server and SQLite put it first, just like NULLs in ORDER BY (article 9). In MySQL, SQL Server and SQLite it sorts first, just like NULLs in ORDER BY (article 9).
The second query groups by category and brand together, so the groups are the five different (category, brand) pairs. Lighting splits into two groups, Lumen and NULL. The order of the columns in GROUP BY doesn't change the groups, only, perhaps, the order the database happens to produce them in.
HAVING: filtering groups
WHERE filters rows before they're grouped. HAVING filters groups after the aggregates have been computed. That's why HAVING can test aggregates and WHERE can't:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- WHERE picks rows, GROUP BY forms groups, HAVING picks groups
SELECT category, COUNT(*) AS cheap_products
FROM products
WHERE price < 100
GROUP BY category
HAVING COUNT(*) >= 2
ORDER BY category;
-- HAVING can test an aggregate that isn't in the SELECT list
SELECT category
FROM products
GROUP BY category
HAVING MAX(price) > 200;
category | cheap_products
----------+----------------
lighting | 2
packs | 2
(2 rows)
category
----------
tents
(1 row)
The first query uses all three clauses. Follow the rows through it:

WHERE price < 100removes the two tents, leaving five rows.GROUP BY categoryforms three groups from those five rows.COUNT(*)is computed per group: lighting 2, packs 2, clothing 1.HAVING COUNT(*) >= 2removes the clothing group.
Tents don't appear at all, even though there are two of them, because their rows were removed before grouping. Moving the price test changes the question: WHERE price < 100 asks "how many cheap products does each category have?", while HAVING MAX(price) < 100 would ask "which categories have only cheap products?".
The second query shows that HAVING can test an aggregate that isn't in the SELECT list. MAX(price) is computed per group just for the filter.
WHERE or HAVING?
The rule is simple:
- A condition on individual rows goes in
WHERE. - A condition on aggregates goes in
HAVING.
What about a condition on a grouping column, like category <> 'tents'? It's legal in either clause and gives the same result. But put it in WHERE: then the database discards the rows before grouping them, instead of grouping them and throwing the group away. Modern optimizers often move such conditions into WHERE automatically, but writing it there makes the intent clear and doesn't depend on the optimizer.
HAVING is allowed without GROUP BY. The whole table is then one group, and HAVING decides whether the single summary row is returned at all. SELECT COUNT(*) FROM products HAVING COUNT(*) > 100 returns no rows, not a row with 7.
Grouping with joins
Grouping becomes really useful after a join, where you summarize the child rows per parent. Count orders per customer:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Orders per customer, including customers with no orders
SELECT c.customer_id,
c.name, -- allowed: grouped by the primary key
COUNT(o.order_id) AS orders, -- counts matched orders only
COUNT(*) AS rows_in_group
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id
ORDER BY c.customer_id;
customer_id | name | orders | rows_in_group
-------------+--------------+--------+---------------
1 | Asha Rao | 2 | 2
2 | Ben Okafor | 1 | 1
3 | Chen Wei | 1 | 1
4 | Dana Cruz | 1 | 1
5 | Eli Novak | 0 | 1
6 | Farah Haddad | 0 | 1
(6 rows)
The LEFT JOIN keeps Eli and Farah, who have no orders. Each of them gets one row in the join, with NULLs in the order columns. Then:
COUNT(o.order_id)skips the NULL and correctly returns 0.COUNT(*)counts the row and wrongly returns 1.
This is one of the most common bugs in SQL reports. After an outer join, count a column from the optional side, preferably its primary key, which is never NULL in a real row.
When a query joins several child tables, watch for fan-out: rows multiply, and SUM and COUNT are inflated. Article 17 explained the problem and the fix (aggregate each child table before joining).
Grouping by expressions
You can group by any expression, not only by a column. That's how you build bands, buckets and time periods:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Group by an expression: price bands
SELECT CASE
WHEN price < 50 THEN 'budget'
WHEN price < 200 THEN 'mid-range'
ELSE 'premium'
END AS band,
COUNT(*) AS products
FROM products
GROUP BY band -- PostgreSQL and MySQL accept the alias here
ORDER BY MIN(price);
-- Group by a date expression: orders per week (weeks start on Monday)
SELECT DATE_TRUNC('week', placed_on)::date AS week_starting,
COUNT(*) AS orders
FROM orders
GROUP BY DATE_TRUNC('week', placed_on)
ORDER BY week_starting;
-- Sort groups by their aggregate
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY COUNT(*) DESC, status;
band | products
-----------+----------
budget | 3
mid-range | 2
premium | 2
(3 rows)
week_starting | orders
---------------+--------
2026-03-02 | 2
2026-03-09 | 2
2026-03-16 | 2
(3 rows)
status | orders
-----------+--------
shipped | 3
cancelled | 1
delivered | 1
pending | 1
(4 rows)
The first query groups products into price bands by a CASE expression. It refers to the expression by its alias, band, which PostgreSQL, MySQL and SQLite allow in GROUP BY. Oracle allows it from version 23ai, but SQL Server doesn't, and the SQL standard doesn't either. There, repeat the whole expression in GROUP BY, or compute it in a derived table or a CTE and group the outer query by the alias:
SELECT band, COUNT(*)
FROM (SELECT CASE WHEN price < 50 THEN 'budget'
WHEN price < 200 THEN 'mid-range'
ELSE 'premium' END AS band
FROM products) AS banded
GROUP BY band;
One trap in PostgreSQL: if an alias has the same name as an input column, GROUP BY uses the input column. Pick aliases that don't clash with column names.
The ORDER BY MIN(price) sorts the bands by their cheapest product, so they appear in price order rather than alphabetically. ORDER BY can use aggregates in a grouped query, because it runs after grouping.
The second query counts orders per week. DATE_TRUNC('week', placed_on) maps every date to the Monday that starts its week, so all the dates in one week share a value and land in one group. The same pattern with 'month' or 'year' gives monthly or yearly totals. Other databases spell it differently: TRUNC(placed_on, 'IW') in Oracle, DATETRUNC(iso_week, placed_on) in SQL Server 2022 (plain week follows SET DATEFIRST, Sunday by default), and DATE_FORMAT or YEARWEEK in MySQL. Article 41 covers calendars and periods with no rows, which a plain GROUP BY silently leaves out: a week with no orders produces no group, not a group with 0.
The third query sorts the groups by their count, largest first, with status as a tie-breaker so that the order of the three groups with 1 order is fixed.
Grouping by position
PostgreSQL, MySQL and SQLite accept a column position in GROUP BY, as in GROUP BY 1, 2, meaning the first and second items of the SELECT list. It's handy in interactive work, but fragile in code: adding a column to the SELECT list silently changes the grouping. Oracle 23ai accepts positions only when the group_by_position_enabled parameter is turned on, and SQL Server doesn't accept them.
More grouped queries
Two patterns appear constantly in practice. The first totals child rows per parent and filters on the total. The second finds duplicates:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Order value per order, keeping only orders worth more than 100
SELECT o.order_id,
o.placed_on,
SUM(oi.qty * oi.unit_price) AS order_value
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.order_id, o.placed_on
HAVING SUM(oi.qty * oi.unit_price) > 100
ORDER BY order_value DESC;
-- Finding duplicates: cities shared by more than one customer
SELECT city, COUNT(*) AS customers, STRING_AGG(name, ', ' ORDER BY name) AS who
FROM customers
GROUP BY city
HAVING COUNT(*) > 1
ORDER BY city;
order_id | placed_on | order_value
----------+------------+-------------
104 | 2026-03-15 | 489.00
101 | 2026-03-02 | 297.99
103 | 2026-03-09 | 154.45
(3 rows)
city | customers | who
-------+-----------+-----------------------
Leeds | 2 | Ben Okafor, Eli Novak
Pune | 2 | Asha Rao, Chen Wei
(2 rows)
The first query groups order lines by order, adds up their value, and keeps only orders worth more than 100. HAVING repeats the expression SUM(oi.qty * oi.unit_price) because PostgreSQL doesn't allow the SELECT alias there (see below). It groups by o.order_id and o.placed_on; the date is functionally dependent on the key, so PostgreSQL would accept GROUP BY o.order_id alone, but listing both works everywhere.
The second query is the standard way to find duplicates: group by the column that should be unique and keep groups with more than one row. STRING_AGG lists the names in each group, so you can see who shares a city. Replace city with an email address or any other column that should be unique, and you have a data-quality check. Article 33 shows how to delete the duplicates once you've found them.
Notice the customer with no city, Farah, isn't in the result. The NULL city forms a group of one, which HAVING COUNT(*) > 1 removes.
GROUP BY versus DISTINCT
A GROUP BY without aggregates returns one row per group, which is exactly what DISTINCT does:
SELECT DISTINCT category FROM products;
SELECT category FROM products GROUP BY category; -- same rows
Databases usually run both the same way. Use DISTINCT when you want unique rows, and GROUP BY when you're computing something per group. That makes the intent obvious to the next reader.
Errors and surprises
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- 1. A column that is neither grouped nor aggregated
SELECT category, name, COUNT(*) FROM products GROUP BY category;
-- 2. A SELECT alias used in HAVING (PostgreSQL rejects it)
SELECT category, COUNT(*) AS n FROM products GROUP BY category HAVING n > 1;
-- 3. No matching rows: GROUP BY returns no rows at all ...
SELECT category, COUNT(*) AS n FROM products WHERE price > 1000 GROUP BY category;
-- ... but a summary query without GROUP BY still returns one row
SELECT COUNT(*) AS n FROM products WHERE price > 1000;
psql:/workspace/solution.sql:20: ERROR: column "products.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT category, name, COUNT(*) FROM products GROUP BY categ...
^
psql:/workspace/solution.sql:23: ERROR: column "n" does not exist
LINE 1: ... COUNT(*) AS n FROM products GROUP BY category HAVING n > 1;
^
category | n
----------+---
(0 rows)
n
---
0
(1 row)
- A column that's neither grouped nor aggregated.
namehas several values per category. Add it toGROUP BYif you want one row per (category, name), or aggregate it, for example withSTRING_AGG(name, ', ')orMIN(name). - A
SELECTalias inHAVING.HAVINGis logically evaluated beforeSELECT, so the aliasndoesn't exist yet. PostgreSQL, SQL Server and Oracle before 23ai reject it, so repeat the expression:HAVING COUNT(*) > 1. MySQL, SQLite and Oracle 23ai accept the alias as an extension. - Empty input. When no rows reach
GROUP BY, there are no groups, so a grouped query returns no rows. A summary query withoutGROUP BYalways returns exactly one row, withCOUNT0 and NULL for the other aggregates. Code that expects "always one row" breaks when aGROUP BYis added.
Grouping and collations
GROUP BY puts values into the same group when the column's collation considers them equal. In PostgreSQL's default, deterministic collations, 'Pune', 'pune' and 'PUNE' are three groups. In MySQL's default utf8mb4_0900_ai_ci collation, which ignores case and accents, they're one group, and the group is shown with one of the spellings. SQL Server's common default collations are case-insensitive too. If your counts look different between databases, check the collation. To make grouping case-insensitive explicitly, group by LOWER(city) and select LOWER(city) too.
What's current
- MySQL 8.0 removed the implicit sorting of
GROUP BYresults and the oldGROUP BY col DESCsyntax. AddORDER BYif you need an order. - Oracle 23ai accepts
SELECTaliases inGROUP BYandHAVING, and column positions when thegroup_by_position_enabledparameter is set. Earlier versions rejected both. - SQL standardized
ANY_VALUE, which PostgreSQL added in version 16, and which is the clean way to select a value that's the same for every row in a group. - Functional dependence on a primary key is supported by PostgreSQL (since 9.1) and MySQL (since 5.7), but not by Oracle or SQL Server.
Common questions
What's the difference between WHERE and HAVING?
WHERE filters rows before grouping and can't use aggregates. HAVING filters groups after aggregation and can. Put row conditions in WHERE and aggregate conditions in HAVING.
Does GROUP BY sort the result?
No. It may look sorted when the database groups by sorting, but that isn't guaranteed and often isn't the case when it groups by hashing. Use ORDER BY.
Can I use a SELECT alias in GROUP BY, HAVING or ORDER BY?
ORDER BY: yes, everywhere. GROUP BY: in PostgreSQL, MySQL, SQLite and Oracle 23ai, but not SQL Server. HAVING: in MySQL, SQLite and Oracle 23ai. Repeating the expression always works.
How are NULLs grouped?
All NULLs in a grouping column form one group, even though NULL = NULL isn't true in a WHERE condition.
Why does my count show 1 for customers who have no orders?
You're using COUNT(*) after a LEFT JOIN. The customer gets one row padded with NULLs, and COUNT(*) counts it. Use COUNT(o.order_id).
Must I put every selected column in GROUP BY?
Every column that isn't inside an aggregate, yes, with one exception: in PostgreSQL and MySQL, columns that depend on a grouped primary key can be left out. Listing them anyway works everywhere.
Is GROUP BY faster than DISTINCT?
They're usually executed the same way. Choose based on what you mean.
Can I group by a column that isn't in the SELECT list?
Yes. SELECT COUNT(*) FROM products GROUP BY category returns one count per category without showing which category each is, which is rarely useful but legal.
Why are some weeks or months missing from my report?
GROUP BY only creates groups for values that exist. A month with no rows has no group. Generate the full list of periods and outer-join to it (article 41).
Summary
GROUP BYsplits rows into groups that share the same values, and aggregates are computed once per group. The result has one row per group.- Every selected expression must be a grouping column, an aggregate, or built from them. PostgreSQL and MySQL also allow columns that depend on a grouped primary key.
- All NULLs form one group.
WHEREfilters rows before grouping.HAVINGfilters groups after aggregation, and is where conditions on aggregates go.- After an outer join, count a column from the optional table, not
*. - You can group by expressions such as
CASEbands and truncated dates. GROUP BYdoesn't sort, and a grouped query returns no rows when no rows match.GROUP BY col HAVING COUNT(*) > 1finds duplicate values.
Practice questions
Write a query that returns each order status and how many orders have it, most common first.
Answer
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC, status;
On the course data, shipped has 3 orders and cancelled, delivered and pending have 1 each. The second sort key, status, makes the order of the ties predictable.
What's wrong with this query, and how do you fix it? SELECT category, AVG(price) FROM products WHERE AVG(price) > 100 GROUP BY category;
Answer
An aggregate can't be used in WHERE, because WHERE runs before the groups exist. Move the condition to HAVING:
SELECT category, AVG(price)
FROM products
GROUP BY category
HAVING AVG(price) > 100;
On the course data, only tents (average 369.50) qualify.
A report lists every customer with their number of orders, using LEFT JOIN orders and COUNT(*). Customers with no orders show 1. Why, and what's the fix?
Answer
A LEFT JOIN gives a customer with no orders one row whose order columns are NULL. COUNT(*) counts that row. COUNT(o.order_id) counts only non-null order IDs, so it returns 0 for those customers. Change COUNT(*) to COUNT(o.order_id).
Write a query that finds email addresses used by more than one row in a table subscribers(id, email), ignoring differences in letter case.
Answer
SELECT LOWER(email) AS email, COUNT(*) AS copies
FROM subscribers
GROUP BY LOWER(email)
HAVING COUNT(*) > 1
ORDER BY copies DESC;
Grouping by LOWER(email) puts Ann@x.com and ann@x.com in one group. Selecting LOWER(email) is allowed because it matches the grouping expression exactly.
What's the difference between these two queries? (1) ... WHERE price < 100 GROUP BY category and (2) ... GROUP BY category HAVING MAX(price) < 100, both selecting category, COUNT(*).
Answer
Query 1 removes expensive products first and then counts the cheap products in each category. A category with some cheap and some expensive products still appears, with only its cheap products counted. On the course data it returns lighting 2, packs 2 and clothing 1.
Query 2 counts all products per category and keeps only the categories whose most expensive product is under 100, so the whole category must be cheap. It returns the same three categories here, with the same counts, because every product in those categories is under 100. Add a 150.00 pack and they differ: query 1 still shows packs with 2, and query 2 drops packs.
SELECT city, COUNT(*) FROM customers GROUP BY city HAVING COUNT(*) > 1 doesn't list customers with no city. Why not?
Answer
The customers with a NULL city do form a group, but on the course data there's only one of them, so HAVING COUNT(*) > 1 removes that group. If there were two customers with no city, they would appear as one group with a NULL city and a count of 2, because GROUP BY puts all NULLs in one group.
Previous: SQL Aggregate Functions: COUNT, SUM, AVG, MIN and MAX
Next: Subtotals and Grand Totals With ROLLUP, CUBE and GROUPING SETS

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.