DISTINCT ON First Row Per Group

Keep the top row of every group with DISTINCT ON, where the leading ORDER BY columns decide which row survives and wrapping re-sorts the output.

SqlData Integrity

Code

snippet
-- DISTINCT ON (expr) 保留每个分组按 ORDER BY 排序后的第一行。
-- 规则:ORDER BY 必须以 DISTINCT ON 里的表达式开头,否则"第一行"没有定义。
SELECT DISTINCT ON (device_id)
    device_id,
    reading_at,
    temperature
FROM sensor_readings
ORDER BY device_id, reading_at DESC;

-- 想按别的列输出时,包一层再排序:内层定"每组取哪一行",外层定展示顺序
SELECT *
FROM (
    SELECT DISTINCT ON (device_id)
        device_id, reading_at, temperature
    FROM sensor_readings
    ORDER BY device_id, reading_at DESC
) AS latest
ORDER BY temperature DESC;

How it works

Several statements share this file — SELECT, with sensor_readings among the objects involved.

Mechanically, the statements are built from: an ORDER BY that fixes the output order; a DISTINCT qualifier that collapses duplicate rows.

Putting it to use

The sensor_readings table is the working surface here.

Core lines

SELECT *
FROM (
SELECT DISTINCT ON (device_id)
device_id, reading_at, temperature
FROM sensor_readings
ORDER BY device_id, reading_at DESC
) AS latest
ORDER BY temperature DESC;
SELECT DISTINCT ON (device_id)
device_id,
reading_at,
temperature
FROM sensor_readings
ORDER BY device_id, reading_at DESC;

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`sensor_readings` — referenced directly, no join needed.