The snippet library.
Small, practical examples. Search by task or narrow things down below.
Find rows shared by two query results
Postgres: INTERSECT compares complete selected rows and removes duplicates.
Postgres✓ Tested
Find the second-highest distinct value
Postgres: Select the maximum below the overall maximum to skip ties at the top.
Postgres✓ Tested
Format a timestamp with to_char
Produce a fixed numeric date string.
to_char✓ Tested
Generate a sequence of numbers
Create rows without a stored table.
generate_series✓ Tested
Generate every combination of two sets
Postgres: CROSS JOIN creates one result per possible pair, so the output size is the product of the input sizes.
Postgres✓ Tested
Get the latest row in each group
Select one ordered row per key with DISTINCT ON.
DISTINCT ON✓ Tested
Give a result column a readable name
Postgres: Use AS to label a computed result column.
Postgres✓ Tested
Group by more than one field
Postgres: Each distinct combination of grouping fields produces its own row.
Postgres✓ Tested
Include every row tied for the highest score
Postgres: Compare with MAX rather than limiting to an arbitrary number of rows.
Postgres✓ Tested
Include missing values in a not-equal filter
Postgres: Ordinary inequality does not include NULL; explicitly include it when that is the intended rule.
Postgres✓ Tested
Include zero counts for missing relationships
Postgres: Count the non-null child key after a left join so a missing relationship produces zero.
Postgres✓ Tested
Increment a stored value in the database
Postgres: An in-database arithmetic update avoids a separate application read-modify-write step.
Postgres✓ Tested