Earliest row per key
Same recipe as latest-row, sorted the other way, plus the anti-join alternative.
The task
You want each customer's first-ever order, full row, to study acquisition behaviour.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
WITH ranked AS (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY order_date, id) AS rn
FROM orders o
)
SELECT id, customer_id, order_date, amount, status
FROM ranked
WHERE rn = 1;
Como funciona
Sorting the window ascending puts each customer's oldest order at number one. The id tiebreaker keeps the result stable when two orders landed on the same timestamp. The NOT EXISTS variant answers the same question without a window function: keep an order only if no earlier order (or same-time order with a lower id) exists for that customer.
Variations
Anti-join version
SELECT o.*
FROM orders o
WHERE NOT EXISTS (
SELECT 1
FROM orders o2
WHERE o2.customer_id = o.customer_id
AND (o2.order_date < o.order_date
OR (o2.order_date = o.order_date AND o2.id < o.id))
);
Questions that come up
When is the anti-join version better?
It runs on engines without window functions, such as MySQL 5.7. With an index on (customer_id, order_date, id) each NOT EXISTS probe is a short index seek, so it can beat the window version when customers have many orders each; without that index it degrades to a nested scan, and the window version, which sorts once, wins.
Keep reading
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.