← 30 Days of SQL
Day 2 / 30Basics

ORDER BY, LIMIT and DISTINCT

Sorting and deduplicating data — asked in almost every first-round SQL interview.

1
Easy

How do you sort employees by salary in descending order?

SQL Answer
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.

2
Easy

Write a query to get the top 5 highest-paid employees.

SQL Answer
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.

3
Easy

How do you get unique department names from the employees table?

SQL Answer
SELECT DISTINCT department
FROM employees;
💡

DISTINCT removes duplicate values. If you SELECT DISTINCT on multiple columns, it returns unique combinations of all selected columns.

4
Medium

Get the 2nd highest salary from the employees table.

SQL Answer
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;

5
Hard

How do you get the Nth highest salary?

SQL Answer
-- 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.

6
Easy

Write a query to count the number of distinct departments.

SQL Answer
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 →
← PREVIOUSDay 1: SQL Basics — SELECT, FROM, WHERENEXT →Day 3: LIKE, IN, BETWEEN and IS NULL
Best Data Analytics Course in Noida Delhi NCR | EVIKA ACADEMY