Clause semantics
Overview
Predict the result of a query by separating joining, filtering, grouping and projection. SQL describes the required result; a logical phase model explains its meaning rather than dictating the runtime algorithm.
First example
SELECT c.id,COUNT(o.id) FROM lq_customer c LEFT JOIN lq_order o ON o.customer_id=c.id AND o.status='paid' GROUP BY c.id ORDER BY c.id;Observed SQLite result (rows in JSON):
[ [ 1, 2 ], [ 2, 1 ], [ 3, 0 ], [ 4, 0 ]]How it works
Prerequisite: joins and grouping. FROM and JOIN establish the input; ON decides matches, and LEFT JOIN adds NULL-extended rows for unmatched left rows. WHERE then retains only true conditions, not false or unknown. GROUP BY forms groups; HAVING filters groups; the select list forms output values; DISTINCT removes duplicate output rows. In the first example, the paid predicate is in ON: Ada has two paid orders, Reza one, Sara and Mina have none. COUNT(o.id) counts matched orders, not the NULL placeholder. Moving the predicate into WHERE in the second example excludes both unmatched customers. A customer with only pending orders is not rescued by adding OR o.id IS NULL to WHERE. SELECT aliases are not generally available to earlier clauses; SQLite allows some alias references as extensions. Use a derived table for portable filtering of calculated values.
Practical example
SELECT c.id,COUNT(o.id) FROM lq_customer c LEFT JOIN lq_order o ON o.customer_id=c.id WHERE o.status='paid' GROUP BY c.id ORDER BY c.id;Observed SQLite result (rows in JSON):
[ [ 1, 2 ], [ 2, 1 ]]Practice and mistakes
Practice: return all customers and their paid totals, including zero. Hint 1: retain the paid condition in ON. Hint 2: use COALESCE(SUM(o.amount),0). Expected totals by ID: 250,250,0,0. Compare COUNT(*) with COUNT(o.id) for Sara; do not count a NULL-extended row as an order.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE lq_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);CREATE TEMP TABLE lq_order(id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES lq_customer(id), amount INTEGER NOT NULL CHECK(amount>=0), status TEXT NOT NULL CHECK(status IN ('paid','pending')));INSERT INTO lq_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara'),(4,'Mina');INSERT INTO lq_order VALUES(1,1,100,'paid'),(2,1,150,'paid'),(3,2,250,'paid'),(4,2,50,'pending'),(5,4,80,'pending'),(6,1,150,'pending');CREATE INDEX lq_order_amount ON lq_order(amount,id);CREATE INDEX lq_order_customer ON lq_order(customer_id);
SELECT c.id,COUNT(o.id) FROM lq_customer c LEFT JOIN lq_order o ON o.customer_id=c.id AND o.status='paid' GROUP BY c.id ORDER BY c.id;ROLLBACK;Expected result, not executed: [[1, 2], [2, 1], [3, 0], [4, 0]]