// SQL snippet

Deduplicate SELECT output

DISTINCT for value sets, ROW_NUMBER for full-row dedupe with a survivor policy.

Main statement
All engines

The task

Your joined query repeats the same customer/status combination many times, and you want each combination once.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT DISTINCT customer_id, status
FROM orders
ORDER BY customer_id, status;

Como funciona

DISTINCT compares the whole selected row list and removes exact duplicates after the fact. It cannot pick which of two different rows survives, because it only sees the selected columns. When a row can differ in the unselected columns and you want one deterministic survivor per key, dedupe with ROW_NUMBER instead.

Variations

Keep one full row per key

WITH ranked AS (
  SELECT o.*,
         ROW_NUMBER() OVER (PARTITION BY customer_id, order_date
                            ORDER BY id) AS rn
  FROM orders o
)
SELECT id, customer_id, order_date, amount, status
FROM ranked
WHERE rn = 1;

Questions that come up

Why does DISTINCT not remove rows that differ only in a column I left out?

Because deduplication happens on the projected column list only. Either add the column to the select list, or use the ROW_NUMBER variant to define exactly which row survives per key.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.