The snippet library.
Small, practical examples. Search by task or narrow things down below.
Attach an overall count to every row
Postgres: An uncorrelated scalar subquery supplies the same aggregate to each output row.
Postgres✓ Tested
Build a query from several named stages
Postgres: Separate row selection from aggregation using two common table expressions.
Postgres✓ Tested
Compare a row with its own group average
Postgres: A correlated aggregate computes a different comparison value for each group.
Postgres✓ Tested
Find the second-highest distinct value
Postgres: Select the maximum below the overall maximum to skip ties at the top.
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
Read a page after a known unique key
Postgres: A keyset predicate avoids scanning and discarding an increasing offset on a suitable index.
Postgres✓ Tested
Report duplicate business values and their frequency
Postgres: Group by a candidate business key and retain only groups with multiple rows.
Postgres✓ Tested
Return all rows tied for the maximum in a group
Postgres: An equality comparison with a grouped maximum retains ties rather than choosing one arbitrary row.
Postgres✓ Tested
Sort preferred rows ahead of other rows
Postgres: A CASE ordering key expresses business priority before a stable secondary sort.
Postgres✓ Tested