PostgreSQL GROUP BY puts rows that share a value into one group, and an aggregate such as count() or sum() returns one number per group:
SELECT category, count(*) AS orders, sum(amount) AS total
FROM orders
GROUP BY category
ORDER BY total DESC;
Kitchen leads with $424.00. I ran every query here in psql on PostgreSQL 18.6, the 64-bit Windows build:
category | orders | total
----------+--------+--------
Kitchen | 3 | 424.00
Garden | 3 | 284.50
Books | 4 | 123.74
(3 rows)

The sample orders and customers tables
Ten orders, August to October 2026, five US customers. Five orders have no coupon. That matters later:
DROP TABLE IF EXISTS orders, customers CASCADE;
CREATE TABLE customers (
customer_id int PRIMARY KEY,
name varchar(20) NOT NULL,
state char(2) NOT NULL
);
INSERT INTO customers VALUES
(1, 'Megan Bowen', 'TX'), (2, 'Alex Wilber', 'CA'), (3, 'Adele Vance', 'WA'),
(4, 'Lee Gu', 'TX'), (5, 'Lidia Holloway', 'NY');
CREATE TABLE orders (
order_id int PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers,
category varchar(10) NOT NULL,
amount numeric(10,2) NOT NULL,
ordered_at date NOT NULL,
coupon varchar(10)
);
INSERT INTO orders VALUES
(101, 1, 'Books', 45.00, '2026-08-04', NULL),
(102, 2, 'Garden', 120.00, '2026-08-11', 'FALL10'),
(103, 1, 'Garden', 89.50, '2026-08-19', NULL),
(104, 3, 'Books', 32.25, '2026-09-02', 'FALL10'),
(105, 4, 'Kitchen', 210.00, '2026-09-09', NULL),
(106, 2, 'Books', 18.99, '2026-09-15', NULL),
(107, 5, 'Kitchen', 64.00, '2026-09-28', 'VIP5'),
(108, 1, 'Kitchen', 150.00, '2026-10-03', 'FALL10'),
(109, 3, 'Garden', 75.00, '2026-10-12', NULL),
(110, 4, 'Books', 27.50, '2026-10-20', 'VIP5');
Paste it into psql. New to this? See how to create a table in PostgreSQL first.
Postgres GROUP BY multiple columns (with a JOIN)
Each existing combination becomes a group. State comes from a JOIN to customers:
SELECT c.state, o.category, count(*) AS orders,
round(avg(o.amount), 2) AS avg_order
FROM orders o
JOIN customers c USING (customer_id)
WHERE c.state IN ('CA', 'TX')
GROUP BY c.state, o.category
ORDER BY c.state, o.category;
Output:
state | category | orders | avg_order
-------+----------+--------+-----------
CA | Books | 1 | 18.99
CA | Garden | 1 | 120.00
TX | Books | 2 | 36.25
TX | Garden | 1 | 89.50
TX | Kitchen | 2 | 180.00
(5 rows)
Texas splits into three rows. avg() needs round() or you get 16 decimals.
GROUP BY with HAVING vs WHERE
WHERE filters rows before grouping; HAVING filters groups after. Same orders, September on, totals over $100:
SELECT category, sum(amount) AS total
FROM orders
WHERE ordered_at >= '2026-09-01'
GROUP BY category
HAVING sum(amount) > 100
ORDER BY total DESC;
SELECT category, sum(amount) AS total
FROM orders
WHERE sum(amount) > 100
GROUP BY category;
Output and error:
category | total
----------+--------
Kitchen | 424.00
(1 row)
psql:group-by-having-vs-where.sql:11: ERROR: aggregate functions are not allowed in WHERE
LINE 3: WHERE sum(amount) > 100
^

