bhylu.com

Advertisements

SQL Having

HAVING filters groups after aggregation. WHERE filters individual input rows before they form groups. A report can need both, and moving a condition from one to the other can change the answer.

Understand the idea

We first exclude cancelled orders with WHERE. Then we group by customer and keep only groups whose total reaches 2000 cents. The HAVING condition uses an aggregate because it asks about several rows together. Writing the aggregate explicitly avoids relying on engine-specific alias rules.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

SELECT customer_id, SUM(total_cents) AS committed_cents
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING SUM(total_cents) >= 2000
ORDER BY customer_id;

Read the result

Only customer 1 remains, with 3200 cents across a paid and a pending order. The name committed_cents is deliberately different from paid revenue.

Try one change

Require at least two non-cancelled orders as well as the amount threshold. Check that both group conditions hold.