Vol. I · A Postgres HandbookTwelve chapters · · 756 queries

The Query & the Schema

A reading-room reference for writing PostgreSQL by hand — selects to window functions, with the schema in plain view.

FrontChaptersSchemaColophon
Chapters · WHERE & Filtering · Query 014 / 030
IntermediateWHERE & Filtering

Find customers with more than 3 orders

The query

SQL
SELECT cust_id, COUNT(*) AS order_count
FROM orders
GROUP BY cust_id
HAVING COUNT(*) > 3
ORDER BY order_count DESC;
Tested against PostgreSQL 16

Note

“HAVING on aggregates is the correct approach. Never use WHERE for aggregate conditions.

Tables referenced

  • orders6 cols

← Previous

Filter using HAVING with GROUP BY

Next →

Find employees with email matching company domain

The Query & the Schema

Set in Fraunces and Inter Tight. Printed on parchment, in oxblood and ink. No tracking, no accounts, no JavaScript on the answer pages beyond what your browser needs to copy a query.

Compiled for Postgres 16 · MMXXVI