HAVING
Overview
WHERE filters individual rows before aggregation; HAVING filters the resulting groups. To identify repeat customers, group orders by customer and keep groups containing at least two rows.
First example
SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id HAVING COUNT(*) >= 2 ORDER BY customer_id;Observed SQLite result (rows in JSON):
[ [ 1, 2 ]]How it works
The second example uses a new grouping_sales fixture: six synthetic transactions in North, South and an unknown region. WHERE removes amounts below 50 before summation. HAVING then keeps totals of at least 100. North is 350; South is 80 and the unknown region has no remaining rows. The logical pipeline is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY; physical execution may differ.
Practical example
SELECT region, SUM(amount_cents) AS total FROM grouping_sales WHERE amount_cents >= 50 GROUP BY region HAVING SUM(amount_cents) >= 100 ORDER BY region;Observed SQLite result (rows in JSON):
[ [ "North", 350 ]]Practice and mistakes
Do not write WHERE COUNT(*) >= 2 at the same query level. Practice: change the second HAVING threshold to 80 and predict North and South. Use the aggregate expression rather than depending on dialect-specific aliases in HAVING.