brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: SELECT DISTINCT ON gives you the newest row per group in PostgreSQL

Postgresql
~/tips/tip-database-postgresql-distinct-on

SELECT DISTINCT ON (sensor_id) sensor_id, recorded_at, temperature

Returns one row per group, such as the latest reading of each sensor, without a subquery.

“Give me the latest reading for each sensor” or “the last login of every user” sounds like a simple question, yet the usual answer is a subquery with max() and a join back to the same table. PostgreSQL has a shortcut I wish more people knew: DISTINCT ON.

It keeps the first row of every group, and ORDER BY decides which row counts as first:

SELECT DISTINCT ON (sensor_id) sensor_id, recorded_at, temperature
FROM readings
ORDER BY sensor_id, recorded_at DESC;

That returns one row per sensor_id: the one with the newest recorded_at, with all its other columns intact. You don’t need a subquery or a join, and two rows with the same maximum value don’t cause duplicates (you simply get one of them). Swap DESC for ASC and you get the oldest row per group instead. You can also group on more than one column, such as DISTINCT ON (host, service) for the last status of every service on every host.

The rule to remember is that the DISTINCT ON expressions must match the leftmost ORDER BY expressions. So sensor_id comes first in the ORDER BY, and the column that picks the winner comes after it. If you leave out ORDER BY altogether, PostgreSQL still returns one row per group, but which one is unpredictable. That’s the caveat that bites: the query runs without complaint and quietly gives you a random reading.

Two more things. DISTINCT ON is a PostgreSQL extension to the SQL standard, so the query won’t run on MySQL, MariaDB or SQLite; there you’d use a window function with row_number(). And on a big table, an index on (sensor_id, recorded_at DESC) helps a lot, because it matches the sort the query needs. EXPLAIN will tell you whether PostgreSQL uses it.

Further reading: PostgreSQL 17 docs: SELECT, DISTINCT clause

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link