ORDER BY, LIMIT and DISTINCT
Sorting and deduplicating data — asked in almost every first-round SQL interview.
How do you sort employees by salary in descending order?
SELECT * FROM employees
ORDER BY salary DESC;DESC sorts highest to lowest. ASC (default) sorts lowest to highest. You can sort by multiple columns: ORDER BY department ASC, salary DESC.
Write a query to get the top 5 highest-paid employees.
SELECT * FROM employees
ORDER BY salary DESC
LIMIT 5;LIMIT restricts the number of rows returned. In SQL Server use TOP 5 instead. In Oracle use ROWNUM or FETCH FIRST 5 ROWS ONLY.
How do you get unique department names from the employees table?
SELECT DISTINCT department
FROM employees;DISTINCT removes duplicate values. If you SELECT DISTINCT on multiple columns, it returns unique combinations of all selected columns.
Get the 2nd highest salary from the employees table.
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);Classic interview question. Alternative using LIMIT: SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1;
How do you get the Nth highest salary?
-- For Nth highest (e.g. 3rd):
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET N-1;
-- Example for 3rd highest:
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;OFFSET skips rows. OFFSET 0 = 1st row, OFFSET 1 = 2nd row, OFFSET N-1 = Nth row. This is a very common interview question at MNCs in Delhi NCR.
Write a query to count the number of distinct departments.
SELECT COUNT(DISTINCT department)
FROM employees;COUNT(DISTINCT column) counts unique non-NULL values. Different from COUNT(*) which counts all rows.
EVIKA ACADEMY · SQL FOR DATA ANALYTICS
Want to master SQL with live practice?
Join our SQL for Data Analytics course — live classes in Noida and online across India.
Book Free Demo Class →