FIND YOUR NEXT FEW LINES

The snippet library.

Small, practical examples. Search by task or narrow things down below.

125 snippets foundClear filters
PostgresBulk changes & set operations

Find rows shared by two query results

Postgres: INTERSECT compares complete selected rows and removes duplicates.

Postgres✓ Tested
PostgresSubqueries & ranked selection

Find the second-highest distinct value

Postgres: Select the maximum below the overall maximum to skip ties at the top.

Postgres✓ Tested
PostgresDates & series

Format a timestamp with to_char

Produce a fixed numeric date string.

to_char✓ Tested
PostgresDates & series

Generate a sequence of numbers

Create rows without a stored table.

generate_series✓ Tested
PostgresRelationships & missing data

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
PostgresRows & writes

Get the latest row in each group

Select one ordered row per key with DISTINCT ON.

DISTINCT ON✓ Tested
PostgresGetting Started

Give a result column a readable name

Postgres: Use AS to label a computed result column.

Postgres✓ Tested
PostgresReporting & grouped calculations

Group by more than one field

Postgres: Each distinct combination of grouping fields produces its own row.

Postgres✓ Tested
PostgresSubqueries & ranked selection

Include every row tied for the highest score

Postgres: Compare with MAX rather than limiting to an arbitrary number of rows.

Postgres✓ Tested
PostgresSubqueries & ranked selection

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
PostgresRelationships & missing data

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
PostgresBulk changes & set operations

Increment a stored value in the database

Postgres: An in-database arithmetic update avoids a separate application read-modify-write step.

Postgres✓ Tested