How would you retrieve the top 3 salaries from the employees table?
💡 Model Answer
To retrieve the top three salaries from an employees table, you can use the ORDER BY clause with a limiting construct. In ANSI‑SQL, SELECT salary FROM employees ORDER BY salary DESC LIMIT 3; returns the three highest salaries, including duplicates. If you want distinct top salaries, add DISTINCT: SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 3;. In SQL Server, use TOP 3: SELECT TOP 3 salary FROM employees ORDER BY salary DESC;. In Oracle, use FETCH FIRST 3 ROWS ONLY: SELECT salary FROM employees ORDER BY salary DESC FETCH FIRST 3 ROWS ONLY;. These queries are efficient because the database can use an index on the salary column to quickly locate the highest values. If the table is large, ensure the index is maintained and consider adding a covering index on (salary DESC) to avoid a full table scan. Another common pattern is to use a window function: SELECT salary FROM (SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS rn FROM employees) AS sub WHERE rn <= 3;. This works in PostgreSQL, SQL Server, and Oracle. If you need the top three distinct salaries, replace ROW_NUMBER() with DENSE_RANK() and filter on dr <= 3. Also, be mindful of NULL salaries; they will be sorted last. Finally, always test the query on a sample dataset to ensure it returns the expected results, especially when the salary column contains many duplicate values.
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