SQL

DISTINCT ON: last row per key in a single pass

PostgreSQL-specific: DISTINCT ON keeps the first row of each group per the ORDER BY — often faster than ROW_NUMBER with the right index.

Prerequisites

PostgreSQL — ROW_NUMBER() = 1 sur les autres moteurs

SQL
SELECT DISTINCT ON (user_id)
    user_id,
    event_type,
    created_at
FROM user_events
ORDER BY user_id, created_at DESC;
-- L'ORDER BY doit commencer par les colonnes du DISTINCT ON
-- Index conseillé : user_events (user_id, created_at DESC)

Result

 user_id | event_type  |     created_at
---------+-------------+---------------------
     101 | purchase    | 2026-06-10 11:42:08
     102 | view_page   | 2026-06-10 09:15:33
     103 | add_to_cart | 2026-06-09 22:01:54
     104 | login       | 2026-06-08 07:30:12
(4 rows)   -- exactement 1 ligne par user : son dernier événement
SQLDISTINCT ONPostgreSQLDernière ligne

Related snippets

Back to the Data Lab