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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `sensor_readings` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.