The snippet library.
Small, practical examples. Search by task or narrow things down below.
Calculate each group’s integer percentage of the total
Postgres: Multiply before division and protect against a zero denominator.
Postgres✓ Tested
Calculate each group’s numeric spread
Postgres: Subtract MIN from MAX to report the difference between extremes.
Postgres✓ Tested
Check JSONB containment
Test whether an object contains a key-value pair.
jsonb✓ Tested
Collect ordered values into an array
Build a sorted array from query rows.
array_agg✓ Tested
Combine results while retaining duplicates
Postgres: UNION ALL does not spend work removing equal rows.
Postgres✓ Tested
Combine text values with a separator
Postgres: Use the concatenation operator supported by the selected SQL dialect.
Postgres✓ Tested
Commit multiple related changes together
Postgres: The first transaction prepares the fixtures. The second commits both updates as one unit.
Postgres✓ Tested
Compare a row with its own group average
Postgres: A correlated aggregate computes a different comparison value for each group.
Postgres✓ Tested
Compare a row with the previous row
Read a preceding value with LAG.
LAG✓ Tested
Compute an integer weighted average
Postgres: Multiply before summing and guard a zero total weight with NULLIF.
Postgres✓ Tested
Copy selected rows into another table
Postgres: INSERT SELECT performs a set-based copy with an explicit destination column list.
Postgres✓ Tested
Count distinct values within a result
Postgres: COUNT DISTINCT counts distinct non-null values.
Postgres✓ Tested