Skip to content
Quantoros

Return the transactionid of the extra duplicate rows that should be removed - for each (accountid, transactiondate,…

SQLLevel: IntermediateCore interview patterns

Return the transaction_id of the extra duplicate rows that should be removed - for each (account_id, transaction_date, amount) group that appears more than once, keep the lowest transaction_id and return the rest. Interviewers explicitly reward calling out NULL and duplicate handling.

Table definitions (from the source exercise):

CREATE TABLE transactions(transaction_id INTEGER PRIMARY KEY, account_id INTEGER, transaction_date TEXT, amount REAL, merchant_category TEXT);
Hints
  • Distinguish a missing value from zero, an empty string and false.
  • Test comparison, aggregation and filtering on a tiny missing-value example.

Answer

Approach: ROW_NUMBER() OVER (PARTITION BY the natural key ORDER BY transaction_id); rows with rn > 1 are the extras.

SELECT transaction_id
FROM (
  SELECT transaction_id,
         ROW_NUMBER() OVER (PARTITION BY account_id, transaction_date, amount
                            ORDER BY transaction_id) AS rn
  FROM transactions
) x
WHERE rn > 1;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions