SQL Syntax Quick Reference

Reference — Print-friendly

Standard SQL query shape and execution order. Written order differs from meaning order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.

Query Shape

SELECT [DISTINCT] A1, A2, ...        -- projection (keeps duplicates unless DISTINCT)
FROM r1 [JOIN TYPE] r2 ON pred       -- meaning order: FROM → WHERE → GROUP BY → HAVING → SELECT
WHERE predicate                      -- unknown rows dropped like false
GROUP BY A1 [, A2]
HAVING group_predicate               -- filters groups after grouping
ORDER BY A [ASC|DESC] [NULLS FIRST|LAST]

Joins

Form Behavior
JOIN ... ON pred Arbitrary predicate; filters before outer-padding
LEFT/RIGHT/FULL OUTER JOIN Pads unmatched rows with NULLs
NATURAL JOIN Equates ALL shared attributes — risky if schema gains columns
JOIN ... USING (A) Equates only named attributes

Aggregation

Construct Notes
COUNT(*) / COUNT(col) / COUNT(DISTINCT col) COUNT(col) ignores NULLs
SUM, AVG, MIN, MAX Ignore NULLs (AVG = SUM/COUNT non-null)
GROUP BY + HAVING HAVING filters groups; WHERE filters rows before grouping

Nulls & Three-Valued Logic

NULL = NULL is UNKNOWN, not TRUE. Use IS NULL / IS NOT NULL. WHERE keeps only TRUE rows; UNKNOWN is dropped like FALSE.

Window Functions

SELECT rank() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
FROM instructor;

PARTITION BY groups; ORDER BY inside OVER orders within each partition.