Query Practice Problems
Find the second highest salary.
Example
Using a subquery (works everywhere):
SELECT MAX(Salary) AS SecondHighest
FROM Employees
WHERE Salary < (SELECT MAX(Salary) FROM Employees);Result: 1 row
| SecondHighest |
|---|
| 72000 |
Example (window function)
Using DENSE_RANK (handles ties and generalises to N):
SELECT DISTINCT Salary AS SecondHighest
FROM (SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS r FROM Employees) t
WHERE r = 2;Result: 1 row
| SecondHighest |
|---|
| 72000 |
Find the Nth highest salary (N = 3).
Example
With LIMIT/OFFSET on distinct salaries:
SELECT DISTINCT Salary FROM Employees
ORDER BY Salary DESC
LIMIT 1 OFFSET 2;Result: 1 row
| Salary |
|---|
| 67000 |
Note: SQL Server: ORDER BY Salary DESC OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY.
Highest-paid employee in each department.
Example
Rank employees by salary inside each department and keep rank 1:
SELECT Department, FirstName, Salary
FROM (
SELECT Department, FirstName, Salary,
RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS r
FROM Employees
) t
WHERE r = 1;Result: 3 rows
| Department | FirstName | Salary |
|---|---|---|
| Finance | Fatima | 80000 |
| Sales | Rahul | 72000 |
| Support | James | 67000 |
Employees who earn more than their manager.
Example
First give Sara a raise above her manager (Rahul, 72000), then compare each employee with their manager:
UPDATE Employees SET Salary = 75000 WHERE EmployeeID = 2;
SELECT e.FirstName, e.Salary, m.FirstName AS Manager, m.Salary AS ManagerSalary
FROM Employees e
JOIN Employees m ON m.EmployeeID = e.ManagerID
WHERE e.Salary > m.Salary;Result: 1 row
| FirstName | Salary | Manager | ManagerSalary |
|---|---|---|---|
| Sara | 75000 | Rahul | 72000 |
Tip: In an interview, mention that you tested it with data where the answer is not empty, as done here with the UPDATE.
Find duplicate values in a column.
Example
Cities that appear more than once in Customers:
SELECT City, COUNT(*) AS Times
FROM Customers
WHERE City IS NOT NULL
GROUP BY City
HAVING COUNT(*) > 1;Result: 1 row
| City | Times |
|---|---|
| London | 2 |
Find missing IDs in a sequence.
Example
Generate the full range with a recursive CTE and anti-join (we delete order 104 first):
DELETE FROM Orders WHERE OrderID = 104;
WITH RECURSIVE ids(n) AS (
SELECT MIN(OrderID) FROM Orders
UNION ALL
SELECT n + 1 FROM ids WHERE n < (SELECT MAX(OrderID) FROM Orders)
)
SELECT n AS MissingOrderID
FROM ids
LEFT JOIN Orders o ON o.OrderID = ids.n
WHERE o.OrderID IS NULL;Result: 1 row
| MissingOrderID |
|---|
| 104 |
Customers who placed orders in consecutive months.
Example
Pair each month a customer ordered in with the next calendar month:
WITH m AS (
SELECT DISTINCT CustomerID, strftime('%Y-%m', OrderDate) AS Mon FROM Orders
)
SELECT a.CustomerID, a.Mon AS Month1, b.Mon AS Month2
FROM m a
JOIN m b ON b.CustomerID = a.CustomerID
AND b.Mon = strftime('%Y-%m', date(a.Mon || '-01', '+1 month'));Result: 1 row
| CustomerID | Month1 | Month2 |
|---|---|---|
| 1 | 2024-01 | 2024-02 |
Top 3 customers by total spending.
Example
Sum each customer’s orders and keep the three largest totals:
SELECT c.CustomerName, SUM(o.Amount) AS Spent
FROM Orders o
JOIN Customers c ON c.CustomerID = o.CustomerID
GROUP BY c.CustomerName
ORDER BY Spent DESC
LIMIT 3;Result: 3 rows
| CustomerName | Spent |
|---|---|
| Blue Harbor Foods | 412 |
| Cedar & Co | 320.75 |
| Aarav Traders | 301.75 |
Monthly revenue with a running total.
Example
Group by month, then run a window SUM over the grouped totals:
SELECT strftime('%Y-%m', OrderDate) AS Month,
SUM(Amount) AS Revenue,
SUM(SUM(Amount)) OVER (ORDER BY strftime('%Y-%m', OrderDate)) AS RunningRevenue
FROM Orders
GROUP BY Month
ORDER BY Month;Result: 4 rows
| Month | Revenue | RunningRevenue |
|---|---|---|
| 2024-01 | 335.4 | 335.4 |
| 2024-02 | 468.25 | 803.65 |
| 2024-03 | 497.75 | 1301.4 |
| 2024-04 | 198.4 | 1499.8 |
Tip: SUM(SUM(Amount)) OVER (...) applies a window function on top of the grouped result. Interviewers like this one.
Best-selling product in each category.
Example
Units sold per product, ranked within each category:
WITH Sold AS (
SELECT p.Category, p.ProductName, SUM(od.Quantity) AS Units
FROM OrderDetails od JOIN Products p ON p.ProductID = od.ProductID
GROUP BY p.Category, p.ProductName
)
SELECT Category, ProductName, Units
FROM (SELECT *, RANK() OVER (PARTITION BY Category ORDER BY Units DESC) AS r FROM Sold) t
WHERE r = 1;Result: 3 rows
| Category | ProductName | Units |
|---|---|---|
| Beverages | Espresso Beans 1kg | 18 |
| Grocery | Olive Oil 1L | 29 |
| Snacks | Dark Chocolate | 18 |
Percentage of orders handled by each employee.
Example
Count orders per employee and divide by the total number of orders:
SELECT COALESCE(e.FirstName, '(no employee)') AS Employee,
COUNT(*) AS Orders,
ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM Orders), 1) AS Pct
FROM Orders o
LEFT JOIN Employees e ON e.EmployeeID = o.EmployeeID
GROUP BY e.FirstName
ORDER BY Orders DESC;Result: 3 rows
| Employee | Orders | Pct |
|---|---|---|
| Sara | 4 | 50 |
| David | 3 | 37.5 |
| (no employee) | 1 | 12.5 |
Customers who bought every product in the Beverages category.
"Relational division": count the distinct Beverages products each customer bought and compare with the total.
Example
No customer in the demo data has bought both Beverages products yet, so we first add Green Tea to order 103 (Blue Harbor Foods):
INSERT INTO OrderDetails (OrderDetailID, OrderID, ProductID, Quantity) VALUES (13, 103, 2, 4);
SELECT c.CustomerName
FROM Customers c
JOIN Orders o ON o.CustomerID = c.CustomerID
JOIN OrderDetails od ON od.OrderID = o.OrderID
JOIN Products p ON p.ProductID = od.ProductID
WHERE p.Category = 'Beverages'
GROUP BY c.CustomerName
HAVING COUNT(DISTINCT p.ProductID) = (SELECT COUNT(*) FROM Products WHERE Category = 'Beverages');Result: 1 row
| CustomerName |
|---|
| Blue Harbor Foods |