SQL query patterns reference
Common SQL problems grouped by the operation and result shape involved.
Filtering and result shape
SELECT determines the output columns; WHERE selects rows; ORDER BY defines result order. DISTINCT removes duplicate output rows, not necessarily duplicate business entities. NULL tests use IS NULL or IS NOT NULL rather than equality with NULL.
Relationships and result grain
INNER JOIN keeps matched row combinations; LEFT JOIN also retains unmatched rows from its left side. One-to-many joins can multiply rows and inflate aggregates. EXISTS and NOT EXISTS test whether related rows exist without adding their columns to the result.
Analytical queries
Window functions support latest-row-per-group, top-N-per-group, running totals and previous/next event comparisons while retaining detail rows. CTEs name intermediate results. A deterministic latest-row result needs an ordering rule that resolves ties.
Transactional writes
INSERT, UPDATE and DELETE change data. Transactions group changes for commit or rollback; constraints enforce rules such as keys, uniqueness and required values. The affected-row scope and concurrent transaction behavior are separate from whether a statement is syntactically valid.
Data-quality checks
Orphan rows, duplicate business keys, mismatched payment totals and differences between expected and actual sets are distinct query patterns. A zero-row result represents success only when the query describes invalid states in the intended data scope.
Detailed references
| Pattern | Material |
|---|---|
| Filtering and NULL | Filtering, boolean logic, NULL and patterns |
| Relationships | JOINs and multi-table relationships |
| Aggregation | Aggregates, GROUP BY and HAVING |
| Analytical SQL | Window functions |
| Writes and transactions | INSERT, UPDATE, DELETE and transactions |
| Integrity and reconciliation | SQL for QA and data validation |