The Unity Catalog table sales.customers contains multiple records for some customers. The rows for the same customer_id differ in other columns, as shown in the exhibit. You need a query that returns every column and exactly one row per customer_id: the row that has the most recent updated_at value. Customers that appear only once must also be returned.
| customer_id | name | updated_at | status | |
|---|---|---|---|---|
| 1001 | jane@contoso.com | Jane Doe | 2024-01-15 | Active |
| 1001 | jane@contoso.com | Jane D. | 2024-03-20 | Active |
| 1002 | bob@fabrikam.com | Bob Smith | 2024-02-10 | Pending |
| 1002 | bob@fabrikam.com | Robert Smith | 2024-02-11 | Active |
| 1003 | ana@contoso.com | Ana Silva | 2024-02-01 | Active |
Which query should you use?
The rows for each customer differ in columns such as name and status, so a whole-row DISTINCT cannot collapse them. You must choose which duplicate survives. ROW_NUMBER() partitioned by customer_id and ordered by updated_at descending, filtered with QUALIFY to row number 1, keeps the most recently updated row for every customer. The COUNT-based queries only identify duplicates.
- Not correct:
SELECT DISTINCT * FROM sales.customers;. DISTINCT deduplicates only rows that are identical across all columns. Rows such as Jane Doe and Jane D. differ, so both stay. - Not correct:
SELECT customer_id, COUNT(*) AS occurrence_count FROM sales.customers GROUP BY customer_id HAVING COUNT(*) > 1;. GROUP BY with HAVING finds duplicate keys and their counts. It does not return the full rows and leaves out customers that appear only once. - Not correct:
SELECT * FROM sales.customers QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at ASC) = 1;. Ascending order makes row number 1 the oldest row in each partition, so the earliest record is kept instead of the latest. - Not correct:
SELECT * FROM sales.customers QUALIFY COUNT(*) OVER (PARTITION BY customer_id) > 1;. This pattern identifies duplicates: it retains every row belonging to a repeated customer_id and excludes customers that appear only once. It does not select the latest row per customer. - Correct:
SELECT * FROM sales.customers QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) = 1;. Numbering the rows in each customer_id partition by updated_at descending and keeping number 1 returns all columns of the most recently updated row for each customer, including customers with one row.