Launch price: every exam for $29.99 a year, for the first 300 buyers. See the price

CertStreak
Menu

Identify and resolve duplicate, missing, and null values

A worked example

Single answer

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_idemailnameupdated_atstatus
1001jane@contoso.comJane Doe2024-01-15Active
1001jane@contoso.comJane D.2024-03-20Active
1002bob@fabrikam.comBob Smith2024-02-10Pending
1002bob@fabrikam.comRobert Smith2024-02-11Active
1003ana@contoso.comAna Silva2024-02-01Active

Which query should you use?

Choose one answer
Why

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.

Practise this topic until it's automatic.

Ten questions a day, every answer explained, and misses that come back until you beat them.

Start free