SQL: DISTINCT applies to the whole row, not to one column

SELECT DISTINCT a, b removes duplicate PAIRS. It is not a way to pick one row per a - for that you need GROUP BY or a window function.

Code
SELECT DISTINCT customer_id, status FROM orders;
-- distinct COMBINATIONS, so a customer appears once per status

-- one row per customer, latest order:
SELECT DISTINCT ON (customer_id) customer_id, id, created_at
  FROM orders ORDER BY customer_id, created_at DESC;   -- PostgreSQL

-- portable version:
SELECT customer_id, id FROM (
  SELECT customer_id, id,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) rn
    FROM orders) t
 WHERE rn = 1;
Output
DISTINCT customer_id, status:
  7 | PAID
  7 | PENDING        <- same customer, twice

ROW_NUMBER filter:
  7 | 8821           <- one row per customer
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25