TGViewer
Data Analytics Data Analytics @sqlspecialist · 111K subscribers
Post #2429 11.9K
✅ SQL Interview Challenge – Filter Top N Records per Group 🧠💾

🧑‍💼 Interviewer: How would you fetch the top 2 highest-paid employees per department?

👨‍💻 Me: Use ROW_NUMBER() with a PARTITION BY clause—it's a window function that numbers rows uniquely within groups, resetting per partition for precise top-N filtering.

🔹 SQL Query:
SELECT *
FROM (
SELECT name, department, salary,
ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn
FROM employees
) AS ranked
WHERE rn <= 2;


✔ Why it works:
– PARTITION BY department resets row numbers (starting at 1) for each dept group, treating them as mini-tables.
– ORDER BY salary DESC ranks highest first within each partition.
– WHERE rn <= 2 grabs the top 2 per group—subquery avoids duplicates in complex joins!

💡 Pro Tip: Swap to RANK() if ties get equal ranks (e.g., two at #1 means next is #3, but you might get 3 rows); DENSE_RANK() avoids gaps. For big datasets, this scales well in SQL Server or Postgres.

💬 Tap ❤️ for more!
  • ❤ 18
  • 👍 1
More from @sqlspecialist
  1. Oct 13, 2026📊 Data Analyst Interview Series — Part 9 Guys, let's continue our Data Analyst Interview…
  2. Oct 13, 2026𝗧𝗢𝗣 𝗙𝗥𝗘𝗘 𝗖𝗢𝗨𝗥𝗦𝗘𝗦 𝗧𝗢 𝗕𝗢𝗢𝗦𝗧 𝗬𝗢𝗨𝗥 𝗦𝗞𝗜𝗟𝗟𝗦 𝗜𝗡 𝟮𝟬𝟮𝟲! Explor…
  3. Oct 12, 20268️⃣ You receive a dataset with inconsistent date formats. How would you clean it? Sample A…
  4. Oct 12, 2026📊 Data Analyst Interview Series — Part 7 Guys, let's continue our Data Analyst Interview…
  5. Oct 12, 2026🚀 𝗪𝗵𝗶𝗰𝗵 𝗧𝗲𝗰𝗵 𝗦𝗸𝗶𝗹𝗹 𝗪𝗶𝗹𝗹 𝗬𝗼𝘂 𝗠𝗮𝘀𝘁𝗲𝗿 𝗶𝗻 𝟮𝟬𝟮𝟲? Want to buil…
  6. Oct 9, 2026“Here, the data is sorted by the second column in descending order and the first five rows…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →