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

DepartmentFirstNameSalary
FinanceFatima80000
SalesRahul72000
SupportJames67000

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

FirstNameSalaryManagerManagerSalary
Sara75000Rahul72000

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

CityTimes
London2

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

CustomerIDMonth1Month2
12024-012024-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

CustomerNameSpent
Blue Harbor Foods412
Cedar & Co320.75
Aarav Traders301.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

MonthRevenueRunningRevenue
2024-01335.4335.4
2024-02468.25803.65
2024-03497.751301.4
2024-04198.41499.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

CategoryProductNameUnits
BeveragesEspresso Beans 1kg18
GroceryOlive Oil 1L29
SnacksDark Chocolate18

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

EmployeeOrdersPct
Sara450
David337.5
(no employee)112.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