Top N rows per group
Get the latest or highest N rows for each category using ROW_NUMBER in a subquery.
Queries for PostgreSQL and other relational databases.
Loading snippets…
15 snippets
Get the latest or highest N rows for each category using ROW_NUMBER in a subquery.
Keep deleted rows but still enforce unique emails among active rows using a partial unique index.
Query an employee/manager or category hierarchy to any depth using WITH RECURSIVE.
Understand how the three ranking window functions treat ties, with one query that shows all three.
Turn row values into columns (for example monthly totals) using conditional aggregates, without crosstab.
Show each row's share of the grand total or of its group without a self-join.
Compute a 7-day rolling average with AVG over a ROWS BETWEEN frame.
Filter on JSONB fields with the containment operator and make it fast with a GIN index.
Produce a row for every day in a range and left join your data so days with no activity show zero.
A reusable PostgreSQL trigger function that sets updated_at to now() on every UPDATE.
Insert a row or update it if the unique key already exists, atomically and safely under concurrency.
Compute cumulative sums per group without self-joins using SUM() OVER (PARTITION BY ... ORDER BY ...).