Write a SQL query to find the fifth highest salary. If there are ties for the highest salaries (e.g., multiple employees earning 10k), those ties should not be counted; only distinct salaries should be considered.
💡 Model Answer
You can solve this with a subquery that selects distinct salaries ordered descending, then picks the fifth row. Example:
SELECT salary
FROM (
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
) AS distinct_salaries
LIMIT 1 OFFSET 4;
Alternatively, use DENSE_RANK():
SELECT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS dr
FROM employees
) AS ranked
WHERE dr = 5;
Both queries ignore ties because DISTINCT or DENSE_RANK() collapses duplicates. The first uses LIMIT/OFFSET; the second uses a window function. Complexity is O(n log n) due to sorting.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500