Question presented to candidate: "Walk me through ROW_NUMBER, RANK and DENSE_RANK. If I have scores 95, 90, 90, 85, what does each one return, and why?"
What a strong answer should cover:
- All three are ranking window functions that number rows inside each partition by the window
ORDER BY; they differ only in how they treat ties (rows with equal sort values, called peers) ROW_NUMBERgives every row a distinct number (1, 2, 3, 4) and breaks ties arbitrarily unless theORDER BYis uniqueRANKgives peers the same number and then skips (1, 2, 2, 4): rank = 1 + number of rows strictly aheadDENSE_RANKgives peers the same number with no gap (1, 2, 2, 3): dense rank = 1 + number of distinct values strictly aheadPARTITION BYrestarts the numbering per group; NULL placement in the sort differs by engine (PostgreSQL puts NULL first inDESC, SQLite last), so sayNULLS LAST
Code / implementation expected: Yes β one query putting the three side by side over data with ties.
Schema used by the examples: