SQL Querying
Logical Query Processing
A SQL query is understood as a sequence of logical transformations, even though its clauses are written in a different order. This model explains name visibility and result semantics; it does not prescribe the optimizer's physical execution plan.
FROMand joins establish the input row source before row filtering.WHEREfilters rows, whileHAVINGfilters groups.- Window calculations observe the grouped, filtered row set without collapsing it.
SELECTcomputes the output expressions;DISTINCTthen removes duplicate output rows.ORDER BYestablishes presentation order, and row limiting chooses a slice of that ordered result.- Logical order is not physical execution order.
Read a query in semantic order
| Logical stage | What exists | Consequence |
|---|---|---|
FROM, ON, joins | Input rows and join matches | Outer joins may add null-extended rows |
WHERE | Joined rows | Only predicate result TRUE survives |
GROUP BY, aggregates | One logical group per grouping key | Detail rows collapse into group results |
HAVING | Groups and aggregate values | Whole groups are retained or removed |
| Windows | Rows after grouping and HAVING | Analytics are added without further grouping |
SELECT | Projected expressions and aliases | Aliases become available to later stages |
DISTINCT | Projected rows | Duplicate projected rows are eliminated |
ORDER BY | Final result expressions | A deterministic sequence requires a total tie-breaker |
| Limiting | Ordered result | A requested prefix or page is selected |
SELECT o.customer_id, SUM(i.quantity * i.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.status = 'PAID'
GROUP BY o.customer_id
HAVING SUM(i.quantity * i.unit_price) >= 1000
ORDER BY revenue DESC, o.customer_id;For the sample query, joins first form paid-order line rows, WHERE removes non-paid orders, grouping forms one group per customer, and HAVING keeps groups totaling at least 1000. Projection names the total revenue; ordering then sorts totals and uses customer_id to break ties.