The snippet library.
Small, practical examples. Search by task or narrow things down below.
Find rows shared by two query results
SQL: INTERSECT compares complete selected rows and removes duplicates.
SQL✓ Tested
Find rows with a related record
Use EXISTS without duplicating the outer rows.
EXISTS✓ Tested
Find the second-highest distinct value
SQL: Select the maximum below the overall maximum to skip ties at the top.
SQL✓ Tested
Generate every combination of two sets
SQL: CROSS JOIN creates one result per possible pair, so the output size is the product of the input sizes.
SQL✓ Tested
Give a result column a readable name
SQL: Use AS to label a computed result column.
SQL✓ Tested
Group by more than one field
SQL: Each distinct combination of grouping fields produces its own row.
SQL✓ Tested
Include every row tied for the highest score
SQL: Compare with MAX rather than limiting to an arbitrary number of rows.
SQL✓ Tested
Include missing values in a not-equal filter
SQL: Ordinary inequality does not include NULL; explicitly include it when that is the intended rule.
SQL✓ Tested
Include zero counts for missing relationships
SQL: Count the non-null child key after a left join so a missing relationship produces zero.
SQL✓ Tested
Increment a stored value in the database
SQL: An in-database arithmetic update avoids a separate application read-modify-write step.
SQL✓ Tested
Insert a row with named columns
Add a record without relying on implicit column order.
INSERT✓ Tested
Insert only keys absent from a destination
SQL: NOT EXISTS supports a set-based missing-row insert in a single-writer example.
SQL✓ Tested