Example 1
Get each customer's single highest-value order
Alice has two orders: 101 (amount 50) and 105 (amount 120). The goal is to keep only the highest-amount order per customer. For PostgreSQL, DISTINCT ON (customer_id) groups rows by customer_id and returns the first row from each group in the order defined by ORDER BY customer_id, amount DESC — so for Alice, the row with amount 120 comes first and is kept. Bob's highest-amount order is 102 (80 > 35). Carol has only one order. For all other engines, the ROW_NUMBER() window function assigns rank 1 to the highest-amount row within each customer_id partition; the outer query filters to rn = 1. Both approaches produce the same three rows. The ROW_NUMBER approach generalizes to any engine supporting window functions; the DISTINCT ON approach is more concise but PostgreSQL-only.
CREATE TABLE orders (
customer_id INT,
customer_name VARCHAR(20),
order_id INT,
amount INT
);
INSERT INTO
orders
VALUES
(1, 'Alice', 101, 50),
(1, 'Alice', 105, 120),
(2, 'Bob', 102, 80),
(2, 'Bob', 106, 35),
(3, 'Carol', 103, 200);SELECT
customer_id,
customer_name,
order_id,
amount
FROM
(
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY
customer_id
ORDER BY
amount DESC
) AS rn
FROM
orders
) t
WHERE
rn = 1
ORDER BY
customer_id;| customer_id | customer_name | order_id | amount |
|---|---|---|---|
| 1 | Alice | 105 | 120 |
| 2 | Bob | 102 | 80 |
| 3 | Carol | 103 | 200 |
CREATE TABLE orders (
customer_id INT,
customer_name VARCHAR(20),
order_id INT,
amount INT
);
INSERT INTO
orders
VALUES
(1, 'Alice', 101, 50),
(1, 'Alice', 105, 120),
(2, 'Bob', 102, 80),
(2, 'Bob', 106, 35),
(3, 'Carol', 103, 200);SELECT DISTINCT
ON (customer_id) customer_id,
customer_name,
order_id,
amount
FROM
orders
ORDER BY
customer_id,
amount DESC;| customer_id | customer_name | order_id | amount |
|---|---|---|---|
| 1 | Alice | 105 | 120 |
| 2 | Bob | 102 | 80 |
| 3 | Carol | 103 | 200 |
PostgreSQL uses DISTINCT ON (customer_id) with ORDER BY customer_id, amount DESC. All other engines use a ROW_NUMBER() subquery with PARTITION BY customer_id ORDER BY amount DESC. Results are identical.