Only Kitchen clears $100 after 09/01/2026. Put an aggregate in WHERE and you’ll get that error, because WHERE runs on single rows before any group exists.
PostgreSQL runs FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, then LIMIT. More filters in my PostgreSQL HAVING guide.
Group by order by in PostgreSQL: aggregate, alias or ordinal
Want sorted groups? You’ll need ORDER BY. Sort by an alias, a position or the aggregate itself:
SELECT customer_id, sum(amount) AS spent,
max(ordered_at) AS last_order
FROM orders
GROUP BY 1
ORDER BY spent DESC
LIMIT 3;
SELECT customer_id, max(ordered_at) AS last_order
FROM orders
GROUP BY customer_id
ORDER BY max(ordered_at) DESC
LIMIT 2;
Output:
customer_id | spent | last_order
-------------+--------+------------
1 | 284.50 | 2026-10-03
4 | 237.50 | 2026-10-20
2 | 138.99 | 2026-09-15
(3 rows)
customer_id | last_order
-------------+------------
4 | 2026-10-20
3 | 2026-10-12
(2 rows)
GROUP BY 1 means the first SELECT column. Megan (customer 1) spent the most: $284.50. Sorting on max(ordered_at) puts the latest buyer, Lee Gu, first.
Every sort option, NULLS LAST too, is in the PostgreSQL ORDER BY guide.
Group by month with date_trunc
You can group by an expression, and PostgreSQL accepts the output alias in GROUP BY:
SELECT date_trunc('month', ordered_at)::date AS month,
count(*) AS orders, sum(amount) AS total
FROM orders
GROUP BY month
ORDER BY month;
Output:
month | orders | total
------------+--------+--------
2026-08-01 | 3 | 254.50
2026-09-01 | 4 | 325.24
2026-10-01 | 3 | 252.50
(3 rows)
September is the busy month: four orders, $325.24. date_trunc() returns a timestamp, so the ::date cast drops the 00:00:00.
Why does PostgreSQL say a column must appear in the GROUP BY clause?
Every SELECT column must be grouped or aggregated. One exception: group by a table’s primary key and you’re free to select its other columns.
\set VERBOSITY verbose
SELECT c.customer_id, c.name, c.state, sum(o.amount) AS spent
FROM customers c
JOIN orders o USING (customer_id)
GROUP BY c.customer_id
ORDER BY spent DESC
LIMIT 2;
SELECT c.name, c.state, sum(o.amount) AS spent
FROM customers c
JOIN orders o USING (customer_id)
GROUP BY c.name;
Output and error:
customer_id | name | state | spent
-------------+-------------+-------+--------
1 | Megan Bowen | TX | 284.50
4 | Lee Gu | TX | 237.50
(2 rows)
psql:group-by-must-appear-error.sql:12: ERROR: 42803: column "c.state" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT c.name, c.state, sum(o.amount) AS spent
^
LOCATION: substitute_grouped_columns_mutator, parse_agg.c:1558

customer_id is the primary key, so name and state depend on it. c.name isn’t a key. Two customers could share it.
VERBOSITY verbose prints the SQLSTATE, 42803 (grouping_error). The fix: group on the key, or wrap the column in an aggregate.
Variations: NULL groups and the FILTER clause
All NULLs land in one group. And FILTER lets each aggregate pick its own rows:
SELECT coupon, count(*) AS orders
FROM orders
GROUP BY coupon
ORDER BY coupon NULLS FIRST;
SELECT category, count(*) AS orders,
count(*) FILTER (WHERE coupon IS NOT NULL) AS coupon_orders,
sum(amount) FILTER (WHERE amount >= 100) AS big_sales
FROM orders
GROUP BY category
ORDER BY category;
Output:
coupon | orders
--------+--------
| 5
FALL10 | 3
VIP5 | 2
(3 rows)
category | orders | coupon_orders | big_sales
----------+--------+---------------+-----------
Books | 4 | 2 |
Garden | 3 | 1 | 120.00
Kitchen | 3 | 2 | 360.00
(3 rows)

Watch out for Books: no order hit $100, so big_sales is NULL, not 0. Wrap it in coalesce() if you’d rather see zero.
It’s shorter than sum(CASE WHEN ... END), though a CASE expression still works.
GROUP BY ROLLUP for a grand total
ROLLUP adds a total row. grouping() returns 1 on it, so it sorts last:
SELECT coalesce(category, 'All') AS category, sum(amount) AS total
FROM orders
GROUP BY ROLLUP (category)
ORDER BY grouping(category), category;
Output:
category | total
----------+--------
Books | 123.74
Garden | 284.50
Kitchen | 424.00
All | 832.24
(4 rows)
The All row is $832.24. GROUPING SETS and CUBE give you several groupings in one pass.
Next step: for the top order per customer instead of a total, you’ll want ROW_NUMBER() over a partition.
Same task on other engines, plus two related reads:
- MariaDB GROUP BY with WITH ROLLUP
- COUNT with JOIN and GROUP BY in SQL Server
- string_agg(), the PostgreSQL GROUP_CONCAT
- PostgreSQL sum() with conditions
If you want to see the difference between COUNT(*), COUNT(column), and COUNT(DISTINCT column) inside your groups, my PostgreSQL COUNT function tutorial runs each one on the same table so you can see how NULLs change the result.
Frequently Asked Questions
Does GROUP BY sort the results in PostgreSQL?
No. The planner may use a HashAggregate, which returns groups in no particular order. Add ORDER BY whenever order matters.
What’s the difference between GROUP BY and DISTINCT?
GROUP BY with no aggregate returns the same rows as SELECT DISTINCT. Use GROUP BY when you need counts or sums per group.
What does GROUP BY DISTINCT do in PostgreSQL?
Added in PostgreSQL 14, it removes duplicate grouping sets that ROLLUP or CUBE combinations produce (SELECT reference).
What if a GROUP BY name matches both a table column and an alias?
GROUP BY picks the input column, while ORDER BY picks the output alias. Rename the alias to avoid surprises (table expressions docs).

Kumar Saurabh is a freelance software engineer who builds web and mobile apps with Next.js, React, Flutter and Python. From 2021 to 2024, Saurabh worked as an IT analyst and developer at TSInfo Technologies, writing technical articles on SQL and PostgreSQL. Saurabh writes the PostgreSQL, MySQL, MariaDB and MongoDB tutorials on DatabaseFAQs.com and holds a Master of Computer Applications (MCA) from Chandigarh University.