๐ง SQL Interview Question (ModerateโTricky & Duplicate Detection + Latest Record)
๐
employees(emp_id, email, updated_at)
โ Ques :
๐ Find duplicate emails, but return only the latest record for each duplicate email.
๐งฉ How Interviewers Expect You to Think
โข Identify duplicates using COUNT() ๐
โข Use window functions for ranking
โข Partition by email
โข Order by latest timestamp
โข Filter only duplicates + latest row
๐ก SQL Solution
SELECT emp_id, email, updated_at
FROM (
SELECT
emp_id,
email,
updated_at,
COUNT(*) OVER (PARTITION BY email) AS cnt,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC
) AS rn
FROM employees
) t
WHERE cnt > 1
AND rn = 1;
๐ฅ Why This Question Is Powerful
โข Tests window functions (COUNT OVER, ROW_NUMBER) ๐ง
โข Combines deduplication + ranking logic
โข Very common in data cleaning scenarios ๐งน
โข Real-world use case: keeping latest user records
โค๏ธ React if you want more such real interview-level SQL questions ๐
Post #2118
2.09K
- โค 7