Query Structure
Learn SQL query structure with practical examples and guided drills on dbSyntax.
Start with Query StructureQuery Structure
The core SQL clauses and the order they execute. Written order is SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT. Logical orde...
SELECT
Choose which columns (or derived expressions) to return. The simplest clause in SQL, and the one most likely to silently break a downstream ...
FROM
Pick the source the query reads rows from: a table, a view, a subquery, or a CTE. Multiple comma-separated sources in FROM are an implicit c...
WHERE
Filter rows before grouping, window functions, or aggregation. WHERE runs early in logical order, so it can't reference column aliases from ...
ORDER BY
Sort the output rows. Runs after SELECT in logical order, so (unlike WHERE) it can reference column aliases and computed expressions. With L...
LIMIT
Cap the number of returned rows. Used during exploration to keep queries fast, and in production for pagination (with OFFSET). Without ORDER...
GROUP BY
Collapse rows into one output row per distinct combination of the grouping keys. Every column in SELECT must either appear in GROUP BY or be...
HAVING
Filter after aggregation. HAVING sees aggregate results (COUNT(*), SUM(total), AVG(x)) that WHERE cannot, because WHERE runs before GROUP BY...
UNION / UNION ALL
Stack two result sets vertically. Both sides must have the same number of columns and compatible types. UNION deduplicates rows (a hash/sort...
INTERSECT / EXCEPT
Set operations on two result sets. INTERSECT returns rows in both sides; EXCEPT returns rows in the left side but not the right. Both dedupl...