intview SQL Interview Notes

SQL Interview Questions 1–40 — Medium to Advanced

1. Find the second highest salary from the Employee table.

SQL
SELECT MAX(salary) AS SecondHighestSalary
FROM employees
WHERE salary < (
    SELECT MAX(salary)
    FROM employees
);

Logic:

  1. The inner query finds the highest salary.
  2. WHERE salary < that value removes the top salary.
  3. MAX(salary) of the remaining rows is the second-highest distinct salary.
Concept

Subquery with an aggregate function.

Note

It returns NULL when there are fewer than two distinct salaries. Duplicate top salaries do not matter because the comparison is on the value.

2. Find duplicate records in a table.

SQL
SELECT name, COUNT(*)
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;

Logic:

  1. GROUP BY name puts identical names in one group.
  2. COUNT(*) counts the rows in each group.
  3. HAVING COUNT(*) > 1 keeps only the groups that appear more than once.
Concept

Duplicate detection with GROUP BY and HAVING.

Note

Add more columns to GROUP BY to detect duplicates on a combination of columns (see Question 56).

3. Retrieve employees who earn more than their manager.

SQL
SELECT e.name AS Employee, e.salary, m.name AS Manager, m.salary AS ManagerSalary
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.salary > m.salary;

Logic:

  1. Join employees to itself: e is the employee, m is the manager.
  2. e.manager_id = m.id links each employee to their manager's row.
  3. WHERE e.salary > m.salary keeps employees who earn more than their manager.
Concept

Self join.

Note

Employees without a manager (manager_id IS NULL) disappear because of the inner JOIN.

4. Count employees in each department having more than 5 employees.

SQL
SELECT department_id, COUNT(*) AS num_employees
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 5;

Logic:

  1. GROUP BY department_id creates one group per department.
  2. COUNT(*) counts the employees in each group.
  3. HAVING COUNT(*) > 5 filters the groups after aggregation.
Concept

HAVING filters groups; WHERE filters rows.

5. Find employees who joined in the last 6 months.

SQL
SELECT *
FROM employees
WHERE join_date >= CURRENT_DATE - INTERVAL '6 months';

Logic:

  1. CURRENT_DATE - INTERVAL '6 months' computes the date six months ago.
  2. join_date >= that date keeps recent joiners.
Concept

Date arithmetic in WHERE.

Note

This is PostgreSQL syntax. MySQL: DATE_SUB(CURDATE(), INTERVAL 6 MONTH). SQL Server: DATEADD(month, -6, GETDATE()).

6. Get departments with no employees.

SQL
SELECT d.department_name
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
WHERE e.id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from departments.
  2. Rows without a match have NULL in all employees columns.
  3. WHERE e.id IS NULL keeps only the departments rows that have no match in employees.
Concept

Anti-join to find parents without children.

Note

Always test a column that can never be NULL in a real match (usually the primary key) in the IS NULL check.

7. Write a query to find the median salary.

SQL
SELECT AVG(salary) AS median_salary
FROM (
    SELECT salary
    FROM employees
    ORDER BY salary
    LIMIT 2 - (SELECT COUNT(*) FROM employees) % 2
    OFFSET (SELECT (COUNT(*) - 1) / 2 FROM employees)
) AS median_subquery;

Logic:

  1. Count the rows (N). The middle position is (N - 1) / 2 (integer division), used as the OFFSET.
  2. LIMIT 2 - N % 2 fetches 1 row when N is odd and 2 rows when N is even.
  3. AVG(salary) of those one or two middle rows is the median.
Concept

Median using ORDER BY, LIMIT and OFFSET.

Important

Subqueries inside LIMIT/OFFSET work in PostgreSQL but not in MySQL. The simpler PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) (Question 153) is usually preferred.

8. Running total of salaries by department.

SQL
SELECT name, department_id, salary,
    SUM(salary) OVER (PARTITION BY department_id ORDER BY id) AS running_total
FROM employees;

Logic:

  1. PARTITION BY department_id restarts the total for each department.
  2. ORDER BY id defines the order in which rows are added.
  3. SUM(salary) OVER (...) adds salaries from the first row up to the current row.
Concept

Running total with SUM() OVER.

Note

With only ORDER BY, the default frame is RANGE, so rows with equal id values share one total. Add ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for a strict row-by-row total.

9. Find the longest consecutive streak of daily logins for each user.

SQL
WITH login_dates AS (
    SELECT user_id, login_date,
        login_date - INTERVAL ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date) DAY AS grp
    FROM user_logins
)
SELECT user_id, COUNT(*) AS streak_length, MIN(login_date) AS start_date,
    MAX(login_date) AS end_date
FROM login_dates
GROUP BY user_id, grp
ORDER BY streak_length DESC;

Logic:

  1. ROW_NUMBER() numbers each user's login dates in order.
  2. Subtracting that number of days from the date gives the same value (grp) for every date in an unbroken streak.
  3. Group by user_id and grp; COUNT(*) is the streak length and MIN/MAX give its start and end.
Concept

Gaps and islands technique.

Important

The INTERVAL ROW_NUMBER() OVER (...) DAY syntax is MySQL-style and varies by database. The query also lists every streak for each user, and duplicate login dates would break the numbering. The PostgreSQL version below removes duplicate dates and keeps only each user's longest streak.

PostgreSQL version returning only the longest streak per user:

SQL
WITH login_dates AS (
    SELECT DISTINCT user_id, login_date
    FROM user_logins
), grouped AS (
    SELECT user_id, login_date,
        login_date - (ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY login_date))::int AS grp
    FROM login_dates
), streaks AS (
    SELECT user_id, COUNT(*) AS streak_length,
        MIN(login_date) AS start_date, MAX(login_date) AS end_date,
        ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY COUNT(*) DESC) AS rn
    FROM grouped
    GROUP BY user_id, grp
)
SELECT user_id, streak_length, start_date, end_date
FROM streaks
WHERE rn = 1;

10. Recursive query to find the full reporting chain for each employee.

SQL
WITH RECURSIVE reporting_chain AS (
    SELECT id, name, manager_id, 1 AS level
    FROM employees
    WHERE manager_id IS NULL
    UNION ALL
    SELECT e.id, e.name, e.manager_id, rc.level + 1
    FROM employees e
    JOIN reporting_chain rc ON e.manager_id = rc.id
)
SELECT * FROM reporting_chain ORDER BY level, id;

Logic:

  1. The anchor query starts with the top employee (manager_id IS NULL) at level 1.
  2. The recursive part joins employees to the rows already found through manager_id = rc.id, adding 1 to the level each time.
  3. Recursion stops when no more employees are found; the final query orders by level.

Showing the chain as text:

SQL
WITH RECURSIVE chain AS (
    SELECT id, name, manager_id, name::text AS path
    FROM employees
    WHERE manager_id IS NULL
    UNION ALL
    SELECT e.id, e.name, e.manager_id, c.path || ' > ' || e.name
    FROM employees e
    JOIN chain c ON e.manager_id = c.id
)
SELECT name, path
FROM chain
ORDER BY path;
Concept

Recursive CTE for hierarchies.

Note

This returns each employee's level in the hierarchy. To display the actual chain (CEO > Manager > Employee), carry a text path through the recursion.

11. Write a query to find gaps in a sequence of numbers

SQL
(missing IDs).
SELECT (id + 1) AS missing_id
FROM employees e1
WHERE NOT EXISTS (
    SELECT 1 FROM employees e2 WHERE e2.id = e1.id + 1
)
ORDER BY missing_id;

Logic:

  1. For each id, check whether a row with id + 1 exists.
  2. NOT EXISTS is true when the next number is missing.
  3. id + 1 is reported as the missing ID.
Concept

Gap detection using NOT EXISTS.

Important

The highest ID always qualifies, so max(id) + 1 is reported even though it is not a real gap. Exclude it as shown below.

Corrected version that ignores the last ID:

SQL
SELECT (e1.id + 1) AS missing_id
FROM employees e1
WHERE NOT EXISTS (
    SELECT 1 FROM employees e2 WHERE e2.id = e1.id + 1
)
AND e1.id < (SELECT MAX(id) FROM employees)
ORDER BY missing_id;

12. Calculate cumulative distribution (CDF) of salaries.

SQL
SELECT name, salary, CUME_DIST() OVER (ORDER BY salary) AS salary_cdf
FROM employees;

Logic:

  1. ORDER BY salary sorts employees from lowest to highest salary.
  2. CUME_DIST() returns the fraction of rows with a salary less than or equal to the current salary.
Concept

Cumulative distribution window function.

Note

Values range from just above 0 up to 1. Employees with equal salaries share the same value.

13. Compare two tables and find rows with differences in any column (all columns).

SQL
SELECT *
FROM table1 t1
FULL OUTER JOIN table2 t2 ON t1.id = t2.id
WHERE t1.col1 IS DISTINCT FROM t2.col1
    OR t1.col2 IS DISTINCT FROM t2.col2
    OR t1.col3 IS DISTINCT FROM t2.col3;

Logic:

  1. FULL OUTER JOIN keeps rows that exist in only one of the tables.
  2. IS DISTINCT FROM compares values and treats NULL as a normal value (two NULLs are equal).
  3. Any column difference, or a missing row on either side, makes the row appear in the result.

Alternative using set operators (rows in one table but not the other):

SQL
(SELECT * FROM table1 EXCEPT SELECT * FROM table2)
UNION ALL
(SELECT * FROM table2 EXCEPT SELECT * FROM table1);
Concept

Table comparison with null-safe operators.

Note

MySQL does not support IS DISTINCT FROM; use <=> (NOT (a <=> b)).

14. Write a query to rank employees based on salary with ties handled properly.

SQL
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;

Logic:

  1. ORDER BY salary DESC ranks the highest salary first.
  2. RANK() gives equal salaries the same rank.
  3. The next rank skips numbers after a tie (1, 2, 2, 4).
Concept

RANK() window function.

Note

Use DENSE_RANK() when you do not want gaps after ties (1, 2, 2, 3).

15. Find customers who have not made any purchase.

SQL
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN sales s ON c.customer_id = s.customer_id
WHERE s.sale_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from customers.
  2. Rows without a match have NULL in all sales columns.
  3. WHERE s.sale_id IS NULL keeps only the customers rows that have no match in sales.
Concept

Anti-join to find customers without activity.

16. Write a query to perform a conditional aggregation

SQL
(count males and females in each department).
SELECT department_id, COUNT(CASE WHEN gender = 'M' THEN 1
    END) AS male_count, COUNT(CASE WHEN gender = 'F' THEN 1
    END) AS female_count
FROM employees
GROUP BY department_id;

Logic:

  1. CASE WHEN gender = 'M' THEN 1 END returns 1 for males and NULL otherwise.
  2. COUNT() ignores NULL values, so it counts only the matching rows.
  3. GROUP BY department_id produces one row per department.
Concept

Conditional aggregation.

Note

SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0 END) gives the same result.

17. Write a query to calculate the difference between current row and previous row's salary (lag function).

SQL
SELECT name, salary, salary - LAG(salary) OVER (ORDER BY id) AS salary_diff
FROM employees;

Logic:

  1. LAG(salary) returns the salary from the previous row in the ORDER BY id order.
  2. Subtracting it from the current salary gives the difference.
Concept

LAG() window function.

Note

The first row has no previous row, so its difference is NULL.

18. Identify overlapping date ranges for bookings.

SQL
SELECT b1.booking_id, b2.booking_id
FROM bookings b1
JOIN bookings b2 ON b1.booking_id <> b2.booking_id
WHERE b1.start_date <= b2.end_date
    AND b1.end_date >= b2.start_date;

Logic:

  1. Join the bookings table to itself to compare every pair of bookings.
  2. Two ranges overlap when each one starts on or before the other one ends: start1 <= end2 AND end1 >= start2.
  3. b1.booking_id <> b2.booking_id prevents comparing a booking with itself.
Concept

Interval overlap test with a self join.

Important

With <>, each overlapping pair appears twice ((A, B) and (B, A)). Use b1.booking_id < b2.booking_id to return each pair once.

19. Write a query to find employees with salary greater than average salary in the entire company, ordered by salary descending.

SQL
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC;

Logic:

  1. The scalar subquery calculates the company's average salary.
  2. WHERE salary > keeps employees above it.
  3. ORDER BY salary DESC lists the highest earners first.
Concept

Scalar subquery in WHERE.

20. Aggregate JSON data (if supported) to list all employee names in a department as a JSON array.

SQL
SELECT department_id, JSON_AGG(name) AS employee_names
FROM employees
GROUP BY department_id;

Logic:

  1. GROUP BY department_id creates one group per department.
  2. JSON_AGG(name) collects the names of each group into one JSON array.
Concept

JSON aggregation.

Note

JSON_AGG is PostgreSQL. MySQL and Oracle use JSON_ARRAYAGG(name); SQL Server uses FOR JSON PATH or STRING_AGG.

21. Find employees who have the same salary as their manager.

SQL
SELECT e.name AS Employee, e.salary, m.name AS Manager
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.salary = m.salary;

Logic:

  1. The self join links each employee e to their manager m.
  2. WHERE e.salary = m.salary keeps employees who earn exactly their manager's salary.
Concept

Self join with an equality comparison.

22. Write a query to get the first and last purchase date for each customer.

SQL
SELECT customer_id, MIN(purchase_date) AS first_purchase,
    MAX(purchase_date) AS last_purchase
FROM sales
GROUP BY customer_id;

Logic:

  1. GROUP BY customer_id creates one group per customer.
  2. MIN(purchase_date) is the first purchase and MAX(purchase_date) is the last.
Concept

MIN and MAX aggregates.

Note

Customers with no purchases are not returned. Question 73 shows how to include them.

23. Find departments with the highest average salary.

SQL
WITH avg_salaries AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
)
SELECT *
FROM avg_salaries
WHERE avg_salary = (SELECT MAX(avg_salary)
    FROM avg_salaries);

Logic:

  1. The CTE calculates the average salary of each department.
  2. The subquery finds the largest of those averages.
  3. The outer query keeps departments whose average equals that maximum.
Concept

CTE with a nested aggregate.

Note

This returns all departments tied for the highest average. ORDER BY avg_salary DESC LIMIT 1 returns only one row.

24. Write a query to find the number of employees in each job title.

SQL
SELECT job_title, COUNT(*) AS num_employees
FROM employees
GROUP BY job_title;

Logic:

  1. GROUP BY job_title creates one group per title.
  2. COUNT(*) counts the employees in each group.
Concept

Basic GROUP BY with COUNT.

25. Find employees who don’t have a department assigned.

SQL
SELECT *
FROM employees
WHERE department_id IS NULL;

Logic:

  1. department_id IS NULL selects rows where no department was assigned.
Concept

NULL handling.

Important

Use IS NULL, not = NULL. Any comparison with NULL using = returns unknown, so no rows would be returned.

26. Write a query to find the difference in days between two dates in the same table.

SQL
SELECT id, DATEDIFF(day, start_date, end_date) AS days_difference
FROM projects;

Logic:

  1. DATEDIFF(day, start_date, end_date) returns the number of days between the two dates for each project.
Concept

Date difference function.

Note

Syntax depends on the database. SQL Server: DATEDIFF(day, start_date, end_date). MySQL: DATEDIFF(end_date, start_date). PostgreSQL: end_date - start_date (for DATE columns).

27. Calculate the moving average of salaries over the last 3 employees ordered by hire date.

SQL
SELECT name, hire_date, salary,
    AVG(salary) OVER (ORDER BY hire_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg_salary
FROM employees;

Logic:

  1. ORDER BY hire_date defines the order of employees.
  2. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW creates a window of the current row and the two rows before it.
  3. AVG(salary) averages the salaries inside that window.
Concept

Moving average with a window frame.

Note

The first two rows average fewer than three salaries because fewer preceding rows exist.

28. Find the most recent purchase per customer using window functions.

SQL
SELECT *
FROM (
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY purchase_date DESC) AS rn
    FROM sales
) sub
WHERE rn = 1;

Logic:

  1. PARTITION BY customer_id ORDER BY purchase_date DESC numbers each customer's purchases from newest to oldest.
  2. rn = 1 selects the newest purchase of each customer.
Concept

ROW_NUMBER() for top-1 per group.

Note

If two purchases share the newest date, ROW_NUMBER() picks one arbitrarily. Use RANK() to return all tied rows.

29. Detect hierarchical depth of each employee in the org chart.

SQL
WITH RECURSIVE employee_depth AS (
    SELECT id, name, manager_id, 1 AS depth
    FROM employees
    WHERE manager_id IS NULL
    UNION ALL
    SELECT e.id, e.name, e.manager_id, ed.depth + 1
    FROM employees e
    JOIN employee_depth ed ON e.manager_id = ed.id
)
SELECT * FROM employee_depth;

Logic:

  1. The anchor row is the top employee at depth 1.
  2. Each recursion joins the employees who report to the rows found so far and adds 1 to the depth.
  3. The final query returns every employee with their depth.
Concept

Recursive CTE for hierarchy depth.

Note

Add WHERE manager_id IS NOT NULL-style guards or a depth limit if the data might contain cycles (see Question 41).

30. Write a query to perform a self-join to find pairs of employees in the same department.

SQL
SELECT e1.name AS Employee1, e2.name AS Employee2, e1.department_id
FROM employees e1
JOIN employees e2 ON e1.department_id = e2.department_id AND e1.id < e2.id;

Logic:

  1. Self join employees on department_id to pair employees within a department.
  2. e1.id < e2.id removes self-pairs and prevents the same pair from appearing in both orders.
Concept

Self join for pair generation.

31. Write a query to pivot rows into columns dynamically (if dynamic pivot is not supported, simulate it for fixed values).

SQL
SELECT department_id, SUM(CASE WHEN job_title = 'Manager' THEN 1
        ELSE 0 END) AS Managers, SUM(CASE WHEN job_title = 'Developer' THEN 1
        ELSE 0 END) AS Developers, SUM(CASE WHEN job_title = 'Tester' THEN 1
        ELSE 0 END) AS Testers
FROM employees
GROUP BY department_id;

Logic:

  1. Each CASE expression returns 1 for one job title and 0 for the others.
  2. SUM() of those values counts employees of that title.
  3. GROUP BY department_id gives one row per department, with one column per title.
Concept

Pivoting with conditional aggregation.

Note

A truly dynamic pivot requires dynamic SQL (building the query text from the distinct values). SQL Server has PIVOT, and PostgreSQL offers crosstab() from the tablefunc extension.

32. Find customers who made purchases in every category available.

SQL
SELECT customer_id
FROM sales s
GROUP BY customer_id
HAVING COUNT(DISTINCT category_id) = (SELECT COUNT(DISTINCT category_id) FROM sales);

Logic:

  1. Count the distinct categories each customer bought from.
  2. The subquery counts all distinct categories in sales.
  3. HAVING keeps customers whose own count equals the total.
Concept

Relational division with COUNT(DISTINCT).

Note

The total here comes from the sales table. If a category exists but was never sold, use (SELECT COUNT(*) FROM categories) as the total instead.

33. Identify employees who haven’t received a salary raise in more than a year.

SQL
SELECT e.name
FROM employees e
JOIN salary_history sh ON e.id = sh.employee_id
GROUP BY e.id, e.name
HAVING MAX(sh.raise_date) < CURRENT_DATE - INTERVAL '1 year';

Logic:

  1. Join employees to their raise history.
  2. MAX(raise_date) is each employee's latest raise.
  3. HAVING keeps employees whose latest raise is more than a year old.
Concept

Aggregation with a date condition in HAVING.

Important

Employees with no row in salary_history are not returned because of the inner join. Use a LEFT JOIN and add OR MAX(sh.raise_date) IS NULL to include them.

34. Write a query to rank salespeople by monthly sales, resetting the rank every month.

SQL
SELECT salesperson_id, sale_month, total_sales, RANK() OVER (PARTITION BY sale_month
    ORDER BY total_sales DESC) AS monthly_rank
FROM (
    SELECT salesperson_id, DATE_TRUNC('month', sale_date) AS sale_month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY salesperson_id, sale_month
) AS monthly_sales;

Logic:

  1. The subquery totals each salesperson's sales per month.
  2. PARTITION BY sale_month restarts the ranking for every month.
  3. ORDER BY total_sales DESC gives rank 1 to the best seller.
Concept

Ranking within partitions.

35. Calculate the percentage change in sales compared to the previous month for each product.

SQL
SELECT product_id, sale_month, total_sales,
    (total_sales - LAG(total_sales) OVER (PARTITION BY product_id ORDER BY sale_month)) * 100.0 / LAG(total_sales) OVER (PARTITION BY product_id ORDER BY sale_month) AS pct_change
FROM (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS sale_month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, sale_month
) monthly_sales;

Logic:

  1. The subquery totals sales per product per month.
  2. LAG(total_sales) retrieves the same product's previous month.
  3. (current - previous) * 100.0 / previous is the percentage change.
Concept

Month-over-month change with LAG().

Important

The first month of each product has no previous value (result NULL), and a previous value of 0 causes division by zero. Wrap the divisor in NULLIF(..., 0) to avoid the error.

36. Find employees who earn more than the average salary across the company but less than the highest salary in their department.

SQL
SELECT *
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees)
    AND salary < (
    SELECT MAX(salary)
    FROM employees
    WHERE department_id = e.department_id
);

Logic:

  1. The first condition compares the salary with the company average.
  2. The correlated subquery finds the highest salary in the employee's own department.
  3. Both conditions must be true.
Concept

Correlated subquery combined with a scalar subquery.

37. Retrieve the last 5 orders for each customer.

SQL
SELECT *
FROM (
    SELECT o.*,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
    FROM orders o
) sub
WHERE rn <= 5;

Logic:

  1. ROW_NUMBER() numbers each customer's orders from newest to oldest.
  2. rn <= 5 keeps the five most recent.
Concept

Top-N per group.

38. Find employees with no salary changes in the last 2 years.

SQL
SELECT e.*
FROM employees e
LEFT JOIN salary_history sh ON e.id = sh.employee_id AND sh.change_date >= CURRENT_DATE - INTERVAL '2 years'
WHERE sh.employee_id IS NULL;

Logic:

  1. LEFT JOIN salary changes, but only those from the last two years (condition in ON).
  2. Employees with no such change get NULL values.
  3. WHERE sh.employee_id IS NULL keeps them.
Concept

Anti-join with a date filter.

Important

Keep the date condition in the ON clause. If it were in WHERE, the LEFT JOIN would behave like an inner join and the anti-join would return nothing.

39. Find the department with the lowest average salary.

SQL
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
ORDER BY avg_salary
LIMIT 1;

Logic:

  1. AVG(salary) is calculated for each department.
  2. ORDER BY avg_salary sorts from lowest to highest.
  3. LIMIT 1 returns the lowest.
Concept

Top-1 with ORDER BY and LIMIT.

Note

If several departments tie, only one is returned. Use RANK() or compare with MIN() of the averages to return all ties.

40. List employees whose names start and end with the same letter.

SQL
SELECT *
FROM employees
WHERE LEFT(name, 1) = RIGHT(name, 1);

Logic:

  1. LEFT(name, 1) is the first character and RIGHT(name, 1) is the last.
  2. The WHERE clause keeps rows where both are equal.
Concept

String functions.

Important

The comparison is case-sensitive in some databases. Use LOWER(LEFT(name,1)) = LOWER(RIGHT(name,1)) for a case-insensitive check.

SQL Interview Questions 41–80 — Medium to Advanced

41. Write a query to detect circular references in employee-manager hierarchy (cycles).

SQL
WITH RECURSIVE mgr_path (id, manager_id, path) AS (
    SELECT id, manager_id, ARRAY[id]
    FROM employees
    WHERE manager_id IS NOT NULL
    UNION ALL
    SELECT e.id, e.manager_id, path || e.id
    FROM employees e
    JOIN mgr_path mp ON e.manager_id = mp.id
    WHERE NOT e.id = ANY(path)
)
SELECT DISTINCT id
FROM mgr_path
WHERE id = ANY(path);

Logic:

  1. The query below walks upward from each employee through manager_id, remembering where it started.
  2. If the walk returns to the starting employee, that employee is part of a loop.
  3. steps < (SELECT COUNT(*) ...) stops the recursion in loops that never return to the start.
Concept

Cycle detection in a recursive CTE.

Important

The query shown in the PDF does not actually detect cycles. NOT e.id = ANY(path) stops the recursion, and the final id = ANY(path) filter is always true because each row adds its own id to the path. Use the corrected query.

Corrected cycle detection:

SQL
WITH RECURSIVE walk AS (
    SELECT id AS start_id, manager_id AS current_id, 1 AS steps
    FROM employees
    WHERE manager_id IS NOT NULL
    UNION ALL
    SELECT w.start_id, e.manager_id, w.steps + 1
    FROM walk w
    JOIN employees e ON e.id = w.current_id
    WHERE e.manager_id IS NOT NULL
        AND w.current_id <> w.start_id
        AND w.steps < (SELECT COUNT(*) FROM employees)
)
SELECT DISTINCT start_id AS employee_id
FROM walk
WHERE current_id = start_id;

42. Write a query to get the running total of sales per customer, ordered by sale date.

SQL
SELECT customer_id, sale_date, amount,
    SUM(amount) OVER (PARTITION BY customer_id ORDER BY sale_date) AS running_total
FROM sales;

Logic:

  1. PARTITION BY customer_id gives each customer a separate total.
  2. ORDER BY sale_date adds sales in date order.
  3. SUM(amount) OVER (...) returns the cumulative amount.
Concept

Running total with a window function.

43. Find the department-wise salary percentile (e.g., 90th percentile) using window functions.

SQL
SELECT department_id, salary,
    PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY salary) OVER (PARTITION BY department_id) AS pct_90_salary
FROM employees;

Logic:

  1. PERCENTILE_CONT(0.9) returns the value below which 90% of the salaries fall, interpolating between rows if needed.
  2. WITHIN GROUP (ORDER BY salary) defines the sort order used to find it.
  3. The result is calculated for each department.
Concept

Percentiles.

Important

PostgreSQL does not allow PERCENTILE_CONT(...) WITHIN GROUP (...) with OVER; it must be used as an aggregate. SQL Server and Oracle support the OVER (PARTITION BY ...) form.

PostgreSQL version (one row per department):

SQL
SELECT department_id,
    PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY salary) AS pct_90_salary
FROM employees
GROUP BY department_id;

44. Find employees whose salary is a prime number.

SQL
WITH primes AS (
    SELECT generate_series(2, (SELECT MAX(salary)
            FROM employees)) AS num
    EXCEPT
    SELECT num FROM (
        SELECT num, UNNEST(ARRAY(
                SELECT generate_series(2, FLOOR(SQRT(num))) AS divisor
        )) AS divisor
        WHERE num % divisor = 0
    ) AS composite
)
SELECT *
FROM employees
WHERE salary IN (SELECT num FROM primes);

Logic:

  1. Generate candidate divisors from 2 up to the square root of each salary.
  2. A salary is prime if no divisor divides it evenly (NOT EXISTS).
  3. Salaries below 2 are excluded.
Concept

Prime test with a set-generating function.

Important

The query in the PDF is conceptual and does not run as written: the derived subquery refers to num without a source table. The version below works in PostgreSQL for whole-number salaries.

Working PostgreSQL version:

SQL
SELECT e.*
FROM employees e
WHERE e.salary >= 2
    AND e.salary = FLOOR(e.salary)
    AND NOT EXISTS (
        SELECT 1
        FROM generate_series(2, FLOOR(SQRT(e.salary))::int) AS d
        WHERE e.salary % d = 0
    );

45. Find employees who have worked for multiple departments over time.

SQL
SELECT employee_id
FROM employee_department_history
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id) > 1;

Logic:

  1. GROUP BY employee_id groups the history rows of each employee.
  2. COUNT(DISTINCT department_id) > 1 keeps employees who worked in more than one department.
Concept

Distinct count in HAVING.

46. Use window function to find the difference between current row’s sales and previous row’s sales partitioned by product.

SQL
SELECT product_id, sale_date, amount,
    amount - LAG(amount) OVER (PARTITION BY product_id ORDER BY sale_date) AS sales_diff
FROM sales;

Logic:

  1. PARTITION BY product_id compares rows only within the same product.
  2. ORDER BY sale_date defines the row order.
  3. amount - LAG(amount) is the change from the previous sale.
Concept

LAG() with partitions.

47. Write a query to find all employees who are at the lowest level in the hierarchy (no subordinates).

SQL
SELECT *
FROM employees e
WHERE NOT EXISTS (
    SELECT 1 FROM employees sub WHERE sub.manager_id = e.id
);

Logic:

  1. NOT EXISTS checks whether any employee has this employee as their manager.
  2. Employees with no subordinates are returned.
Concept

Leaf nodes of a hierarchy.

48. Find average order value per month and product category.

SQL
SELECT DATE_TRUNC('month', order_date) AS order_month, category_id,
    AVG(order_value) AS avg_order_value
FROM orders
GROUP BY order_month, category_id;

Logic:

  1. DATE_TRUNC('month', order_date) converts each date to the first day of its month.
  2. Grouping by month and category gives one row per combination.
  3. AVG(order_value) is the average within each group.
Concept

Time bucketing with DATE_TRUNC.

49. Write a query to create a running count of how many employees joined in each year.

SQL
SELECT join_year, COUNT(*) AS yearly_hires,
    SUM(COUNT(*)) OVER (ORDER BY join_year) AS running_total_hires
FROM (
    SELECT EXTRACT(YEAR FROM hire_date) AS join_year
    FROM employees
) sub
GROUP BY join_year
ORDER BY join_year;

Logic:

  1. The inner query extracts the hire year.
  2. COUNT(*) counts hires per year.
  3. SUM(COUNT(*)) OVER (ORDER BY join_year) adds the yearly counts cumulatively.
Concept

Window function on top of an aggregate.

50. Write a query to find the second most recent order date per customer.

SQL
SELECT customer_id, order_date
FROM (
    SELECT customer_id, order_date,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
    FROM orders
) sub
WHERE rn = 2;

Logic:

  1. Number each customer's orders from newest to oldest.
  2. rn = 2 selects the second one.
Concept

Nth row per group.

Note

If a customer can place several orders on one day, select DISTINCT dates first or use DENSE_RANK(), otherwise the second row may have the same date as the first.

51. Find employees who have never made a sale.

SQL
SELECT e.id, e.name
FROM employees e
LEFT JOIN sales s ON e.id = s.employee_id
WHERE s.sale_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all sales columns.
  3. WHERE s.sale_id IS NULL keeps only the employees rows that have no match in sales.
Concept

Anti-join using LEFT JOIN … IS NULL.

52. Find the average tenure of employees by department.

SQL
SELECT department_id,
    AVG(DATE_PART('year', CURRENT_DATE - hire_date)) AS avg_tenure_years
FROM employees
GROUP BY department_id;

Logic:

  1. Subtract the hire date from today's date to get the tenure.
  2. DATE_PART('year', ...) converts it to years.
  3. AVG() per department gives the average tenure.
Concept

Date arithmetic with aggregation.

Important

In PostgreSQL, subtracting two DATE values returns an integer number of days, and DATE_PART('year', integer) fails. It works only when hire_date is a TIMESTAMP. For a DATE column use the version below.

Version for DATE columns:

SQL
SELECT department_id,
    AVG(CURRENT_DATE - hire_date) / 365.25 AS avg_tenure_years
FROM employees
GROUP BY department_id;

53. Get employees with salary in the top 10% in their department.

SQL
SELECT *
FROM (
    SELECT e.*,
        NTILE(10) OVER (PARTITION BY department_id ORDER BY salary DESC) AS decile
    FROM employees e
) sub
WHERE decile = 1;

Logic:

  1. NTILE(10) splits each department's employees into 10 equal groups, sorted by salary descending.
  2. Group 1 contains the highest-paid 10%.
Concept

NTILE() for percentile buckets.

Note

In departments with fewer than 10 employees, the first group still contains at least one employee.

54. Find customers who purchased more than once in the same day.

SQL
SELECT customer_id, purchase_date, COUNT(*) AS purchase_count
FROM sales
GROUP BY customer_id, purchase_date
HAVING COUNT(*) > 1;

Logic:

  1. Group by customer and date.
  2. COUNT(*) counts the purchases on each date.
  3. HAVING COUNT(*) > 1 keeps the days with multiple purchases.
Concept

Grouping on a customer and date.

55. List all departments and their employee counts, including departments with zero employees.

SQL
SELECT d.department_id, d.department_name, COUNT(e.id) AS employee_count
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name;

Logic:

  1. LEFT JOIN keeps all departments.
  2. COUNT(e.id) counts only non-NULL employee ids, so departments without employees get 0.
Concept

Left join with a count.

Important

Use COUNT(e.id), not COUNT(*). COUNT(*) would count the unmatched NULL row and return 1 instead of 0.

56. Write a query to find duplicate rows based on multiple columns.

SQL
SELECT column1, column2, COUNT(*)
FROM table_name
GROUP BY column1, column2
HAVING COUNT(*) > 1;

Logic:

  1. Group by the columns that define a duplicate.
  2. HAVING COUNT(*) > 1 keeps combinations that appear more than once.
Concept

Multi-column duplicate detection.

57. Write a recursive query to calculate factorial of a number (e.g., 5).

SQL
WITH RECURSIVE factorial(n, fact) AS (
    SELECT 1, 1
    UNION ALL
    SELECT n + 1, fact * (n + 1)
    FROM factorial
    WHERE n < 5
)
SELECT fact FROM factorial WHERE n = 5;

Logic:

  1. The anchor row is n = 1, fact = 1.
  2. Each recursion increases n by 1 and multiplies fact by the new n.
  3. WHERE n < 5 stops the recursion; the final query reads the row where n = 5 (120).
Concept

Recursive CTE for calculations.

58. Write a query to calculate the cumulative percentage of total sales per product.

SQL
SELECT product_id, sale_amount,
    SUM(sale_amount) OVER (ORDER BY sale_amount DESC) * 100.0 / SUM(sale_amount) OVER () AS cumulative_pct
FROM sales;

Logic:

  1. SUM(sale_amount) OVER (ORDER BY sale_amount DESC) is the running total from the largest amount downward.
  2. SUM(sale_amount) OVER () is the grand total.
  3. Dividing and multiplying by 100 gives the cumulative percentage.
Concept

Running share of a total (Pareto analysis).

Important

If sales has many rows per product, aggregate by product first; otherwise the percentages are per row, not per product.

Aggregating per product first:

SQL
WITH product_sales AS (
    SELECT product_id, SUM(sale_amount) AS total_sales
    FROM sales
    GROUP BY product_id
)
SELECT product_id, total_sales,
    SUM(total_sales) OVER (ORDER BY total_sales DESC) * 100.0
        / SUM(total_sales) OVER () AS cumulative_pct
FROM product_sales;

59. Write a query to get employees who reported directly or indirectly to a given manager (hierarchy traversal).

SQL
WITH RECURSIVE reporting AS (
    SELECT id, name, manager_id
    FROM employees
    WHERE manager_id = 101 -- replace 101 with manager's id
    UNION ALL
    SELECT e.id, e.name, e.manager_id
    FROM employees e
    INNER JOIN reporting r ON e.manager_id = r.id
)
SELECT * FROM reporting;

Logic:

  1. The anchor selects the manager's direct reports.
  2. The recursive part adds the people who report to anyone already found.
  3. The final query returns the full reporting tree below the manager.
Concept

Recursive hierarchy traversal.

Note

The manager (id 101) is not included. Cyclic data would cause infinite recursion.

60. Find the average number of orders per customer and standard deviation.

SQL
SELECT AVG(order_count) AS avg_orders, STDDEV(order_count) AS stddev_orders
FROM (
    SELECT customer_id, COUNT(*) AS order_count
    FROM orders
    GROUP BY customer_id
) sub;

Logic:

  1. The subquery counts the orders of each customer.
  2. AVG() and STDDEV() summarize those counts.
Concept

Aggregating an aggregate.

Note

Customers with no orders are not counted. STDDEV is the sample standard deviation in most databases.

61. Find gaps in date sequences for each customer

SQL
(missing days).
WITH dates AS (
    SELECT customer_id, purchase_date,
        LAG(purchase_date) OVER (PARTITION BY customer_id ORDER BY purchase_date) AS prev_date
    FROM sales
)
SELECT customer_id, prev_date + INTERVAL '1 day' AS missing_date
FROM dates
WHERE purchase_date > prev_date + INTERVAL '1 day';

Logic:

  1. LAG(purchase_date) gets each customer's previous purchase date.
  2. If the current date is more than one day after the previous date, there is a gap.
  3. prev_date + 1 day is the first missing day.
Concept

Gap detection with LAG().

Note

Only the first missing day of each gap is shown. Use generate_series (see Question 106) to list every missing day.

62. Rank employees by salary within their department, and calculate percent rank.

SQL
SELECT name, department_id, salary, RANK() OVER (PARTITION BY department_id
    ORDER BY salary DESC) AS salary_rank, PERCENT_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_percent_rank
FROM employees;

Logic:

  1. RANK() ranks employees by salary within each department.
  2. PERCENT_RANK() converts the position to a value between 0 and 1: (rank - 1) / (rows - 1).
Concept

RANK() and PERCENT_RANK().

Note

The highest salary in a department has percent rank 0; departments with a single employee also return 0.

63. Find products that have never been sold.

SQL
SELECT p.product_id, p.product_name
FROM products p
LEFT JOIN sales s ON p.product_id = s.product_id
WHERE s.sale_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from products.
  2. Rows without a match have NULL in all sales columns.
  3. WHERE s.sale_id IS NULL keeps only the products rows that have no match in sales.
Concept

Anti-join using LEFT JOIN … IS NULL.

64. Write a query to find consecutive days where sales were above a threshold.

SQL
WITH flagged_sales AS (
    SELECT sale_date, amount,
    CASE WHEN amount > 1000 THEN 1 ELSE 0
    END AS flag
    FROM sales
), groups AS (
    SELECT sale_date, amount, flag,
        sale_date - INTERVAL ROW_NUMBER() OVER (ORDER BY sale_date) DAY AS grp
    FROM flagged_sales
    WHERE flag = 1
)
SELECT MIN(sale_date) AS start_date, MAX(sale_date) AS end_date,
    COUNT(*) AS consecutive_days
FROM groups
GROUP BY grp
ORDER BY consecutive_days DESC;

Logic:

  1. A CASE flag marks days with sales above 1000.
  2. Only flagged days are kept and numbered in date order.
  3. Subtracting the row number from the date gives a constant group value for consecutive days; each group is one run.
Concept

Gaps and islands with a threshold.

Important

This assumes one row per day and uses MySQL-style interval syntax. In PostgreSQL use sale_date - (ROW_NUMBER() OVER (ORDER BY sale_date))::int, and total the sales per day first if there are several rows per day.

65. Write a query to concatenate employee names in each department (string aggregation).

SQL
SELECT department_id, STRING_AGG(name, ', ') AS employee_names
FROM employees
GROUP BY department_id;

Logic:

  1. STRING_AGG(name, ', ') joins all names of a group into one comma-separated string.
  2. GROUP BY department_id creates one string per department.
Concept

String aggregation.

Note

MySQL: GROUP_CONCAT(name SEPARATOR ', '). Oracle: LISTAGG(name, ', ').

66. Find employees whose salary is above the average salary of their department but below the company-wide average.

SQL
SELECT *
FROM employees e
WHERE salary > (
    SELECT AVG(salary)
    FROM employees
    WHERE department_id = e.department_id
)
    AND salary < (SELECT AVG(salary) FROM employees);

Logic:

  1. The correlated subquery calculates the average salary of the employee's own department.
  2. The second subquery calculates the company-wide average.
  3. Both conditions must hold.
Concept

Correlated and scalar subqueries together.

67. List the customers who purchased all products in a specific category.

SQL
SELECT customer_id
FROM sales
WHERE category_id = 10 -- example category
GROUP BY customer_id
HAVING COUNT(DISTINCT product_id) = (
    SELECT COUNT(DISTINCT product_id)
    FROM products
    WHERE category_id = 10
);

Logic:

  1. Keep only sales in category 10.
  2. Count the distinct products each customer bought.
  3. Compare with the number of products in that category using HAVING.
Concept

Relational division.

68. Retrieve the Nth highest salary from the employees table.

SQL
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET N-1;

Logic:

  1. DISTINCT salary removes duplicate salaries.
  2. ORDER BY salary DESC sorts from highest to lowest.
  3. OFFSET N-1 skips the first N-1 salaries and LIMIT 1 returns the next one.
Concept

Nth highest value with LIMIT/OFFSET.

Note

Replace N with a number (for example, OFFSET 2 for the 3rd highest). In MySQL, LIMIT/OFFSET need literal numbers or prepared-statement parameters.

69. Find employees with no corresponding entries in the salary_history table.

SQL
SELECT e.*
FROM employees e
LEFT JOIN salary_history sh ON e.id = sh.employee_id
WHERE sh.employee_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all salary_history columns.
  3. WHERE sh.employee_id IS NULL keeps only the employees rows that have no match in salary_history.
Concept

Anti-join using LEFT JOIN … IS NULL.

70. Show the department with the highest number of employees and the count.

SQL
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
ORDER BY employee_count DESC
LIMIT 1;

Logic:

  1. Count employees per department.
  2. ORDER BY employee_count DESC puts the largest first.
  3. LIMIT 1 returns it.
Concept

Top-1 group.

Note

Ties are not returned. Use a RANK() window function to include all tied departments.

71. Write a recursive query to list all ancestors

SQL
(managers) of a given employee.
WITH RECURSIVE ancestors AS (
    SELECT id, name, manager_id
    FROM employees
    WHERE id = 123 -- given employee id
    UNION ALL
    SELECT e.id, e.name, e.manager_id
    FROM employees e
    JOIN ancestors a ON e.id = a.manager_id
)
SELECT * FROM ancestors WHERE id != 123;

Logic:

  1. The anchor row is the given employee (id 123).
  2. Each recursion joins to the employee whose id equals the current row's manager_id, moving one level up.
  3. The final query removes the starting employee, leaving only the managers above them.
Concept

Recursive CTE walking up a hierarchy.

72. Calculate the median salary by department using window functions.

SQL
SELECT DISTINCT department_id,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) OVER (PARTITION BY department_id) AS median_salary
FROM employees;

Logic:

  1. PERCENTILE_CONT(0.5) returns the median of the sorted salaries.
  2. OVER (PARTITION BY department_id) calculates it for each department.
  3. DISTINCT collapses the repeated row for every employee into one row per department.
Concept

Median per group.

Important

PostgreSQL does not allow PERCENTILE_CONT ... WITHIN GROUP with OVER. The OVER (PARTITION BY ...) form works in SQL Server and Oracle. For PostgreSQL use GROUP BY.

PostgreSQL version:

SQL
SELECT department_id,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees
GROUP BY department_id;

73. Write a query to find the first purchase date and last purchase date for each customer, including customers who never purchased anything.

SQL
SELECT c.customer_id, MIN(s.purchase_date) AS first_purchase,
    MAX(s.purchase_date) AS last_purchase
FROM customers c
LEFT JOIN sales s ON c.customer_id = s.customer_id
GROUP BY c.customer_id;

Logic:

  1. LEFT JOIN keeps every customer.
  2. MIN and MAX of the purchase date are calculated per customer.
  3. Customers without purchases get NULL for both dates.
Concept

Left join with aggregates.

74. Find the percentage difference between each month’s total sales and the previous month’s total sales.

SQL
WITH monthly_sales AS (
    SELECT DATE_TRUNC('month', sale_date) AS month, SUM(amount) AS total_sales
    FROM sales
    GROUP BY month
)
SELECT month, total_sales,
    (total_sales - LAG(total_sales) OVER (ORDER BY month)) * 100.0 / LAG(total_sales) OVER (ORDER BY month) AS pct_change
FROM monthly_sales;

Logic:

  1. The CTE totals sales per month.
  2. LAG(total_sales) retrieves the previous month's total.
  3. (current - previous) * 100.0 / previous gives the percentage difference.
Concept

Month-over-month growth.

Important

The first month returns NULL, and a previous total of 0 would cause division by zero. Use NULLIF(previous, 0) to avoid the error. This assumes every month has at least one sale.

75. Write a query to find employees who have the longest tenure within their department.

SQL
WITH tenure AS (
    SELECT *, RANK() OVER (PARTITION BY department_id
        ORDER BY hire_date ASC) AS tenure_rank
    FROM employees
)
SELECT *
FROM tenure
WHERE tenure_rank = 1;

Logic:

  1. RANK() OVER (PARTITION BY department_id ORDER BY hire_date ASC) ranks employees by hire date within each department.
  2. Rank 1 is the earliest hire.
Concept

Ranking within groups.

Note

Employees hired on the same earliest date all receive rank 1, so ties are returned.

76. Generate a report that shows sales and sales growth percentage compared to the same month last year.

SQL
WITH monthly_sales AS (
    SELECT DATE_TRUNC('month', sale_date) AS month, SUM(amount) AS total_sales
    FROM sales
    GROUP BY month
)
SELECT ms1.month, ms1.total_sales,
    ((ms1.total_sales - ms2.total_sales) * 100.0 / ms2.total_sales) AS growth_pct
FROM monthly_sales ms1
LEFT JOIN monthly_sales ms2 ON ms1.month = ms2.month + INTERVAL '1 year';

Logic:

  1. The CTE totals sales per month.
  2. The self join matches each month (ms1) with the same month one year earlier (ms2): ms1.month = ms2.month + INTERVAL '1 year'.
  3. The growth percentage compares the two totals.
Concept

Year-over-year comparison with a self join.

Note

LEFT JOIN keeps months that have no prior-year data; their growth is NULL.

77. Write a query to identify overlapping shifts for employees.

SQL
SELECT s1.employee_id, s1.shift_id AS shift1, s2.shift_id AS shift2
FROM shifts s1
JOIN shifts s2 ON s1.employee_id = s2.employee_id
    AND s1.shift_id <> s2.shift_id
WHERE s1.start_time < s2.end_time AND s1.end_time > s2.start_time;

Logic:

  1. Join each shift to the other shifts of the same employee.
  2. Two shifts overlap when each starts before the other ends.
  3. s1.shift_id <> s2.shift_id excludes comparing a shift with itself.
Concept

Interval overlap with a self join.

Important

Every overlapping pair is returned twice. Use s1.shift_id < s2.shift_id to list each pair once.

78. Calculate the total revenue for each customer, and rank them from highest to lowest spender.

SQL
SELECT customer_id, SUM(amount) AS total_revenue,
    RANK() OVER (ORDER BY SUM(amount) DESC) AS revenue_rank
FROM sales
GROUP BY customer_id;

Logic:

  1. SUM(amount) is the total revenue per customer.
  2. RANK() OVER (ORDER BY SUM(amount) DESC) ranks customers by that total.
Concept

Window function applied to an aggregate.

Note

Window functions are evaluated after GROUP BY, which is why they can use aggregates like SUM().

79. Write a query to find the employee(s) who have never received a promotion.

SQL
SELECT e.*
FROM employees e
LEFT JOIN promotions p ON e.id = p.employee_id
WHERE p.employee_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all promotions columns.
  3. WHERE p.employee_id IS NULL keeps only the employees rows that have no match in promotions.
Concept

Anti-join using LEFT JOIN … IS NULL.

80. Write a query to find the top 3 products with the highest total sales amount each month.

SQL
WITH monthly_product_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, month
), ranked_sales AS (
    SELECT *, RANK() OVER (PARTITION BY month
        ORDER BY total_sales DESC) AS sales_rank
    FROM monthly_product_sales
)
SELECT product_id, month, total_sales
FROM ranked_sales
WHERE sales_rank <= 3
ORDER BY month, sales_rank;

Logic:

  1. The first CTE totals sales per product per month.
  2. The second CTE ranks products within each month.
  3. The final query keeps ranks 1 to 3.
Concept

Top-N per group using RANK().

Note

RANK() can return more than 3 rows when products tie. Use ROW_NUMBER() for exactly 3.

SQL Interview Questions 81–115 — Medium to Advanced

81. Find the customers who placed orders only in the last 30 days.

SQL
SELECT DISTINCT customer_id
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '30 days'
    AND customer_id NOT IN (
    SELECT DISTINCT customer_id
    FROM orders
    WHERE order_date < CURRENT_DATE - INTERVAL '30 days'
);

Logic:

  1. Find customers with at least one order in the last 30 days.
  2. Exclude customers who have any order older than 30 days (NOT IN).

Alternative with a single aggregate (all orders are recent when the oldest one is recent):

SQL
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING MIN(order_date) >= CURRENT_DATE - INTERVAL '30 days';
Concept

Filtering with a subquery.

Important

NOT IN returns no rows if the subquery contains a NULL customer id. Make sure customer_id is never NULL, or use NOT EXISTS.

82. Find products that have never been ordered.

SQL
SELECT p.product_id, p.product_name
FROM products p
LEFT JOIN orders o ON p.product_id = o.product_id
WHERE o.order_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from products.
  2. Rows without a match have NULL in all orders columns.
  3. WHERE o.order_id IS NULL keeps only the products rows that have no match in orders.
Concept

Anti-join using LEFT JOIN … IS NULL.

83. Find employees whose salary is above their department’s average but below the overall average salary.

SQL
SELECT *
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id)
    AND salary < (SELECT AVG(salary) FROM employees);

Logic:

  1. The first subquery is correlated: it calculates the average salary of the employee's own department.
  2. The second subquery calculates the overall average.
  3. Both conditions must hold.
Concept

Correlated subquery.

Note

This is the same pattern as Question 66.

84. Calculate the total sales amount and number of orders per customer in the last year.

SQL
SELECT customer_id, COUNT(*) AS total_orders, SUM(amount) AS total_sales
FROM sales
WHERE sale_date >= CURRENT_DATE - INTERVAL '1 year'
GROUP BY customer_id;

Logic:

  1. Filter sales from the last year with WHERE.
  2. Group by customer.
  3. COUNT(*) gives the number of orders and SUM(amount) the total sales.
Concept

Filtered aggregation.

85. List the top 5 highest-paid employees per department.

SQL
SELECT *
FROM (
    SELECT e.*,
        ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
    FROM employees e
) sub
WHERE rn <= 5;

Logic:

  1. ROW_NUMBER() ranks employees by salary inside each department.
  2. rn <= 5 keeps the top five.
Concept

Top-N per group.

Note

Use DENSE_RANK() if employees with equal salaries should all be included.

86. Write a query to identify “gaps and islands” in attendance records (consecutive dates present).

SQL
WITH attendance_groups AS (
    SELECT employee_id, attendance_date,
        attendance_date - INTERVAL ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY attendance_date) DAY AS grp
    FROM attendance
)
SELECT employee_id, MIN(attendance_date) AS start_date,
    MAX(attendance_date) AS end_date, COUNT(*) AS consecutive_days
FROM attendance_groups
GROUP BY employee_id, grp
ORDER BY employee_id, start_date;

Logic:

  1. Number each employee's attendance dates in order.
  2. Subtracting that row number (as days) from the date gives the same value for consecutive dates.
  3. Grouping by that value produces the islands, with start date, end date and length.
Concept

Gaps and islands technique.

Important

The INTERVAL ROW_NUMBER() ... DAY syntax is MySQL-style. In PostgreSQL use attendance_date - (ROW_NUMBER() OVER (...))::int. Duplicate dates should be removed first (see Question 9).

87. Write a recursive query to list all descendants of a manager in an organizational hierarchy.

SQL
WITH RECURSIVE descendants AS (
    SELECT id, name, manager_id
    FROM employees
    WHERE manager_id = 100 -- starting manager id
    UNION ALL
    SELECT e.id, e.name, e.manager_id
    FROM employees e
    INNER JOIN descendants d ON e.manager_id = d.id
)
SELECT * FROM descendants;

Logic:

  1. The anchor selects the manager's direct reports (manager_id = 100).
  2. Each recursion adds the employees who report to anyone already found.
  3. The result contains everyone below the manager at all levels.
Concept

Recursive CTE walking down a hierarchy.

88. Calculate a 3-month moving average of monthly sales per product.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, month
)
SELECT product_id, month, total_sales,
    AVG(total_sales) OVER (PARTITION BY product_id ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg
FROM monthly_sales;

Logic:

  1. The CTE totals sales per product per month.
  2. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW creates a window of the current and previous two months.
  3. AVG(total_sales) averages that window.
Concept

Moving average per group.

Important

The window counts rows, not calendar months. If a product has months with no sales, the average will span a longer period unless the missing months are filled in.

89. Write a query to find employees who have the same hire date as their managers.

SQL
SELECT e.name AS employee_name, m.name AS manager_name, e.hire_date
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.hire_date = m.hire_date;

Logic:

  1. Self join each employee to their manager.
  2. Keep rows where both hire dates are equal.
Concept

Self join with an equality comparison.

90. Write a query to find products with increasing sales over the last 3 months.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, month
), ranked_sales AS (
    SELECT product_id, month, total_sales,
        ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY month DESC) AS rn
    FROM monthly_sales
)
SELECT ms1.product_id
FROM ranked_sales ms1
JOIN ranked_sales ms2 ON ms1.product_id = ms2.product_id AND ms1.rn = 1 AND ms2.rn = 2
JOIN ranked_sales ms3 ON ms1.product_id = ms3.product_id AND ms3.rn = 3
WHERE ms3.total_sales < ms2.total_sales AND ms2.total_sales < ms1.total_sales;

Logic:

  1. The first CTE totals sales per product per month.
  2. The second CTE numbers months from newest (rn = 1) to oldest.
  3. Joining the latest three months, the query keeps products where month 3 < month 2 < month 1.
Concept

Trend detection with ranked rows.

Important

It assumes the three latest rows are consecutive months. Products with fewer than three months of data are excluded.

91. Write a query to get the nth highest salary per department.

SQL
SELECT department_id, salary
FROM (
    SELECT department_id, salary,
        ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
    FROM employees
) sub
WHERE rn = N;

Logic:

  1. ROW_NUMBER() numbers salaries from highest to lowest within each department.
  2. rn = N keeps the Nth row.
Concept

Nth value per group.

Note

Replace N with a number. If salaries can repeat, use DENSE_RANK() so the Nth distinct salary is returned.

92. Find employees who have managed more than 3 projects.

SQL
SELECT manager_id, COUNT(DISTINCT project_id) AS project_count
FROM projects
GROUP BY manager_id
HAVING COUNT(DISTINCT project_id) > 3;

Logic:

  1. Group projects by manager.
  2. COUNT(DISTINCT project_id) counts the unique projects.
  3. HAVING keeps managers with more than three.
Concept

Distinct count with HAVING.

93. Write a query to calculate the difference in days between each employee's hire date and their manager’s hire date.

SQL
SELECT e.name AS employee, m.name AS manager,
    DATEDIFF(day, m.hire_date, e.hire_date) AS days_difference
FROM employees e
JOIN employees m ON e.manager_id = m.id;

Logic:

  1. Self join each employee to their manager.
  2. DATEDIFF(day, m.hire_date, e.hire_date) returns the days from the manager's hire date to the employee's.
Concept

Date difference in a self join.

Note

The result is positive when the employee was hired after the manager. DATEDIFF syntax varies by database (see Question 26).

94. Write a query to find the department with the highest average years of experience.

SQL
SELECT department_id,
    AVG(EXTRACT(year FROM CURRENT_DATE - hire_date)) AS avg_experience_years
FROM employees
GROUP BY department_id
ORDER BY avg_experience_years DESC
LIMIT 1;

Logic:

  1. Subtract the hire date from today to get years of experience.
  2. AVG() per department gives the average.
  3. ORDER BY ... DESC LIMIT 1 returns the highest.
Concept

Aggregation with ORDER BY and LIMIT.

Important

EXTRACT(year FROM CURRENT_DATE - hire_date) works only when hire_date is a TIMESTAMP. For DATE columns in PostgreSQL, use AVG(CURRENT_DATE - hire_date) / 365.25.

95. Identify employees who had overlapping project assignments.

SQL
SELECT p1.employee_id, p1.project_id AS project1, p2.project_id AS project2
FROM project_assignments p1
JOIN project_assignments p2 ON p1.employee_id = p2.employee_id AND p1.project_id <> p2.project_id
WHERE p1.start_date < p2.end_date AND p1.end_date > p2.start_date;

Logic:

  1. Join each assignment to other assignments of the same employee.
  2. Two assignments overlap when each starts before the other ends.
Concept

Interval overlap test.

Important

Each pair is returned twice. Use p1.project_id < p2.project_id to return it once.

96. Find customers who made purchases in every month of the current year.

SQL
WITH months AS (
    SELECT generate_series(1, 12) AS month
), customer_months AS (
    SELECT customer_id, EXTRACT(MONTH FROM purchase_date) AS month
    FROM sales
    WHERE EXTRACT(YEAR FROM purchase_date) = EXTRACT(YEAR FROM CURRENT_DATE)
    GROUP BY customer_id, EXTRACT(MONTH
        FROM purchase_date)
)
SELECT customer_id
FROM customer_months
GROUP BY customer_id
HAVING COUNT(DISTINCT month) = 12;

Logic:

  1. The first CTE (months) lists 1 to 12, although the final query does not need it.
  2. The second CTE finds the distinct months in which each customer purchased this year.
  3. Customers with 12 distinct months qualify.
Concept

Relational division with counts.

Note

The simplest check is the final HAVING COUNT(DISTINCT month) = 12; the months CTE can be removed.

97. List employees who earn more than all their subordinates.

SQL
SELECT e.id, e.name, e.salary
FROM employees e
WHERE e.salary > ALL (
    SELECT salary
    FROM employees sub
    WHERE sub.manager_id = e.id
);

Logic:

  1. The subquery returns the salaries of the employee's direct reports.
  2. salary > ALL (...) is true when the salary is higher than every one of them.
Concept

ALL with a correlated subquery.

Important

If an employee has no subordinates, > ALL over an empty set is true, so non-managers are also returned. Add a check that at least one subordinate exists if only managers are wanted.

98. Get the product with the highest sales for each category.

SQL
WITH category_sales AS (
    SELECT category_id, product_id, SUM(amount) AS total_sales,
        RANK() OVER (PARTITION BY category_id
        ORDER BY SUM(amount) DESC) AS sales_rank
    FROM sales
    GROUP BY category_id, product_id
)
SELECT category_id, product_id, total_sales
FROM category_sales
WHERE sales_rank = 1;

Logic:

  1. Total the sales of each product within its category.
  2. RANK() orders products by total sales inside each category.
  3. Rank 1 is the top product.
Concept

Top-1 per group.

Note

Tied products all receive rank 1.

99. Find customers who haven’t ordered in the last 6 months.

SQL
SELECT customer_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id
HAVING MAX(o.order_date) < CURRENT_DATE - INTERVAL '6 months' OR MAX(o.order_date) IS NULL;

Logic:

  1. LEFT JOIN customers to their orders.
  2. MAX(o.order_date) is each customer's most recent order.
  3. Customers whose latest order is older than six months, or who never ordered, are returned.
Concept

Aggregation after a left join.

Important

customer_id exists in both tables, so SELECT customer_id is ambiguous and raises an error. Use c.customer_id.

Corrected version:

SQL
SELECT c.customer_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.customer_id
HAVING MAX(o.order_date) < CURRENT_DATE - INTERVAL '6 months'
    OR MAX(o.order_date) IS NULL;

100. Find the maximum salary gap between any two employees within the same department.

SQL
SELECT department_id, MAX(salary) - MIN(salary) AS salary_gap
FROM employees
GROUP BY department_id;

Logic:

  1. In each department, MAX(salary) - MIN(salary) is the largest difference between any two employees.
Concept

Range of values per group.

101. Write a recursive query to compute the total budget under each manager (including subordinates).

SQL
WITH RECURSIVE manager_budget AS (
    SELECT id, manager_id, budget
    FROM departments
    UNION ALL
    SELECT d.id, d.manager_id, mb.budget
    FROM departments d
    JOIN manager_budget mb ON d.manager_id = mb.id
)
SELECT manager_id, SUM(budget) AS total_budget
FROM manager_budget
GROUP BY manager_id;

Logic:

  1. The recursion collects every unit that reports, directly or indirectly, to each starting unit.
  2. Summing the budgets of the collected units gives the total under each manager.
Concept

Recursive roll-up of a hierarchy.

Important

The query in the PDF copies the parent's budget onto child rows, so the totals are incorrect. The version below keeps the original starting unit (root_id) and sums the budgets of all its descendants, assuming manager_id points to the parent row.

Corrected roll-up:

SQL
WITH RECURSIVE tree AS (
    SELECT id AS root_id, id, budget
    FROM departments
    UNION ALL
    SELECT t.root_id, d.id, d.budget
    FROM departments d
    JOIN tree t ON d.manager_id = t.id
)
SELECT root_id AS manager_id, SUM(budget) AS total_budget
FROM tree
GROUP BY root_id;

102. Write a query to detect gaps in a sequence of invoice numbers.

SQL
WITH numbered_invoices AS (
    SELECT invoice_number, ROW_NUMBER() OVER (ORDER BY invoice_number) AS rn
    FROM invoices
)
SELECT invoice_number + 1 AS missing_invoice
FROM numbered_invoices ni
WHERE (invoice_number + 1) <> (
    SELECT invoice_number FROM numbered_invoices
    WHERE rn = ni.rn + 1
);

Logic:

  1. Number the invoices in sorted order (rn).
  2. For each invoice, compare invoice_number + 1 with the next invoice (rn + 1).
  3. If they differ, the number after the current invoice is missing.
Concept

Gap detection with row numbers.

Note

The last invoice has no next row, so the subquery returns NULL and it is not reported. LEAD(invoice_number) is a simpler alternative.

103. Calculate the rank of employees by salary within their department but restart rank numbering every 10 employees.

SQL
WITH ranked_employees AS (
    SELECT e.*,
        ROW_NUMBER() OVER (PARTITION BY department_id ORDER BY salary DESC) AS rn
    FROM employees e
)
SELECT *, ((rn - 1) / 10) + 1 AS rank_group
FROM ranked_employees;

Logic:

  1. ROW_NUMBER() numbers employees by salary within each department.
  2. ((rn - 1) / 10) + 1 converts the position into a block number (1 for rows 1–10, 2 for rows 11–20, and so on).
Concept

Bucketing rows with integer division.

Note

To restart the numbering itself in each block (1–10, 1–10, …) use ((rn - 1) % 10) + 1. The division works as integer division in PostgreSQL and SQL Server when rn is an integer.

104. Find the moving median of daily sales over the last 7 days for each product.

SQL
WITH daily_sales AS (
    SELECT product_id, sale_date, SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, sale_date
)
SELECT product_id, sale_date,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY total_sales) OVER (PARTITION BY product_id ORDER BY sale_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS moving_median
FROM daily_sales;

Logic:

  1. The CTE totals sales per product per day.
  2. The median is calculated over a 7-row window.
  3. The result is one moving median per product and day.
Concept

Moving statistics.

Important

No major database allows PERCENTILE_CONT ... WITHIN GROUP with a window frame. Use a correlated subquery over the last 7 days instead (PostgreSQL).

Working version:

SQL
WITH daily_sales AS (
    SELECT product_id, sale_date, SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, sale_date
)
SELECT d1.product_id, d1.sale_date,
    (SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY d2.total_sales)
     FROM daily_sales d2
     WHERE d2.product_id = d1.product_id
         AND d2.sale_date BETWEEN d1.sale_date - 6 AND d1.sale_date) AS moving_median
FROM daily_sales d1;

105. Find customers who purchased both product A and product B.

SQL
SELECT customer_id
FROM sales
WHERE product_id IN ('A', 'B')
GROUP BY customer_id
HAVING COUNT(DISTINCT product_id) = 2;

Logic:

  1. Keep only sales of products A and B.
  2. Group by customer and count the distinct products.
  3. A count of 2 means the customer bought both.
Concept

Relational division with COUNT(DISTINCT).

106. Write a query to generate a calendar table with all dates for the current year.

SQL
SELECT generate_series(DATE_TRUNC('year', CURRENT_DATE), DATE_TRUNC('year', CURRENT_DATE) + INTERVAL '1 year' - INTERVAL '1 day', INTERVAL '1 day'
) AS calendar_date;

Logic:

  1. generate_series(start, end, step) produces one row per day.
  2. The start is the first day of the current year and the end is the last day (one year later minus one day).
Concept

Date generation.

Note

generate_series is PostgreSQL. Other databases use a recursive CTE to generate dates. Cast the result with ::date if you want DATE instead of TIMESTAMP.

107. Find employees who have worked in more than 3 different departments.

SQL
SELECT employee_id
FROM employee_department_history
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id) > 3;

Logic:

  1. Group the department history by employee.
  2. Count the distinct departments.
  3. Keep employees with more than three.
Concept

Distinct count in HAVING.

108. Calculate the percentage contribution of each product’s sales to the total sales per month.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS product_sales
    FROM sales
    GROUP BY product_id, month
), total_monthly_sales AS (
    SELECT month, SUM(product_sales) AS total_sales
    FROM monthly_sales
    GROUP BY month
)
SELECT ms.product_id, ms.month, ms.product_sales,
    (ms.product_sales * 100.0) / tms.total_sales AS pct_contribution
FROM monthly_sales ms
JOIN total_monthly_sales tms ON ms.month = tms.month;

Logic:

  1. The first CTE totals each product's sales per month.
  2. The second CTE totals all sales per month.
  3. Joining them, product_sales * 100.0 / total_sales is each product's share of the month.
Concept

Share of total using CTEs.

Note

A window function gives the same result: SUM(product_sales) OVER (PARTITION BY month).

109. Write a query to pivot monthly sales data for each product into columns.

SQL
SELECT product_id,
    SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 1 THEN amount ELSE 0 END) AS Jan,
    SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 2 THEN amount ELSE 0 END) AS Feb,
    -- repeat the same pattern for March to November
    SUM(CASE WHEN EXTRACT(MONTH FROM sale_date) = 12 THEN amount ELSE 0 END) AS Dec
FROM sales
GROUP BY product_id;

Logic:

  1. Each CASE returns the sale amount for one month and 0 for all others.
  2. SUM() adds up the amounts for that month.
  3. GROUP BY product_id returns one row per product with one column per month.
Concept

Pivot with conditional aggregation.

Note

The query lists January, February and December. Repeat the same pattern for March to November. The listing above is shown with the comment placeholder so the SQL stays valid.

110. Find the 3 most recent orders per customer including order details.

SQL
SELECT *
FROM (
    SELECT o.*,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
    FROM orders o
) sub
WHERE rn <= 3;

Logic:

  1. Number each customer's orders from newest to oldest.
  2. Keep rows where the number is 3 or less.
Concept

Top-N per group.

111. Find employees who have never taken any leave.

SQL
SELECT e.*
FROM employees e
LEFT JOIN leaves l ON e.id = l.employee_id
WHERE l.leave_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all leaves columns.
  3. WHERE l.leave_id IS NULL keeps only the employees rows that have no match in leaves.
Concept

Anti-join using LEFT JOIN … IS NULL.

112. List customers who placed orders in January but not in February.

SQL
WITH jan_orders AS (
    SELECT DISTINCT customer_id
    FROM orders
    WHERE EXTRACT(MONTH FROM order_date) = 1
), feb_orders AS (
    SELECT DISTINCT customer_id
    FROM orders
    WHERE EXTRACT(MONTH FROM order_date) = 2
)
SELECT customer_id
FROM jan_orders
WHERE customer_id NOT IN (SELECT customer_id
    FROM feb_orders);

Logic:

  1. The first CTE lists customers who ordered in January.
  2. The second CTE lists customers who ordered in February.
  3. The final query keeps January customers who are not in the February list.
Concept

Set difference with NOT IN.

Important

The month filter ignores the year, so January and February of different years are mixed. Add a year filter if needed. NOT IN also fails if the list contains NULL; NOT EXISTS or EXCEPT is safer.

113. Find products that have seen a price increase in the last 6 months.

SQL
WITH price_changes AS (
    SELECT product_id, price, effective_date,
        LAG(price) OVER (PARTITION BY product_id
        ORDER BY effective_date) AS prev_price
    FROM product_prices
    WHERE effective_date >= CURRENT_DATE - INTERVAL '6 months'
)
SELECT DISTINCT product_id
FROM price_changes
WHERE price > prev_price;

Logic:

  1. LAG(price) returns the previous price of the same product.
  2. Rows where the current price is higher than the previous price are price increases.
  3. DISTINCT returns each product once.
Concept

Change detection with LAG().

Note

Because the date filter is applied first, the oldest row inside the six-month window has no previous price and is never compared with an earlier price.

114. Find the department(s) with the second highest average salary.

SQL
WITH avg_salaries AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
), ranked_salaries AS (
    SELECT department_id, avg_salary,
        DENSE_RANK() OVER (ORDER BY avg_salary DESC) AS rnk
    FROM avg_salaries
)
SELECT department_id, avg_salary
FROM ranked_salaries
WHERE rnk = 2;

Logic:

  1. The first CTE calculates each department's average salary.
  2. DENSE_RANK() ranks those averages from highest to lowest.
  3. Rank 2 is the second-highest average.
Concept

Nth value using DENSE_RANK().

Note

DENSE_RANK() ensures that ties for the highest average do not skip rank 2.

115. Find employees who joined in the same month and year.

SQL
SELECT e1.id AS emp1_id, e2.id AS emp2_id, e1.hire_date
FROM employees e1
JOIN employees e2 ON e1.id <> e2.id
    AND EXTRACT(MONTH FROM e1.hire_date) = EXTRACT(MONTH FROM e2.hire_date)
    AND EXTRACT(YEAR FROM e1.hire_date) = EXTRACT(YEAR FROM e2.hire_date);

Logic:

  1. Self join employees on equal hire month and hire year.
  2. e1.id <> e2.id avoids pairing an employee with themselves.
Concept

Self join on derived date parts.

Important

Each pair appears twice. Use e1.id < e2.id to return it once.

SQL Interview Questions 116–140 — Advanced Level

116. Write a recursive query to find all employees and their level of reporting (distance from CEO).

SQL
WITH RECURSIVE hierarchy AS (
    SELECT id, name, manager_id, 1 AS level
    FROM employees
    WHERE manager_id IS NULL -- CEO level
    UNION ALL
    SELECT e.id, e.name, e.manager_id, h.level + 1
    FROM employees e
    JOIN hierarchy h ON e.manager_id = h.id
)
SELECT * FROM hierarchy ORDER BY level, manager_id;

Logic:

  1. The anchor selects the CEO (no manager) at level 1.
  2. Each recursion adds employees who report to the previous level with level + 1.
  3. The final query shows every employee with their distance from the CEO.
Concept

Recursive CTE with a level counter.

117. Find the second highest salary per department without using window functions.

SQL
SELECT department_id, MAX(salary) AS second_highest_salary
FROM employees e1
WHERE salary < (
    SELECT MAX(salary)
    FROM employees e2
    WHERE e2.department_id = e1.department_id
)
GROUP BY department_id;

Logic:

  1. The correlated subquery finds each department's highest salary.
  2. salary < that value removes the top earners.
  3. MAX(salary) of the remaining rows is the second highest.
Concept

Second highest per group using subqueries.

Note

Departments where all employees share one salary are not returned.

118. Calculate the percentage change in sales for each product comparing current month to previous month.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, month
)
SELECT product_id, month, total_sales,
    (total_sales - LAG(total_sales) OVER (PARTITION BY product_id ORDER BY month)) * 100.0 / LAG(total_sales) OVER (PARTITION BY product_id ORDER BY month) AS pct_change
FROM monthly_sales;

Logic:

  1. The CTE totals sales per product per month.
  2. LAG() retrieves the previous month for the same product.
  3. The percentage change is (current - previous) * 100.0 / previous.
Concept

Month-over-month change per product.

Note

This is the same pattern as Question 35. Use NULLIF(previous, 0) to avoid division by zero.

119. Write a query to identify duplicate rows (all columns) in a table.

SQL
SELECT *, COUNT(*) OVER (PARTITION BY col1, col2, col3, ...) AS cnt
FROM table_name
WHERE cnt > 1;

Logic:

  1. COUNT(*) OVER (PARTITION BY ...) counts how many rows share the same column values.
  2. Rows whose count is above 1 are duplicates.
Concept

Duplicate detection with a window function.

Important

WHERE cnt > 1 cannot reference a window-function alias in the same query level, and ... must be replaced with the real column names. Wrap the query in a subquery as shown.

Corrected version (list every column in PARTITION BY):

SQL
SELECT *
FROM (
    SELECT t.*, COUNT(*) OVER (PARTITION BY col1, col2, col3) AS cnt
    FROM table_name t
) x
WHERE cnt > 1;

120. Write a query to unpivot quarterly sales data into rows.

SQL
SELECT product_id, 'Q1' AS quarter, Q1_sales AS sales FROM sales_data
UNION ALL
SELECT product_id, 'Q2', Q2_sales FROM sales_data
UNION ALL
SELECT product_id, 'Q3', Q3_sales FROM sales_data
UNION ALL
SELECT product_id, 'Q4', Q4_sales FROM sales_data;

Logic:

  1. Each SELECT takes one quarter column and turns it into a row with a quarter label.
  2. UNION ALL stacks the four result sets into one.
Concept

Unpivot with UNION ALL.

Note

SQL Server has UNPIVOT, and PostgreSQL can use CROSS JOIN LATERAL (VALUES ...). UNION ALL works everywhere.

121. Find employees whose salary is above the average salary of their department but below the company-wide average.

SQL
SELECT *
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id)
    AND salary < (SELECT AVG(salary) FROM employees);

Logic:

  1. The first subquery is correlated and returns the employee's department average.
  2. The second returns the company-wide average.
  3. Both conditions must be true.
Concept

Correlated subquery.

Note

This is the same pattern as Questions 66 and 83.

122. Write a query to find customers with the highest purchase amount per year.

SQL
WITH yearly_sales AS (
    SELECT customer_id, EXTRACT(YEAR FROM sale_date) AS year,
        SUM(amount) AS total_amount
    FROM sales
    GROUP BY customer_id, year
), ranked_sales AS (
    SELECT *, RANK() OVER (PARTITION BY year
        ORDER BY total_amount DESC) AS rnk
    FROM yearly_sales
)
SELECT customer_id, year, total_amount
FROM ranked_sales
WHERE rnk = 1;

Logic:

  1. The first CTE totals each customer's purchases per year.
  2. RANK() orders customers by total within each year.
  3. Rank 1 is the top customer for that year.
Concept

Top-1 per group.

123. Write a query to list all employees who have a salary equal to the average salary of their department.

SQL
SELECT e.*
FROM employees e
JOIN (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
) d ON e.department_id = d.department_id AND e.salary = d.avg_salary;

Logic:

  1. The derived table calculates each department's average salary.
  2. Joining on department and salary = avg_salary returns employees who earn exactly that average.
Concept

Join to an aggregated subquery.

Note

Averages are often fractional, so an exact match is rare. Round both sides if you want a tolerance.

124. Find the first order date for each customer.

SQL
SELECT customer_id, MIN(order_date) AS first_order_date
FROM orders
GROUP BY customer_id;

Logic:

  1. GROUP BY customer_id creates one group per customer.
  2. MIN(order_date) is the first order.
Concept

MIN aggregate.

125. Find employees who have been promoted more than twice.

SQL
SELECT employee_id, COUNT(*) AS promotion_count
FROM promotions
GROUP BY employee_id
HAVING COUNT(*) > 2;

Logic:

  1. Group promotions by employee.
  2. COUNT(*) counts promotions.
  3. HAVING COUNT(*) > 2 keeps employees with at least three.
Concept

Counting rows per group.

126. Find employees who have not been assigned to any project.

SQL
SELECT e.*
FROM employees e
LEFT JOIN project_assignments pa ON e.id = pa.employee_id
WHERE pa.project_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all project_assignments columns.
  3. WHERE pa.project_id IS NULL keeps only the employees rows that have no match in project_assignments.
Concept

Anti-join using LEFT JOIN … IS NULL.

127. Find the total sales per customer including those with zero sales.

SQL
SELECT c.customer_id, COALESCE(SUM(s.amount), 0) AS total_sales
FROM customers c
LEFT JOIN sales s ON c.customer_id = s.customer_id
GROUP BY c.customer_id;

Logic:

  1. LEFT JOIN keeps every customer.
  2. SUM(s.amount) is NULL for customers without sales.
  3. COALESCE(..., 0) converts it to 0.
Concept

Left join with COALESCE.

128. Find the highest salary by department and the employee(s) who earn it.

SQL
WITH dept_max AS (
    SELECT department_id, MAX(salary) AS max_salary
    FROM employees
    GROUP BY department_id
)
SELECT e.*
FROM employees e
JOIN dept_max d ON e.department_id = d.department_id AND e.salary = d.max_salary;

Logic:

  1. The CTE finds each department's maximum salary.
  2. Joining back to employees on department and salary returns the employee(s) who earn it.
Concept

Join back to a group maximum.

Note

All employees tied for the highest salary are returned.

129. Find customers with no orders in the last year.

SQL
SELECT customer_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id AND o.order_date >= CURRENT_DATE - INTERVAL '1 year'
WHERE o.order_id IS NULL;

Logic:

  1. LEFT JOIN orders, but only those from the last year (condition in ON).
  2. Customers without such orders have NULL order columns.
  3. WHERE o.order_id IS NULL returns them.
Concept

Anti-join with a date filter.

Important

Keep the date condition in ON. In WHERE it would remove the NULL rows and return nothing.

130. Find employees whose salary is within 10% of the highest salary in their department.

SQL
WITH dept_max AS (
    SELECT department_id, MAX(salary) AS max_salary
    FROM employees
    GROUP BY department_id
)
SELECT e.*
FROM employees e
JOIN dept_max d ON e.department_id = d.department_id
WHERE e.salary >= 0.9 * d.max_salary;

Logic:

  1. The CTE finds each department's maximum salary.
  2. salary >= 0.9 * max_salary keeps employees earning at least 90% of it.
Concept

Threshold relative to a group maximum.

131. Find the running total of sales by date.

SQL
SELECT sale_date,
    SUM(amount) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total
FROM sales
ORDER BY sale_date;

Logic:

  1. ORDER BY sale_date orders the rows.
  2. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW adds all rows from the beginning up to the current row.
Concept

Running total with an explicit frame.

Note

If there are several rows per date, each row shows a different partial total. Group by date first for one row per day.

132. Find employees who earn more than the average salary of the entire company.

SQL
SELECT *
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Logic:

  1. The subquery calculates the company average.
  2. The outer query keeps salaries above it.
Concept

Scalar subquery.

133. Get the last 3 orders placed by each customer.

SQL
SELECT *
FROM (
    SELECT o.*,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
    FROM orders o
) sub
WHERE rn <= 3;

Logic:

  1. Number each customer's orders from newest to oldest.
  2. Keep the first three.
Concept

Top-N per group.

134. Find the difference in days between the earliest and latest orders per customer.

SQL
SELECT customer_id, MAX(order_date) - MIN(order_date) AS days_between
FROM orders
GROUP BY customer_id;

Logic:

  1. MAX(order_date) - MIN(order_date) is the number of days between a customer's first and last order.
Concept

Date arithmetic with aggregates.

Note

For DATE columns PostgreSQL returns an integer number of days; for TIMESTAMP it returns an interval.

135. Find employees who have worked on all projects.

SQL
SELECT employee_id
FROM project_assignments
GROUP BY employee_id
HAVING COUNT(DISTINCT project_id) = (SELECT COUNT(*) FROM projects);

Logic:

  1. Count the distinct projects each employee worked on.
  2. Compare with the total number of projects.
  3. Equal counts mean the employee worked on every project.
Concept

Relational division.

136. Find customers who placed orders only in the last 6 months.

SQL
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING MIN(order_date) >= CURRENT_DATE - INTERVAL '6 months';

Logic:

  1. MIN(order_date) is a customer's oldest order.
  2. If the oldest order is within the last six months, every order is.
Concept

Condition on MIN() in HAVING.

137. Get the total number of orders per day, including days with zero orders.

SQL
WITH dates AS (
    SELECT generate_series(MIN(order_date), MAX(order_date), INTERVAL '1 day') AS day
    FROM orders
)
SELECT d.day, COUNT(o.order_id) AS order_count
FROM dates d
LEFT JOIN orders o ON d.day = o.order_date
GROUP BY d.day
ORDER BY d.day;

Logic:

  1. The CTE generates every date between the first and last order.
  2. LEFT JOIN orders to the dates.
  3. COUNT(o.order_id) returns 0 for days without orders.
Concept

Filling missing dates with generate_series.

Important

If order_date is a TIMESTAMP with a time part, d.day = o.order_date will not match. Join on o.order_date::date instead.

138. Find the department with the most employees.

SQL
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
ORDER BY employee_count DESC
LIMIT 1;

Logic:

  1. Count employees per department.
  2. Sort by the count in descending order.
  3. LIMIT 1 returns the largest department.
Concept

Top-1 group.

139. Write a query to find gaps in employee IDs.

SQL
WITH numbered AS (
    SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn
    FROM employees
)
SELECT rn + 1 AS missing_id
FROM numbered
WHERE id <> rn;

Logic:

  1. Look at each ID and the next ID in order (LEAD).
  2. A gap exists when the next ID is more than 1 higher.
  3. The missing range runs from id + 1 to next_id - 1.
Concept

Gap detection.

Important

The query in the PDF compares id with the row number: once a gap appears, every later row differs from its row number, and rn + 1 is not the missing ID. Use LEAD instead.

Corrected version:

SQL
SELECT id + 1 AS gap_start, next_id - 1 AS gap_end
FROM (
    SELECT id, LEAD(id) OVER (ORDER BY id) AS next_id
    FROM employees
) t
WHERE next_id - id > 1;

140. Find employees who were hired before their managers.

SQL
SELECT e.name AS employee, m.name AS manager, e.hire_date,
    m.hire_date AS manager_hire_date
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.hire_date < m.hire_date;

Logic:

  1. Self join each employee to their manager.
  2. e.hire_date < m.hire_date keeps employees who joined before their manager.
Concept

Self join with a date comparison.

SQL Interview Questions 141–165 — Advanced Level

141. List departments with average salary greater than the overall average.

SQL
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > (SELECT AVG(salary)
    FROM employees);

Logic:

  1. GROUP BY department_id gives each department's average salary.
  2. The scalar subquery calculates the overall average.
  3. HAVING keeps departments above it.
Concept

Group filter with a subquery.

142. Find employees with the highest number of dependents.

SQL
SELECT employee_id, COUNT(*) AS dependent_count
FROM dependents
GROUP BY employee_id
ORDER BY dependent_count DESC
LIMIT 1;

Logic:

  1. Count dependents per employee.
  2. Sort by the count descending and return the first row.
Concept

Top-1 group.

Note

Ties are not returned. Use RANK() to include all tied employees.

143. Find customers with the longest gap between two consecutive orders.

SQL
WITH ordered_orders AS (
    SELECT customer_id, order_date,
        LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_order_date
    FROM orders
), gaps AS (
    SELECT customer_id, order_date - prev_order_date AS gap_days
    FROM ordered_orders
    WHERE prev_order_date IS NOT NULL
)
SELECT customer_id, MAX(gap_days) AS longest_gap
FROM gaps
GROUP BY customer_id
ORDER BY longest_gap DESC
LIMIT 1;

Logic:

  1. LAG(order_date) finds each customer's previous order date.
  2. The difference between the two dates is the gap.
  3. MAX(gap_days) per customer is the longest gap.
Concept

Gap analysis with LAG().

Note

ORDER BY ... LIMIT 1 returns only the single customer with the largest gap. Remove them to list the longest gap of every customer.

144. Find customers who ordered all products in a category.

SQL
SELECT customer_id
FROM sales
WHERE product_id IN (SELECT product_id FROM products WHERE category_id = 1)
GROUP BY customer_id
HAVING COUNT(DISTINCT product_id) = (SELECT COUNT(*) FROM products WHERE category_id = 1);

Logic:

  1. Keep sales of products in category 1.
  2. Count the distinct products each customer bought.
  3. Compare with the number of products in the category.
Concept

Relational division.

Note

This is the same pattern as Question 67.

145. Get the most recent order date per customer.

SQL
SELECT customer_id, MAX(order_date) AS last_order_date
FROM orders
GROUP BY customer_id;

Logic:

  1. MAX(order_date) per customer is the latest order.
Concept

MAX aggregate.

146. List all employees and their manager names.

SQL
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

Logic:

  1. LEFT JOIN employees to themselves on manager_id = id.
  2. Employees without a manager are kept with NULL for the manager name.
Concept

Self left join.

147. Find employees with the same salary as their manager.

SQL
SELECT e.name AS employee, m.name AS manager, e.salary
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.salary = m.salary;

Logic:

  1. Self join each employee to their manager.
  2. Keep rows with equal salaries.
Concept

Self join with an equality comparison.

148. List products with sales above the average sales amount.

SQL
WITH avg_sales AS (
    SELECT AVG(amount) AS avg_amount
    FROM sales
)
SELECT product_id, SUM(amount) AS total_sales
FROM sales
GROUP BY product_id
HAVING SUM(amount) > (SELECT avg_amount
    FROM avg_sales);

Logic:

  1. The CTE calculates the average amount of an individual sale.
  2. Group sales by product and total them.
  3. HAVING keeps products whose total exceeds that average.
Concept

Group filter with a CTE.

Important

The average used is the average of single sales, not of product totals. To compare with the average product total, see Question 293.

149. Get the number of employees hired each year.

SQL
SELECT EXTRACT(YEAR FROM hire_date) AS hire_year, COUNT(*) AS count
FROM employees
GROUP BY hire_year
ORDER BY hire_year;

Logic:

  1. EXTRACT(YEAR FROM hire_date) gets the hire year.
  2. Grouping by year and counting gives hires per year.
Concept

Date part grouping.

150. Find the number of employees with the same job title per department.

SQL
SELECT department_id, job_title, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id, job_title;

Logic:

  1. Group by department and job title.
  2. COUNT(*) is the number of employees in each pair.
Concept

Multi-column grouping.

151. Find employees with no manager assigned.

SQL
SELECT *
FROM employees
WHERE manager_id IS NULL;

Logic:

  1. manager_id IS NULL finds employees without a manager.
Concept

NULL handling.

152. Calculate average salary by department and job title.

SQL
SELECT department_id, job_title, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id, job_title;

Logic:

  1. Grouping by department and title gives one row per combination.
  2. AVG(salary) is the average for that group.
Concept

Multi-column grouping.

153. Find the median salary of employees.

SQL
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees;

Logic:

  1. PERCENTILE_CONT(0.5) returns the middle value of the sorted salaries, averaging the two middle values when the count is even.
Concept

Median using an ordered-set aggregate.

Note

Supported by PostgreSQL, Oracle and SQL Server (as a window function). MySQL needs the LIMIT/OFFSET approach from Question 7.

154. Find employees who have been promoted more than once.

SQL
SELECT employee_id, COUNT(*) AS promotion_count
FROM promotions
GROUP BY employee_id
HAVING COUNT(*) > 1;

Logic:

  1. Group promotions by employee.
  2. HAVING COUNT(*) > 1 keeps employees promoted at least twice.
Concept

Counting rows per group.

155. Calculate total sales by product category.

SQL
SELECT p.category_id, SUM(s.amount) AS total_sales
FROM sales s
JOIN products p ON s.product_id = p.product_id
GROUP BY p.category_id;

Logic:

  1. Join sales to products to get each sale's category.
  2. Group by category and SUM(amount).
Concept

Join plus aggregation.

156. Find the top 3 products by sales amount.

SQL
SELECT product_id, SUM(amount) AS total_sales
FROM sales
GROUP BY product_id
ORDER BY total_sales DESC
LIMIT 3;

Logic:

  1. Total sales per product.
  2. Sort descending and keep the first three rows.
Concept

Top-N with LIMIT.

Note

Tied products at third place may be cut off. Use RANK() to include ties.

157. Get employees who joined after their department was created.

SQL
SELECT e.*
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE e.hire_date > d.creation_date;

Logic:

  1. Join employees to their department.
  2. hire_date > creation_date keeps employees hired after the department's creation date.
Concept

Join with a date comparison.

158. Find customers with no sales records.

SQL
SELECT c.*
FROM customers c
LEFT JOIN sales s ON c.customer_id = s.customer_id
WHERE s.sale_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from customers.
  2. Rows without a match have NULL in all sales columns.
  3. WHERE s.sale_id IS NULL keeps only the customers rows that have no match in sales.
Concept

Anti-join using LEFT JOIN … IS NULL.

159. Find the second highest salary in the company.

SQL
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

Logic:

  1. The subquery finds the highest salary.
  2. MAX(salary) among salaries below it is the second highest.
Concept

Subquery with MAX.

Note

Same pattern as Question 1.

160. Find products with sales only in the current month.

SQL
SELECT product_id
FROM sales
GROUP BY product_id
HAVING MAX(sale_date) >= DATE_TRUNC('month', CURRENT_DATE)
    AND MIN(sale_date) >= DATE_TRUNC('month', CURRENT_DATE);

Logic:

  1. MIN(sale_date) and MAX(sale_date) are each product's first and last sales.
  2. If the first sale is in the current month, all sales are in the current month or later.
Concept

Date boundaries in HAVING.

Note

Add an upper bound (< DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month') if future-dated sales are possible.

161. Find employees with consecutive workdays.

SQL
WITH attendance AS (
    SELECT employee_id, work_date,
        work_date - INTERVAL '1 day' * ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY work_date) AS grp
    FROM work_log
)
SELECT employee_id, COUNT(*) AS consecutive_days
FROM attendance
GROUP BY employee_id, grp
HAVING COUNT(*) > 1;

Logic:

  1. Number each employee's work dates in order.
  2. Subtract that number of days from the date; consecutive dates then share the same grp.
  3. COUNT(*) per group is the length of the streak.
Concept

Gaps and islands technique.

Note

HAVING COUNT(*) > 1 returns streaks of at least two days. Remove duplicate dates first if the log can contain several rows per day.

162. Find the average number of orders per customer.

SQL
SELECT AVG(order_count) AS avg_orders_per_customer
FROM (
    SELECT customer_id, COUNT(*) AS order_count
    FROM orders
    GROUP BY customer_id
) sub;

Logic:

  1. The subquery counts orders per customer.
  2. AVG() of those counts is the average.
Concept

Aggregate over an aggregate.

163. Find employees who have worked on more than 5 projects.

SQL
SELECT employee_id, COUNT(DISTINCT project_id) AS project_count
FROM project_assignments
GROUP BY employee_id
HAVING COUNT(DISTINCT project_id) > 5;

Logic:

  1. COUNT(DISTINCT project_id) per employee.
  2. HAVING keeps counts above 5.
Concept

Distinct count in HAVING.

164. Find the total number of products sold each day.

SQL
SELECT sale_date, SUM(quantity) AS total_quantity_sold
FROM sales
GROUP BY sale_date
ORDER BY sale_date;

Logic:

  1. Group sales by date.
  2. SUM(quantity) is the number of items sold that day.
Concept

Daily totals.

165. Find customers with orders totaling more than $10,000.

SQL
SELECT customer_id, SUM(amount) AS total_amount
FROM sales
GROUP BY customer_id
HAVING SUM(amount) > 10000;

Logic:

  1. Group by customer.
  2. SUM(amount) is each customer's total.
  3. HAVING keeps totals above 10,000.
Concept

HAVING with SUM.

SQL Interview Questions 166–200 — Medium to Advanced

166. Find employees who have never received a bonus.

SQL
SELECT e.*
FROM employees e
LEFT JOIN bonuses b ON e.id = b.employee_id
WHERE b.bonus_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all bonuses columns.
  3. WHERE b.bonus_id IS NULL keeps only the employees rows that have no match in bonuses.
Concept

Anti-join using LEFT JOIN … IS NULL.

167. Find the department with the lowest average salary.

SQL
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
ORDER BY avg_salary
LIMIT 1;

Logic:

  1. Average salary per department.
  2. Sort ascending and return the first row.
Concept

Top-1 group.

Note

Same pattern as Question 39.

168. Get cumulative count of orders per customer over time.

SQL
SELECT customer_id, order_date, COUNT(*) OVER (PARTITION BY customer_id
    ORDER BY order_date) AS cumulative_orders
FROM orders;

Logic:

  1. PARTITION BY customer_id handles each customer separately.
  2. COUNT(*) OVER (... ORDER BY order_date) counts orders from the first one up to the current row.
Concept

Running count.

169. Find customers who ordered products only from one category.

SQL
SELECT customer_id
FROM sales s
JOIN products p ON s.product_id = p.product_id
GROUP BY customer_id
HAVING COUNT(DISTINCT p.category_id) = 1;

Logic:

  1. Join sales to products to find each sale's category.
  2. Count the distinct categories per customer.
  3. Keep customers with exactly one.
Concept

Distinct count in HAVING.

170. Write a query to display employee names alongside their manager names, including those without managers.

SQL
SELECT e.name AS employee_name, m.name AS manager_name
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

Logic:

  1. LEFT JOIN the table to itself.
  2. Employees without a manager show NULL as the manager name.
Concept

Self left join.

Note

Same as Question 146.

171. Find products with sales increasing every month for the last 3 months.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    WHERE sale_date >= CURRENT_DATE - INTERVAL '3 months'
    GROUP BY product_id, month
)
SELECT product_id
FROM monthly_sales
GROUP BY product_id
HAVING COUNT(*) = 3
    AND MIN(total_sales) < MAX(total_sales)
    AND total_sales[1] < total_sales[2] AND total_sales[2] < total_sales[3];

Logic:

  1. Total sales per product per month for the last 3 months.
  2. LAG(total_sales, 1) and LAG(total_sales, 2) bring the previous two months into the current row.
  3. Keep products where each month is higher than the one before it.
Concept

Strictly increasing trend with LAG().

Important

The query in the PDF is not valid SQL: array-style references such as total_sales[1] cannot be used on aggregated columns. Use the LAG() version below.

Corrected version:

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    WHERE sale_date >= CURRENT_DATE - INTERVAL '3 months'
    GROUP BY product_id, month
), sales_lag AS (
    SELECT product_id, month, total_sales,
        LAG(total_sales, 1) OVER (PARTITION BY product_id ORDER BY month) AS prev1,
        LAG(total_sales, 2) OVER (PARTITION BY product_id ORDER BY month) AS prev2
    FROM monthly_sales
)
SELECT DISTINCT product_id
FROM sales_lag
WHERE total_sales > prev1 AND prev1 > prev2;

172. Write a recursive query to get all descendants of a manager.

SQL
WITH RECURSIVE subordinates AS (
    SELECT id, name, manager_id
    FROM employees
    WHERE id = :manager_id
    UNION ALL
    SELECT e.id, e.name, e.manager_id
    FROM employees e
    JOIN subordinates s ON e.manager_id = s.id
)
SELECT * FROM subordinates WHERE id != :manager_id;

Logic:

  1. The anchor row is the manager (:manager_id is a parameter).
  2. Each recursion adds employees who report to anyone already found.
  3. The final query removes the manager.
Concept

Recursive CTE with a parameter.

173. Find the department with the highest variance in salaries.

SQL
SELECT department_id, VAR_SAMP(salary) AS salary_variance
FROM employees
GROUP BY department_id
ORDER BY salary_variance DESC
LIMIT 1;

Logic:

  1. VAR_SAMP(salary) is the sample variance of each department's salaries.
  2. Sort descending and return the first.
Concept

Statistical aggregate.

Note

Departments with a single employee return NULL for sample variance.

174. Calculate the difference between each order amount and the previous order amount per customer.

SQL
SELECT customer_id, order_date, amount,
    amount - LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS diff
FROM orders;

Logic:

  1. LAG(amount) returns the customer's previous order amount.
  2. Subtract it from the current amount.
Concept

LAG() per customer.

175. Find customers who purchased both Product A and Product B.

SQL
SELECT customer_id
FROM sales
WHERE product_id IN ('A', 'B')
GROUP BY customer_id
HAVING COUNT(DISTINCT product_id) = 2;

Logic:

  1. Keep sales of A and B.
  2. Count the distinct products per customer.
  3. Count 2 means both were bought.
Concept

Relational division.

Note

Same pattern as Question 105.

176. Find the top N customers by total sales amount.

SQL
SELECT customer_id, SUM(amount) AS total_sales
FROM sales
GROUP BY customer_id
ORDER BY total_sales DESC
LIMIT N;

Logic:

  1. Total sales per customer.
  2. Sort descending and LIMIT N.
Concept

Top-N with LIMIT.

Note

Replace N with a number such as 5. SQL Server uses TOP N and Oracle uses FETCH FIRST N ROWS ONLY.

177. Find the month with the highest sales in the current year.

SQL
SELECT DATE_TRUNC('month', sale_date) AS month, SUM(amount) AS total_sales
FROM sales
WHERE EXTRACT(YEAR FROM sale_date) = EXTRACT(YEAR FROM CURRENT_DATE)
GROUP BY month
ORDER BY total_sales DESC
LIMIT 1;

Logic:

  1. Keep sales of the current year.
  2. Total by month.
  3. Sort descending and return the first month.
Concept

Top-1 month.

178. Write a query to display all employees who have worked on a project longer than 6 months.

SQL
SELECT employee_id
FROM project_assignments
WHERE end_date - start_date > INTERVAL '6 months';

Logic:

  1. The condition compares the project's duration with a 6-month interval.
  2. DISTINCT is needed to list each employee once.
Concept

Duration filter.

Important

For DATE columns, end_date - start_date is an integer in PostgreSQL and cannot be compared to an interval. Compare dates instead, as shown below.

Works for both DATE and TIMESTAMP:

SQL
SELECT DISTINCT employee_id
FROM project_assignments
WHERE end_date > start_date + INTERVAL '6 months';

179. Find the nth highest salary in a company (e.g., 5th highest).

SQL
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
OFFSET n - 1 ROWS FETCH NEXT 1 ROW ONLY;

Logic:

  1. DISTINCT salary removes duplicate salaries.
  2. Sort descending, skip the first n - 1 values and fetch one row.
Concept

OFFSET/FETCH for the Nth value.

Note

Replace n with a number (for example 5). This is the SQL-standard form of the LIMIT/OFFSET query in Question 68.

180. Get the average salary of employees hired each year.

SQL
SELECT EXTRACT(YEAR FROM hire_date) AS year, AVG(salary) AS avg_salary
FROM employees
GROUP BY year
ORDER BY year;

Logic:

  1. Group by hire year.
  2. AVG(salary) per year.
Concept

Group by a date part.

181. Find employees whose salaries are between the 25th and 75th percentile.

SQL
WITH percentiles AS (
    SELECT PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY salary) AS p25,
        PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY salary) AS p75
    FROM employees
)
SELECT e.*
FROM employees e, percentiles p
WHERE e.salary BETWEEN p.p25 AND p.p75;

Logic:

  1. The CTE calculates the 25th and 75th percentile salaries.
  2. The main query keeps salaries between them (the interquartile range).
Concept

Percentile filtering.

182. Find employees with salaries higher than their department average.

SQL
SELECT e.*
FROM employees e
JOIN (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
) d ON e.department_id = d.department_id
WHERE e.salary > d.avg_salary;

Logic:

  1. The derived table calculates each department's average.
  2. Join it to employees and keep those above their department average.
Concept

Join to an aggregated subquery.

183. Find the difference between each row's value and the previous row’s value in sales.

SQL
SELECT sale_date, amount, amount - LAG(amount) OVER (ORDER BY sale_date) AS diff
FROM sales;

Logic:

  1. LAG(amount) gives the previous row's amount in date order.
  2. Subtract it from the current amount.
Concept

LAG() window function.

184. List employees who have been in the company for more than 10 years.

SQL
SELECT *
FROM employees
WHERE CURRENT_DATE - hire_date > INTERVAL '10 years';

Logic:

  1. The condition keeps employees whose service time is over 10 years.
Concept

Date filter.

Important

For DATE columns, CURRENT_DATE - hire_date is an integer and cannot be compared with an interval. Compare the date with a cutoff instead.

Works for both DATE and TIMESTAMP:

SQL
SELECT *
FROM employees
WHERE hire_date < CURRENT_DATE - INTERVAL '10 years';

185. Find the department with the most promotions.

SQL
SELECT e.department_id, COUNT(*) AS promotion_count
FROM promotions p
JOIN employees e ON p.employee_id = e.id
GROUP BY e.department_id
ORDER BY promotion_count DESC
LIMIT 1;

Logic:

  1. Join promotions to employees to find each promotion's department.
  2. Count promotions per department.
  3. Return the highest.
Concept

Join, group and top-1.

186. Find customers who ordered products from at least 3 different categories.

SQL
SELECT customer_id
FROM sales s
JOIN products p ON s.product_id = p.product_id
GROUP BY customer_id
HAVING COUNT(DISTINCT p.category_id) >= 3;

Logic:

  1. Join sales to products to get the category.
  2. Count distinct categories per customer.
  3. HAVING >= 3 keeps those with three or more.
Concept

Distinct count in HAVING.

187. Find the average gap (in days) between orders per customer.

SQL
WITH ordered_orders AS (
    SELECT customer_id, order_date,
        LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_order_date
    FROM orders
), gaps AS (
    SELECT customer_id, order_date - prev_order_date AS gap
    FROM ordered_orders
    WHERE prev_order_date IS NOT NULL
)
SELECT customer_id, AVG(gap) AS avg_gap_days
FROM gaps
GROUP BY customer_id;

Logic:

  1. LAG(order_date) finds the previous order date for each customer.
  2. The difference is the gap between two orders.
  3. AVG(gap) per customer is the average gap.
Concept

Gap analysis with LAG().

Note

The first order of each customer has no previous order, so it is excluded.

188. List all customers who have never ordered product X.

SQL
SELECT customer_id
FROM customers
WHERE customer_id NOT IN (
    SELECT DISTINCT customer_id
    FROM sales
    WHERE product_id = 'X'
);

Logic:

  1. The subquery lists customers who ordered product X.
  2. NOT IN returns the customers not in that list.

Alternative using NOT EXISTS:

SQL
SELECT c.customer_id
FROM customers c
WHERE NOT EXISTS (
    SELECT 1
    FROM sales s
    WHERE s.customer_id = c.customer_id
        AND s.product_id = 'X'
);
Concept

Exclusion with a subquery.

Important

NOT IN returns nothing if the subquery returns a NULL id. NOT EXISTS is safer.

189. Calculate total revenue and number of orders per country.

SQL
SELECT c.country, COUNT(o.order_id) AS order_count, SUM(o.amount) AS total_revenue
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY c.country;

Logic:

  1. Join customers to their orders.
  2. Group by country.
  3. COUNT(o.order_id) and SUM(o.amount) summarize each country.
Concept

Join with aggregation.

190. Find the employees who were hired on the same day as their managers.

SQL
SELECT e.name AS employee, m.name AS manager, e.hire_date
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.hire_date = m.hire_date;

Logic:

  1. Self join employees to their managers.
  2. Keep rows where the hire dates are equal.
Concept

Self join.

Note

Same as Question 89.

191. Find the top 3 products by quantity sold in each category.

SQL
SELECT category_id, product_id, total_quantity
FROM (
    SELECT p.category_id, s.product_id, SUM(s.quantity) AS total_quantity,
        ROW_NUMBER() OVER (PARTITION BY p.category_id ORDER BY SUM(s.quantity) DESC) AS rn
    FROM sales s
    JOIN products p ON s.product_id = p.product_id
    GROUP BY p.category_id, s.product_id
) sub
WHERE rn <= 3;

Logic:

  1. The inner query totals quantity per product and category.
  2. ROW_NUMBER() ranks products within each category by that total.
  3. rn <= 3 keeps the top three.
Concept

Top-N per group over an aggregate.

192. Find the difference in days between the first and last order for each customer.

SQL
SELECT customer_id, MAX(order_date) - MIN(order_date) AS days_between
FROM orders
GROUP BY customer_id;

Logic:

  1. MAX(order_date) - MIN(order_date) is the span between the first and last order.
Concept

Date difference with aggregates.

Note

Same as Question 134.

193. Find customers who have increased their order volume every month for the last 3 months.

SQL
WITH monthly_orders AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month,
        COUNT(*) AS orders_count
    FROM orders
    WHERE order_date >= CURRENT_DATE - INTERVAL '3 months'
    GROUP BY customer_id, month
)
SELECT customer_id
FROM monthly_orders
GROUP BY customer_id
HAVING COUNT(*) = 3
    AND MIN(orders_count) < MAX(orders_count);

Logic:

  1. The CTE counts orders per customer per month for the last 3 months.
  2. MIN(orders_count) < MAX(orders_count) only proves the counts are not all equal; it does not prove an increase every month.
Concept

Trend detection.

Important

The PDF query is incomplete (its own comment says it needs a window check). Use LAG() to compare each month with the previous two.

Corrected version:

SQL
WITH monthly_orders AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month,
        COUNT(*) AS orders_count
    FROM orders
    WHERE order_date >= CURRENT_DATE - INTERVAL '3 months'
    GROUP BY customer_id, month
), with_lag AS (
    SELECT customer_id, month, orders_count,
        LAG(orders_count, 1) OVER (PARTITION BY customer_id ORDER BY month) AS prev1,
        LAG(orders_count, 2) OVER (PARTITION BY customer_id ORDER BY month) AS prev2
    FROM monthly_orders
)
SELECT DISTINCT customer_id
FROM with_lag
WHERE orders_count > prev1 AND prev1 > prev2;

194. Find employees who have the same salary as the average salary in their job title.

SQL
SELECT e.*
FROM employees e
JOIN (
    SELECT job_title, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY job_title
) j ON e.job_title = j.job_title
WHERE e.salary = j.avg_salary;

Logic:

  1. The derived table calculates the average salary per job title.
  2. Join on job title and keep employees whose salary equals it.
Concept

Join to an aggregated subquery.

195. Write a query to calculate the difference in salary between employees and their managers.

SQL
SELECT e.name, m.name AS manager_name, e.salary, m.salary AS manager_salary,
    e.salary - m.salary AS salary_diff
FROM employees e
JOIN employees m ON e.manager_id = m.id;

Logic:

  1. Self join each employee to their manager.
  2. e.salary - m.salary is the difference (negative when the employee earns less).
Concept

Self join with arithmetic.

196. List the departments with no employees.

SQL
SELECT d.*
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
WHERE e.id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from departments.
  2. Rows without a match have NULL in all employees columns.
  3. WHERE e.id IS NULL keeps only the departments rows that have no match in employees.
Concept

Anti-join using LEFT JOIN … IS NULL.

Note

Always test a column that can never be NULL in a real match (usually the primary key) in the IS NULL check.

197. Find the employee with the maximum salary in each department.

SQL
WITH dept_max AS (
    SELECT department_id, MAX(salary) AS max_salary
    FROM employees
    GROUP BY department_id
)
SELECT e.*
FROM employees e
JOIN dept_max d ON e.department_id = d.department_id AND e.salary = d.max_salary;

Logic:

  1. The CTE calculates the maximum salary per department.
  2. Join back to employees to find who earns it.
Concept

Join back to a group maximum.

Note

Same as Question 128; ties are all returned.

198. Find customers with orders on every day in the last week.

SQL
WITH days AS (
    SELECT generate_series(CURRENT_DATE - INTERVAL '6 days', CURRENT_DATE, INTERVAL '1 day') AS day
)
SELECT customer_id
FROM orders o
JOIN days d ON o.order_date = d.day
GROUP BY customer_id
HAVING COUNT(DISTINCT o.order_date) = 7;

Logic:

  1. The CTE generates the last 7 dates.
  2. Join orders to those dates.
  3. COUNT(DISTINCT order_date) = 7 keeps customers with an order on each day.
Concept

Relational division over dates.

Important

generate_series returns timestamps. If order_date is a DATE, cast the generated value (::date) so the join matches.

199. Find the product that has been sold in the highest quantity in a single order.

SQL
SELECT product_id, MAX(quantity) AS max_quantity_in_order
FROM sales
GROUP BY product_id
ORDER BY max_quantity_in_order DESC
LIMIT 1;

Logic:

  1. MAX(quantity) per product is the largest quantity in one sale.
  2. Sort descending and return the first product.
Concept

Top-1 with MAX.

200. Find employees who joined before their department was created.

SQL
SELECT e.*
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE e.hire_date < d.creation_date;

Logic:

  1. Join employees to their department.
  2. hire_date < creation_date finds the unusual (inconsistent) cases.
Concept

Join with a date comparison.

SQL Interview Questions 201–235 — Medium to Advanced

201. Find customers with sales in at least 3 different years.

SQL
SELECT customer_id
FROM sales
GROUP BY customer_id
HAVING COUNT(DISTINCT EXTRACT(YEAR
        FROM sale_date)) >= 3;

Logic:

  1. Extract the year from each sale.
  2. Count distinct years per customer.
  3. Keep customers with three or more.
Concept

Distinct count of a date part.

202. Find employees whose salary is above the company’s average but below their department’s average.

SQL
WITH company_avg AS (SELECT AVG(salary) AS avg_salary FROM employees), dept_avg AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
)
SELECT e.*
FROM employees e, company_avg ca
JOIN dept_avg da ON e.department_id = da.department_id
WHERE e.salary > ca.avg_salary AND e.salary < da.avg_salary;

Logic:

  1. The first CTE is the company average and the second is each department's average.
  2. Join employees to both averages.
  3. Keep employees above the company average and below their department average.
Concept

Combining company and department averages.

Important

The PDF mixes a comma join with JOIN ... ON, which raises an error because the ON clause cannot see e. Use CROSS JOIN for the one-row company average.

Corrected version:

SQL
WITH company_avg AS (
    SELECT AVG(salary) AS avg_salary FROM employees
), dept_avg AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
)
SELECT e.*
FROM employees e
CROSS JOIN company_avg ca
JOIN dept_avg da ON e.department_id = da.department_id
WHERE e.salary > ca.avg_salary
    AND e.salary < da.avg_salary;

203. Find the average order amount per customer per year.

SQL
SELECT customer_id, EXTRACT(YEAR FROM order_date) AS year,
    AVG(amount) AS avg_order_amount
FROM orders
GROUP BY customer_id, year;

Logic:

  1. Group by customer and order year.
  2. AVG(amount) for each group.
Concept

Multi-column grouping.

204. Find employees who have worked on at least one project with a budget over $1,000,000.

SQL
SELECT DISTINCT pa.employee_id
FROM project_assignments pa
JOIN projects p ON pa.project_id = p.project_id
WHERE p.budget > 1000000;

Logic:

  1. Join assignments to projects.
  2. Keep projects over the budget.
  3. DISTINCT returns each employee once.
Concept

Join with a filter.

205. Find the most recent promotion date per employee.

SQL
SELECT employee_id, MAX(promotion_date) AS last_promotion_date
FROM promotions
GROUP BY employee_id;

Logic:

  1. MAX(promotion_date) per employee.
Concept

MAX aggregate.

206. Find customers who made orders totaling more than the average order amount.

SQL
WITH avg_order AS (
    SELECT AVG(amount) AS avg_amount FROM orders
)
SELECT customer_id, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > (SELECT avg_amount
    FROM avg_order);

Logic:

  1. The CTE calculates the average amount of a single order.
  2. Group orders by customer and total them.
  3. Keep customers whose total exceeds the average.
Concept

Group filter with a CTE.

Important

This compares customer totals with the average single order, which almost every active customer exceeds. To compare with the average customer total, see Question 293.

207. Find products never ordered.

SQL
SELECT product_id
FROM products
WHERE product_id NOT IN (SELECT DISTINCT product_id FROM sales);

Logic:

  1. The subquery lists product ids that appear in sales.
  2. NOT IN keeps products not in that list.
Concept

Exclusion with a subquery.

Important

If sales.product_id can be NULL, NOT IN returns no rows. Prefer NOT EXISTS or LEFT JOIN ... IS NULL (Question 63).

208. Find the month with the lowest sales in the past year.

SQL
SELECT DATE_TRUNC('month', sale_date) AS month, SUM(amount) AS total_sales
FROM sales
WHERE sale_date >= CURRENT_DATE - INTERVAL '1 year'
GROUP BY month
ORDER BY total_sales
LIMIT 1;

Logic:

  1. Keep sales from the last year.
  2. Total by month.
  3. Sort ascending and return the first.
Concept

Top-1 month.

209. Calculate the number of employees hired each month in the last year.

SQL
SELECT DATE_TRUNC('month', hire_date) AS month, COUNT(*) AS hires
FROM employees
WHERE hire_date >= CURRENT_DATE - INTERVAL '1 year'
GROUP BY month
ORDER BY month;

Logic:

  1. Keep employees hired in the last year.
  2. Group by month and count.
Concept

Monthly counts.

210. Find the department with the highest number of projects.

SQL
SELECT department_id, COUNT(*) AS project_count
FROM projects
GROUP BY department_id
ORDER BY project_count DESC
LIMIT 1;

Logic:

  1. Count projects per department.
  2. Return the department with the highest count.
Concept

Top-1 group.

211. Find employees who do not have dependents.

SQL
SELECT e.*
FROM employees e
LEFT JOIN dependents d ON e.id = d.employee_id
WHERE d.dependent_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all dependents columns.
  3. WHERE d.dependent_id IS NULL keeps only the employees rows that have no match in dependents.
Concept

Anti-join using LEFT JOIN … IS NULL.

212. Get the total sales amount for each product category including categories with zero sales.

SQL
SELECT c.category_id, COALESCE(SUM(s.amount), 0) AS total_sales
FROM categories c
LEFT JOIN products p ON c.category_id = p.category_id
LEFT JOIN sales s ON p.product_id = s.product_id
GROUP BY c.category_id;

Logic:

  1. LEFT JOIN categories to products, then products to sales, so every category is kept.
  2. SUM(s.amount) is NULL for categories without sales.
  3. COALESCE(..., 0) replaces NULL with 0.
Concept

Chained left joins with COALESCE.

213. Find employees who have been promoted but their salary didn’t increase.

SQL
SELECT e.id, e.name
FROM employees e
JOIN promotions p ON e.id = p.employee_id
WHERE e.salary <= (SELECT salary_before FROM promotion_history WHERE employee_id = e.id
    ORDER BY promotion_date DESC LIMIT 1);

Logic:

  1. Join employees to their promotions.
  2. The subquery fetches the salary recorded before the latest promotion.
  3. The current salary being less than or equal to it means no increase.
Concept

Correlated subquery for the latest record.

Note

The query assumes a promotion_history table with salary_before and promotion_date.

214. Find customers with average order amount above $500.

SQL
SELECT customer_id, AVG(amount) AS avg_order_amount
FROM orders
GROUP BY customer_id
HAVING AVG(amount) > 500;

Logic:

  1. Group by customer.
  2. AVG(amount) is the customer's average order.
  3. HAVING AVG(amount) > 500 keeps those above 500.
Concept

HAVING with AVG.

215. Find orders where the total quantity exceeds 100 units.

SQL
SELECT order_id, SUM(quantity) AS total_quantity
FROM order_items
GROUP BY order_id
HAVING SUM(quantity) > 100;

Logic:

  1. Group order items by order.
  2. SUM(quantity) is the total units per order.
  3. HAVING keeps totals above 100.
Concept

HAVING with SUM.

216. Find products whose sales have doubled compared to the previous month.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, month
), sales_comparison AS (
    SELECT product_id, month, total_sales,
        LAG(total_sales) OVER (PARTITION BY product_id ORDER BY month) AS prev_month_sales
    FROM monthly_sales
)
SELECT product_id, month
FROM sales_comparison
WHERE prev_month_sales IS NOT NULL AND total_sales >= 2 * prev_month_sales;

Logic:

  1. The first CTE totals sales per product per month.
  2. LAG() brings the previous month's total into the row.
  3. total_sales >= 2 * prev_month_sales keeps months where sales at least doubled.
Concept

Growth threshold with LAG().

Note

LAG() uses the previous row, which is the previous month only if no months are missing.

217. Write a query to find employees who worked on more than 3 projects in 2023.

SQL
SELECT employee_id, COUNT(DISTINCT project_id) AS project_count
FROM project_assignments
WHERE assignment_date BETWEEN '2023-01-01'
    AND '2023-12-31'
GROUP BY employee_id
HAVING COUNT(DISTINCT project_id) > 3;

Logic:

  1. Keep assignments dated in 2023.
  2. Count distinct projects per employee.
  3. Keep counts above 3.
Concept

Date filter with a distinct count.

Important

BETWEEN '2023-01-01' AND '2023-12-31' misses timestamps later than midnight on December 31. A safer range is >= '2023-01-01' AND < '2024-01-01'.

218. Find customers whose last order was placed more than 1 year ago.

SQL
SELECT customer_id, MAX(order_date) AS last_order_date
FROM orders
GROUP BY customer_id
HAVING MAX(order_date) < CURRENT_DATE - INTERVAL '1 year';

Logic:

  1. MAX(order_date) is each customer's last order.
  2. HAVING keeps those older than one year.
Concept

Condition on MAX() in HAVING.

219. Find the average salary increase percentage per department.

SQL
SELECT e.department_id,
    AVG((e.salary - p.old_salary) / p.old_salary * 100) AS avg_increase_pct
FROM employees e
JOIN promotions p ON e.id = p.employee_id
GROUP BY e.department_id;

Logic:

  1. The percentage increase is (current salary - old salary) / old salary * 100.
  2. Join employees to their promotions to get the old salary.
  3. AVG() per department summarizes the increases.
Concept

Aggregating a calculated percentage.

Note

If an employee has several promotions, each one is counted as a separate row.

220. Find employees who have never been promoted.

SQL
SELECT *
FROM employees
WHERE id NOT IN (SELECT DISTINCT employee_id FROM promotions);

Logic:

  1. The subquery lists employees who have been promoted.
  2. NOT IN returns the others.
Concept

Exclusion with a subquery.

Important

If promotions.employee_id can be NULL, NOT IN returns no rows. Prefer NOT EXISTS or LEFT JOIN ... IS NULL (Question 79).

221. Find products ordered by all customers.

SQL
SELECT product_id
FROM sales
GROUP BY product_id
HAVING COUNT(DISTINCT customer_id) = (SELECT COUNT(*) FROM customers);

Logic:

  1. Count the distinct customers who ordered each product.
  2. Compare with the total number of customers.
  3. Equal counts mean every customer ordered the product.
Concept

Relational division.

222. Find customers with orders totaling more than $5000 in the last 6 months.

SQL
SELECT customer_id, SUM(amount) AS total_amount
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY customer_id
HAVING SUM(amount) > 5000;

Logic:

  1. Keep orders from the last six months.
  2. Total per customer.
  3. HAVING keeps totals above 5000.
Concept

Filter, group and HAVING.

223. Find the rank of employees based on salary within their department.

SQL
SELECT *,
    RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank
FROM employees;

Logic:

  1. PARTITION BY department_id ranks inside each department.
  2. ORDER BY salary DESC gives rank 1 to the highest salary.
Concept

RANK() per group.

224. Find customers who purchased a product but never reordered it.

SQL
WITH order_counts AS (
    SELECT customer_id, product_id, COUNT(*) AS order_count
    FROM sales
    GROUP BY customer_id, product_id
)
SELECT customer_id, product_id
FROM order_counts
WHERE order_count = 1;

Logic:

  1. Count how many times each customer bought each product.
  2. A count of exactly 1 means the product was bought once and never reordered.
Concept

Counting repeat purchases.

225. Find the day with the highest number of new hires.

SQL
SELECT hire_date, COUNT(*) AS hires
FROM employees
GROUP BY hire_date
ORDER BY hires DESC
LIMIT 1;

Logic:

  1. Group employees by hire date.
  2. Count per day, sort descending and return the first.
Concept

Top-1 day.

Note

Ties are not returned.

226. Find the number of employees who have worked in more than one department.

SQL
SELECT employee_id
FROM employee_department_history
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id) > 1;

Logic:

  1. Group the history by employee.
  2. Count distinct departments.
  3. Keep counts above 1.
Concept

Distinct count in HAVING.

Note

This returns the employees; wrap it in SELECT COUNT(*) FROM (...) to get the number of employees.

227. Find customers who ordered the most products in 2023.

SQL
SELECT customer_id, SUM(quantity) AS total_quantity
FROM sales
WHERE EXTRACT(YEAR FROM sale_date) = 2023
GROUP BY customer_id
ORDER BY total_quantity DESC
LIMIT 1;

Logic:

  1. Keep sales from 2023.
  2. SUM(quantity) per customer.
  3. Sort descending and return the first.
Concept

Top-1 with a filter.

Note

Ties are not returned.

228. Find the average days taken to ship orders per shipping method.

SQL
SELECT shipping_method, AVG(shipping_date - order_date) AS avg_shipping_days
FROM orders
GROUP BY shipping_method;

Logic:

  1. shipping_date - order_date is the number of days between order and shipping.
  2. AVG() per shipping method.
Concept

Date difference with AVG.

Note

For DATE columns PostgreSQL returns an integer number of days.

229. Find employees with overlapping project assignments.

SQL
SELECT pa1.employee_id, pa1.project_id, pa2.project_id AS overlapping_project
FROM project_assignments pa1
JOIN project_assignments pa2 ON pa1.employee_id = pa2.employee_id AND pa1.project_id <> pa2.project_id
WHERE pa1.start_date <= pa2.end_date AND pa1.end_date >= pa2.start_date;

Logic:

  1. Join each assignment to others of the same employee.
  2. Ranges overlap when each starts on or before the other ends.
Concept

Interval overlap test.

Note

Same logic as Question 95. Each pair is returned twice.

230. Find the total number of unique customers per product category.

SQL
SELECT p.category_id, COUNT(DISTINCT s.customer_id) AS unique_customers
FROM sales s
JOIN products p ON s.product_id = p.product_id
GROUP BY p.category_id;

Logic:

  1. Join sales to products for the category.
  2. COUNT(DISTINCT customer_id) per category.
Concept

Distinct count per group.

231. Find customers whose orders increased by at least 20% compared to the previous month.

SQL
WITH monthly_orders AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month,
        COUNT(*) AS order_count
    FROM orders
    GROUP BY customer_id, month
), orders_comparison AS (
    SELECT customer_id, month, order_count,
        LAG(order_count) OVER (PARTITION BY customer_id ORDER BY month) AS prev_order_count
    FROM monthly_orders
)
SELECT customer_id, month
FROM orders_comparison
WHERE prev_order_count IS NOT NULL AND order_count >= 1.2 * prev_order_count;

Logic:

  1. The first CTE counts orders per customer per month.
  2. LAG() retrieves the previous month's count.
  3. order_count >= 1.2 * prev_order_count keeps months with at least a 20% increase.
Concept

Growth threshold with LAG().

232. Find employees with no projects assigned in the last 6 months.

SQL
SELECT e.*
FROM employees e
LEFT JOIN project_assignments pa ON e.id = pa.employee_id AND pa.start_date >= CURRENT_DATE - INTERVAL '6 months'
WHERE pa.project_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all project_assignments columns.
  3. WHERE pa.project_id IS NULL keeps only the employees rows that have no match in project_assignments.
Concept

Anti-join with a date condition in ON.

Important

Keep the date condition in the ON clause. If it is moved to WHERE, the anti-join returns no rows.

233. Find the number of employees who have changed departments more than twice.

SQL
SELECT employee_id
FROM employee_department_history
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id) > 2;

Logic:

  1. Group the department history by employee.
  2. Count distinct departments.
  3. Keep employees with more than two.
Concept

Distinct count in HAVING.

Note

This counts distinct departments, not the number of moves; an employee who returns to a previous department is counted once.

234. Find the product with the highest average rating.

SQL
SELECT product_id, AVG(rating) AS avg_rating
FROM product_reviews
GROUP BY product_id
ORDER BY avg_rating DESC
LIMIT 1;

Logic:

  1. AVG(rating) per product.
  2. Sort descending and return the first.
Concept

Top-1 average.

Note

A product with one 5-star review can win. Add HAVING COUNT(*) >= n to require a minimum number of reviews.

235. Find customers who have placed orders but never used a discount.

SQL
SELECT DISTINCT customer_id
FROM orders
WHERE discount_used = FALSE;

Logic:

  1. The goal is customers whose orders all have discount_used = FALSE.
  2. Group by customer and count orders where a discount was used.
  3. Keep customers whose count is 0.
Concept

Group-level condition.

Important

The query in the PDF returns customers who have at least one order without a discount, including customers who used a discount on other orders. Check the whole group instead.

Corrected version:

SQL
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING SUM(CASE WHEN discount_used = TRUE THEN 1 ELSE 0 END) = 0;

SQL Interview Questions 236–270 — Medium to Advanced

236. Find employees who have worked on every project in their department.

SQL
SELECT e.id, e.name
FROM employees e
JOIN projects p ON e.department_id = p.department_id
LEFT JOIN project_assignments pa ON e.id = pa.employee_id AND p.project_id = pa.project_id
GROUP BY e.id, e.name, p.department_id
HAVING COUNT(p.project_id) = COUNT(pa.project_id);

Logic:

  1. Join each employee to all projects of their department.
  2. LEFT JOIN the employee's assignments to those projects.
  3. If the number of department projects equals the number of matched assignments, the employee worked on all of them.
Concept

Relational division per group.

237. Find the average order amount excluding the top 5% largest orders.

SQL
WITH ordered_orders AS (
    SELECT amount, NTILE(100) OVER (ORDER BY amount DESC) AS percentile
    FROM orders
)
SELECT AVG(amount)
FROM ordered_orders
WHERE percentile > 5;

Logic:

  1. NTILE(100) splits orders into 100 buckets from the largest amount down.
  2. Buckets 1 to 5 are the top 5%.
  3. AVG(amount) of the remaining buckets is the trimmed average.
Concept

Trimmed mean with NTILE.

238. Find the top 3 employees with the highest salary increase over last year.

SQL
WITH salary_last_year AS (
    SELECT employee_id, salary AS last_year_salary
    FROM salaries
    WHERE year = EXTRACT(YEAR FROM CURRENT_DATE) - 1
), salary_this_year AS (
    SELECT employee_id, salary AS this_year_salary
    FROM salaries
    WHERE year = EXTRACT(YEAR FROM CURRENT_DATE)
)
SELECT t.employee_id, t.this_year_salary - l.last_year_salary AS salary_increase
FROM salary_this_year t
JOIN salary_last_year l ON t.employee_id = l.employee_id
ORDER BY salary_increase DESC
LIMIT 3;

Logic:

  1. The first CTE selects last year's salary and the second selects this year's.
  2. Join them on employee_id and subtract.
  3. Sort by the increase and keep three rows.
Concept

Year-over-year difference.

239. Find employees with the longest consecutive workdays.

SQL
WITH workdays AS (
    SELECT employee_id, work_date,
        ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY work_date) - ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY work_date) AS grp
    FROM attendance
), consecutive_days AS (
    SELECT employee_id, COUNT(*) AS consecutive_days
    FROM workdays
    GROUP BY employee_id, grp
)
SELECT employee_id, MAX(consecutive_days) AS max_consecutive_days
FROM consecutive_days
GROUP BY employee_id;

Logic:

  1. Remove duplicate dates, then number each employee's dates in order.
  2. Subtract the row number (as days) from the date to get a group value shared by consecutive days.
  3. COUNT(*) per group is the streak length; MAX per employee is the longest.
Concept

Gaps and islands technique.

Important

The query in the PDF subtracts ROW_NUMBER() from the same ROW_NUMBER(), so grp is always 0 and every day looks consecutive. The group value must be work_date minus the row number.

Corrected version (PostgreSQL):

SQL
WITH workdays AS (
    SELECT DISTINCT employee_id, work_date
    FROM attendance
), grouped AS (
    SELECT employee_id, work_date,
        work_date - (ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY work_date))::int AS grp
    FROM workdays
), streaks AS (
    SELECT employee_id, COUNT(*) AS consecutive_days
    FROM grouped
    GROUP BY employee_id, grp
)
SELECT employee_id, MAX(consecutive_days) AS max_consecutive_days
FROM streaks
GROUP BY employee_id;

240. Find all managers who do not manage any employee.

SQL
SELECT DISTINCT manager_id
FROM employees
WHERE manager_id NOT IN (SELECT DISTINCT id
    FROM employees);

Logic:

  1. The subquery lists all employee ids.
  2. manager_id NOT IN (...) finds manager_id values that do not match any employee.
Concept

Orphaned references.

Important

As written, this finds manager_id values that point to non-existent employees (broken references). A person who is a manager but has no subordinates cannot appear in manager_id at all. If you have a job-title column, find managers without reports with NOT EXISTS.

Managers (by job title) with no direct reports:

SQL
SELECT e.id, e.name
FROM employees e
WHERE e.job_title = 'Manager'
    AND NOT EXISTS (
        SELECT 1
        FROM employees sub
        WHERE sub.manager_id = e.id
    );

241. Find the average salary of employees hired each month.

SQL
SELECT EXTRACT(YEAR FROM hire_date) AS year, EXTRACT(MONTH FROM hire_date) AS month,
    AVG(salary) AS avg_salary
FROM employees
GROUP BY year, month
ORDER BY year, month;

Logic:

  1. Extract year and month from hire_date.
  2. Group by both so months from different years stay separate.
  3. AVG(salary) per month.
Concept

Grouping by date parts.

242. Find the first 5 orders after a customer's registration date.

SQL
SELECT order_id, customer_id, order_date
FROM (
    SELECT order_id, customer_id, order_date,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) AS rn
    FROM orders
    JOIN customers c ON orders.customer_id = c.customer_id
    WHERE order_date >= c.registration_date
) sub
WHERE rn <= 5;

Logic:

  1. Join orders to customers and keep orders on or after registration.
  2. ROW_NUMBER() numbers each customer's orders by date.
  3. rn <= 5 keeps the first five.
Concept

Top-N per group with a join.

Important

customer_id and order_date could be ambiguous in the inner query. Qualify them with table aliases.

Corrected version:

SQL
SELECT order_id, customer_id, order_date
FROM (
    SELECT o.order_id, o.customer_id, o.order_date,
        ROW_NUMBER() OVER (PARTITION BY o.customer_id ORDER BY o.order_date) AS rn
    FROM orders o
    JOIN customers c ON o.customer_id = c.customer_id
    WHERE o.order_date >= c.registration_date
) sub
WHERE rn <= 5;

243. Find customers who placed orders every month for the last 6 months.

SQL
WITH months AS (
    SELECT generate_series(DATE_TRUNC('month', CURRENT_DATE) - INTERVAL '5 months', DATE_TRUNC('month', CURRENT_DATE), INTERVAL '1 month'
    ) AS month
), customer_months AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month
    FROM orders
    WHERE order_date >= CURRENT_DATE - INTERVAL '6 months'
    GROUP BY customer_id, month
)
SELECT customer_id
FROM customer_months cm
JOIN months m ON cm.month = m.month
GROUP BY customer_id
HAVING COUNT(DISTINCT cm.month) = 6;

Logic:

  1. The first CTE generates the last six months.
  2. The second CTE lists the distinct months in which each customer ordered.
  3. Joining and counting distinct months equal to 6 keeps customers with an order in every month.
Concept

Relational division over months.

244. Calculate the moving average of sales over the last 3 days.

SQL
SELECT sale_date, product_id, amount,
    AVG(amount) OVER (PARTITION BY product_id ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg_3_days
FROM sales;

Logic:

  1. PARTITION BY product_id keeps products separate.
  2. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW creates a 3-row window.
  3. AVG(amount) is the moving average.
Concept

Moving average.

Note

The window uses three rows, which equals three days only if there is exactly one row per day.

245. Find the number of employees who share the same birthday.

SQL
SELECT birth_date, COUNT(*) AS count_employees
FROM employees
GROUP BY birth_date
HAVING COUNT(*) > 1;

Logic:

  1. Group employees by birth_date.
  2. HAVING COUNT(*) > 1 keeps dates shared by several employees.
Concept

Grouping and HAVING.

Important

Grouping by the full birth_date includes the year, so it finds people born on the same date. For the same birthday (month and day), group by month and day.

Same month and day:

SQL
SELECT EXTRACT(MONTH FROM birth_date) AS birth_month,
    EXTRACT(DAY FROM birth_date) AS birth_day,
    COUNT(*) AS count_employees
FROM employees
GROUP BY 1, 2
HAVING COUNT(*) > 1;

246. Find customers who ordered the same product multiple times in one day.

SQL
SELECT customer_id, product_id, order_date, COUNT(*) AS order_count
FROM sales
GROUP BY customer_id, product_id, order_date
HAVING COUNT(*) > 1;

Logic:

  1. Group by customer, product and date.
  2. HAVING COUNT(*) > 1 finds repeated purchases.
Concept

Duplicate detection.

247. Find the total sales for each product including products with zero sales.

SQL
SELECT p.product_id, COALESCE(SUM(s.amount), 0) AS total_sales
FROM products p
LEFT JOIN sales s ON p.product_id = s.product_id
GROUP BY p.product_id;

Logic:

  1. LEFT JOIN keeps every product.
  2. COALESCE(SUM(...), 0) turns NULL totals into 0.
Concept

Left join with COALESCE.

248. List the top 5 employees by number of projects in each department.

SQL
SELECT department_id, employee_id, project_count
FROM (
    SELECT e.department_id, pa.employee_id,
        COUNT(DISTINCT pa.project_id) AS project_count,
        ROW_NUMBER() OVER (PARTITION BY e.department_id ORDER BY COUNT(DISTINCT pa.project_id) DESC) AS rn
    FROM project_assignments pa
    JOIN employees e ON pa.employee_id = e.id
    GROUP BY e.department_id, pa.employee_id
) sub
WHERE rn <= 5;

Logic:

  1. The inner query counts distinct projects per employee.
  2. ROW_NUMBER() ranks employees inside each department by that count.
  3. rn <= 5 keeps the top five.
Concept

Top-N per group over an aggregate.

249. Find the day with the largest difference between maximum and minimum temperature.

SQL
SELECT weather_date, MAX(temperature) - MIN(temperature) AS temp_diff
FROM weather_data
GROUP BY weather_date
ORDER BY temp_diff DESC
LIMIT 1;

Logic:

  1. Group readings by day.
  2. MAX - MIN is the daily temperature range.
  3. Sort descending and return the first day.
Concept

Range per group.

250. Find the 3 most recent orders per customer.

SQL
SELECT order_id, customer_id, order_date
FROM (
    SELECT order_id, customer_id, order_date,
        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
    FROM orders
) sub
WHERE rn <= 3;

Logic:

  1. ROW_NUMBER() numbers each customer's orders from newest to oldest.
  2. rn <= 3 keeps three.
Concept

Top-N per group.

251. Find products with sales only in a specific country.

SQL
SELECT product_id
FROM sales s
JOIN customers c ON s.customer_id = c.customer_id
GROUP BY product_id
HAVING COUNT(DISTINCT c.country) = 1;

Logic:

  1. Join sales to customers to find each sale's country.
  2. Count the distinct countries per product.
  3. A count of 1 means the product was sold in only one country.
Concept

Distinct count in HAVING.

Note

Add HAVING MIN(c.country) = 'India' (or similar) to restrict to one particular country.

252. Find employees with a salary greater than all employees in department 10.

SQL
SELECT *
FROM employees
WHERE salary > ALL (
    SELECT salary FROM employees WHERE department_id = 10
);

Logic:

  1. The subquery returns every salary in department 10.
  2. > ALL keeps employees earning more than the highest of them.
Concept

ALL operator.

Note

If department 10 has no employees, > ALL over an empty set is true and every employee is returned.

253. Find the percentage of employees in each department.

SQL
WITH total_employees AS (SELECT COUNT(*) AS total FROM employees)
SELECT department_id,
    COUNT(*) * 100.0 / (SELECT total FROM total_employees) AS percentage
FROM employees
GROUP BY department_id;

Logic:

  1. Count employees per department.
  2. Divide by the total count and multiply by 100.

Alternative using a window function:

SQL
SELECT department_id,
    COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () AS percentage
FROM employees
GROUP BY department_id;
Concept

Percentage of total.

254. Find the median salary per department.

SQL
SELECT department_id,
    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees
GROUP BY department_id;

Logic:

  1. PERCENTILE_CONT(0.5) is the median of each group's sorted salaries.
  2. GROUP BY department_id calculates it per department.
Concept

Median per group.

255. Find the employee who worked the most hours in a project.

SQL
SELECT employee_id, project_id, MAX(hours_worked) AS max_hours
FROM project_assignments
GROUP BY employee_id, project_id
ORDER BY max_hours DESC
LIMIT 1;

Logic:

  1. Group by employee and project.
  2. MAX(hours_worked) is the largest hours value per pair.
  3. Sort descending and return the first.
Concept

Top-1 with MAX.

Note

If hours_worked is stored per day or per entry, use SUM(hours_worked) to get the total hours.

256. Find the first order date for each customer.

SQL
SELECT customer_id, MIN(order_date) AS first_order_date
FROM orders
GROUP BY customer_id;

Logic:

  1. MIN(order_date) per customer.
Concept

MIN aggregate.

Note

Same as Question 124.

257. Find the second most expensive product per category.

SQL
SELECT category_id, product_id, price
FROM (
    SELECT category_id, product_id, price,
        ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY price DESC) AS rn
    FROM products
) sub
WHERE rn = 2;

Logic:

  1. ROW_NUMBER() ranks products by price within each category.
  2. rn = 2 selects the second.
Concept

Nth value per group.

Note

If prices can tie, use DENSE_RANK() to get the second distinct price.

258. Find employees with the highest salary in each job title.

SQL
WITH max_salary_per_job AS (
    SELECT job_title, MAX(salary) AS max_salary
    FROM employees
    GROUP BY job_title
)
SELECT e.*
FROM employees e
JOIN max_salary_per_job m ON e.job_title = m.job_title AND e.salary = m.max_salary;

Logic:

  1. The CTE finds the maximum salary per job title.
  2. Join back to employees to list who earns it.
Concept

Join back to a group maximum.

259. Calculate the ratio of males to females in each department.

SQL
SELECT department_id, SUM(CASE WHEN gender = 'M' THEN 1 ELSE 0
    END) * 1.0 / NULLIF(SUM(CASE WHEN gender = 'F' THEN 1 ELSE 0 END),
        0) AS male_to_female_ratio
FROM employees
GROUP BY department_id;

Logic:

  1. Count males and females in each department with conditional sums.
  2. Divide males by females.
  3. NULLIF(..., 0) prevents division by zero when a department has no females.
Concept

Ratio with safe division.

260. Find customers who spent more than average in their country.

SQL
WITH avg_spent_per_country AS (
    SELECT c.country, AVG(o.amount) AS avg_amount
    FROM customers c
    JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.country
)
SELECT c.customer_id, SUM(o.amount) AS total_spent
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN avg_spent_per_country a ON c.country = a.country
GROUP BY c.customer_id, c.country, a.avg_amount
HAVING SUM(o.amount) > a.avg_amount;

Logic:

  1. The intended comparison is each customer's total spend against the average total spend in their country.
  2. First total each customer's spend, then compute the country average with a window function.
  3. Keep customers above it.
Concept

Comparison with a partition average.

Important

The PDF query compares a customer's total with the average single order amount of the country, which is not the same as average spend per customer. The version below compares totals with totals.

Corrected version:

SQL
WITH customer_totals AS (
    SELECT c.customer_id, c.country, SUM(o.amount) AS total_spent
    FROM customers c
    JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.customer_id, c.country
)
SELECT customer_id, country, total_spent
FROM (
    SELECT customer_id, country, total_spent,
        AVG(total_spent) OVER (PARTITION BY country) AS country_avg
    FROM customer_totals
) t
WHERE total_spent > country_avg;

261. Find employees who have not been assigned to any project in the last year.

SQL
SELECT e.*
FROM employees e
LEFT JOIN project_assignments pa ON e.id = pa.employee_id AND pa.assignment_date >= CURRENT_DATE - INTERVAL '1 year'
WHERE pa.project_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all project_assignments columns.
  3. WHERE pa.project_id IS NULL keeps only the employees rows that have no match in project_assignments.
Concept

Anti-join with a date condition in ON.

Important

Keep the date condition in the ON clause, not in WHERE.

262. Find the top 3 customers by total order amount in each region.

SQL
SELECT region, customer_id, total_amount
FROM (
    SELECT c.region, o.customer_id, SUM(o.amount) AS total_amount,
        ROW_NUMBER() OVER (PARTITION BY c.region ORDER BY SUM(o.amount) DESC) AS rn
    FROM customers c
    JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.region, o.customer_id
) sub
WHERE rn <= 3;

Logic:

  1. The inner query totals orders per customer within each region.
  2. ROW_NUMBER() ranks customers by total inside each region.
  3. rn <= 3 keeps three per region.
Concept

Top-N per group over an aggregate.

263. Find employees hired after their managers.

SQL
SELECT e.name AS employee_name, m.name AS manager_name, e.hire_date,
    m.hire_date AS manager_hire_date
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.hire_date > m.hire_date;

Logic:

  1. Self join each employee to their manager.
  2. e.hire_date > m.hire_date keeps employees hired later than the manager.
Concept

Self join with a date comparison.

264. Find customers who ordered all products from a specific category.

SQL
WITH category_products AS (
    SELECT product_id
    FROM products
    WHERE category_id = :category_id
), customer_products AS (
    SELECT customer_id, product_id
    FROM sales
    WHERE product_id IN (SELECT product_id FROM category_products)
    GROUP BY customer_id, product_id
)
SELECT customer_id
FROM customer_products
GROUP BY customer_id
HAVING COUNT(DISTINCT product_id) = (SELECT COUNT(*) FROM category_products);

Logic:

  1. The first CTE lists products of the category.
  2. The second CTE lists distinct products each customer bought from them.
  3. Customers whose count equals the number of category products ordered all of them.
Concept

Relational division with CTEs.

Note

:category_id is a bind parameter.

265. Find employees with the highest number of direct reports.

SQL
SELECT manager_id, COUNT(*) AS report_count
FROM employees
WHERE manager_id IS NOT NULL
GROUP BY manager_id
ORDER BY report_count DESC
LIMIT 1;

Logic:

  1. Count employees per manager_id.
  2. Return the manager with the highest count.
Concept

Top-1 group.

266. Calculate the retention rate of customers month-over-month.

SQL
WITH monthly_customers AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month
    FROM orders
    GROUP BY customer_id, month
), retention AS (
    SELECT current.month AS current_month, current.customer_id
    FROM monthly_customers current
    JOIN monthly_customers previous ON current.customer_id = previous.customer_id
        AND current.month = previous.month + INTERVAL '1 month'
)
SELECT current_month,
    COUNT(DISTINCT customer_id) * 100.0 / (SELECT COUNT(DISTINCT customer_id)
    FROM monthly_customers WHERE month = current_month - INTERVAL '1 month') AS retention_rate
FROM retention
GROUP BY current_month
ORDER BY current_month;

Logic:

  1. Get the distinct customers active in each month.
  2. For every month, find the customers who were also active in the following month.
  3. Retention = retained customers ÷ customers of the earlier month × 100.
Concept

Cohort-style retention.

Important

The PDF query refers to the alias current_month inside a subquery of the same SELECT, which most databases do not allow, and current is a reserved word in some of them. The version below uses a self join instead.

Corrected version:

SQL
WITH monthly_customers AS (
    SELECT DISTINCT customer_id, DATE_TRUNC('month', order_date) AS month
    FROM orders
)
SELECT p.month + INTERVAL '1 month' AS month,
    COUNT(c.customer_id) * 100.0 / COUNT(p.customer_id) AS retention_rate
FROM monthly_customers p
LEFT JOIN monthly_customers c
    ON c.customer_id = p.customer_id
    AND c.month = p.month + INTERVAL '1 month'
GROUP BY p.month
ORDER BY month;

267. Find the average time difference between order and delivery.

SQL
SELECT AVG(delivery_date - order_date) AS avg_delivery_time
FROM orders
WHERE delivery_date IS NOT NULL;

Logic:

  1. delivery_date - order_date is the delivery time.
  2. AVG() averages it for delivered orders.
  3. WHERE delivery_date IS NOT NULL excludes undelivered orders.
Concept

Date difference with AVG.

268. Find the department with the youngest average employee age.

SQL
SELECT department_id, AVG(EXTRACT(YEAR
        FROM AGE(CURRENT_DATE, birth_date))) AS avg_age
FROM employees
GROUP BY department_id
ORDER BY avg_age
LIMIT 1;

Logic:

  1. AGE(CURRENT_DATE, birth_date) gives each employee's age.
  2. EXTRACT(YEAR FROM ...) converts it to whole years.
  3. Average per department, sorted ascending, first row.
Concept

Age calculation.

Note

AGE() is PostgreSQL. MySQL uses TIMESTAMPDIFF(YEAR, birth_date, CURDATE()).

269. Find products that were sold in every quarter of the current year.

SQL
WITH quarterly_sales AS (
    SELECT product_id, DATE_TRUNC('quarter', sale_date) AS quarter
    FROM sales
    WHERE EXTRACT(YEAR FROM sale_date) = EXTRACT(YEAR FROM CURRENT_DATE)
    GROUP BY product_id, quarter
)
SELECT product_id
FROM quarterly_sales
GROUP BY product_id
HAVING COUNT(DISTINCT quarter) = 4;

Logic:

  1. DATE_TRUNC('quarter', sale_date) maps each sale to its quarter.
  2. Count the distinct quarters per product in the current year.
  3. Count 4 means the product sold in all quarters.
Concept

Relational division over periods.

270. Find customers whose orders decreased consecutively for 3 months.

SQL
WITH monthly_orders AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month,
        COUNT(*) AS order_count
    FROM orders
    GROUP BY customer_id, month
), orders_with_lag AS (
    SELECT customer_id, month, order_count,
        LAG(order_count, 1) OVER (PARTITION BY customer_id ORDER BY month) AS prev_1,
        LAG(order_count, 2) OVER (PARTITION BY customer_id ORDER BY month) AS prev_2
    FROM monthly_orders
)
SELECT DISTINCT customer_id
FROM orders_with_lag
WHERE order_count < prev_1 AND prev_1 < prev_2;

Logic:

  1. Count orders per customer per month.
  2. LAG(…, 1) and LAG(…, 2) bring in the previous two months.
  3. Keep customers where each month is lower than the one before.
Concept

Trend detection with LAG().

Note

LAG() looks at the previous row, so months without orders (no row) are skipped over.

SQL Interview Questions 271–305 — Medium to Advanced

271. Find the employee(s) with the highest number of late arrivals.

SQL
SELECT employee_id, COUNT(*) AS late_count
FROM attendance
WHERE arrival_time > scheduled_start_time
GROUP BY employee_id
ORDER BY late_count DESC
LIMIT 1;

Logic:

  1. Keep rows where the arrival time is after the scheduled start.
  2. Count them per employee.
  3. Return the highest.
Concept

Top-1 with a filter.

Note

Ties are not returned.

272. Find the most common product combinations in orders (pairs).

SQL
WITH order_pairs AS (
    SELECT o1.order_id, o1.product_id AS product1, o2.product_id AS product2
    FROM order_items o1
    JOIN order_items o2 ON o1.order_id = o2.order_id
        AND o1.product_id < o2.product_id
)
SELECT product1, product2, COUNT(*) AS pair_count
FROM order_pairs
GROUP BY product1, product2
ORDER BY pair_count DESC
LIMIT 10;

Logic:

  1. Join order_items to itself on the same order.
  2. o1.product_id < o2.product_id removes self-pairs and avoids counting each pair twice.
  3. Count how many orders contain each pair and return the most frequent.
Concept

Market-basket analysis with a self join.

273. Find employees who have worked more than 40 hours in a week.

SQL
WITH weekly_hours AS (
    SELECT employee_id, DATE_TRUNC('week', work_date) AS week_start,
        SUM(hours_worked) AS total_hours
    FROM work_logs
    GROUP BY employee_id, week_start
)
SELECT employee_id, week_start, total_hours
FROM weekly_hours
WHERE total_hours > 40;

Logic:

  1. DATE_TRUNC('week', work_date) groups days into weeks.
  2. SUM(hours_worked) totals each employee's weekly hours.
  3. Keep weeks above 40.
Concept

Weekly totals.

274. Find the total revenue generated per sales representative.

SQL
SELECT sales_rep_id, SUM(amount) AS total_revenue
FROM sales
GROUP BY sales_rep_id;

Logic:

  1. Group sales by sales_rep_id.
  2. SUM(amount) is each rep's revenue.
Concept

Basic aggregation.

275. Find customers with no orders in the last year.

SQL
SELECT customer_id
FROM customers
WHERE customer_id NOT IN (
    SELECT DISTINCT customer_id FROM orders
    WHERE order_date >= CURRENT_DATE - INTERVAL '1 year'
);

Logic:

  1. The subquery lists customers who ordered in the last year.
  2. NOT IN returns the other customers.
Concept

Exclusion with a subquery.

Important

NOT IN returns no rows if the subquery has a NULL customer id. Use NOT EXISTS if NULLs are possible (see Question 188).

276. Find products with an increasing sales trend over the last 3 months.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    WHERE sale_date >= CURRENT_DATE - INTERVAL '3 months'
    GROUP BY product_id, month
), sales_ranked AS (
    SELECT product_id, month, total_sales,
        LAG(total_sales) OVER (PARTITION BY product_id ORDER BY month) AS prev_month_sales,
        LAG(total_sales, 2) OVER (PARTITION BY product_id ORDER BY month) AS prev_2_month_sales
    FROM monthly_sales
)
SELECT DISTINCT product_id
FROM sales_ranked
WHERE total_sales > prev_month_sales AND prev_month_sales > prev_2_month_sales;

Logic:

  1. Total sales per product per month for the last three months.
  2. LAG() brings in the previous two months.
  3. Keep products where each month is higher than the previous one.
Concept

Strictly increasing trend.

277. Find departments where average salary is higher than the company average.

SQL
WITH company_avg AS (
    SELECT AVG(salary) AS avg_salary FROM employees
)
SELECT department_id, AVG(salary) AS dept_avg
FROM employees
GROUP BY department_id
HAVING AVG(salary) > (SELECT avg_salary FROM company_avg);

Logic:

  1. The CTE calculates the company average.
  2. Group by department.
  3. HAVING keeps departments above it.
Concept

Group filter with a CTE.

Note

Same as Question 141.

278. Find customers with orders where no product quantity is less than 5.

SQL
SELECT DISTINCT order_id
FROM order_items
GROUP BY order_id
HAVING MIN(quantity) >= 5;

Logic:

  1. Group order items by order.
  2. MIN(quantity) >= 5 means no line is below 5.
Concept

Condition on MIN().

Note

The query returns order ids. Join to orders to get the customers.

279. Find products ordered only by customers from one country.

SQL
SELECT product_id
FROM sales s
JOIN customers c ON s.customer_id = c.customer_id
GROUP BY product_id
HAVING COUNT(DISTINCT c.country) = 1;

Logic:

  1. Join sales to customers to find the country of each buyer.
  2. Count distinct countries per product.
  3. Keep products with exactly one.
Concept

Distinct count in HAVING.

Note

Same as Question 251.

280. Find employees who have not submitted their timesheets in the last month.

SQL
SELECT e.id, e.name
FROM employees e
LEFT JOIN timesheets t ON e.id = t.employee_id AND t.timesheet_date >= CURRENT_DATE - INTERVAL '1 month'
WHERE t.timesheet_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all timesheets columns.
  3. WHERE t.timesheet_id IS NULL keeps only the employees rows that have no match in timesheets.
Concept

Anti-join with a date condition in ON.

Important

Keep the date condition in the ON clause, not in WHERE.

281. Find the total discount given in each month.

SQL
SELECT DATE_TRUNC('month', order_date) AS month,
    SUM(discount_amount) AS total_discount
FROM orders
GROUP BY month
ORDER BY month;

Logic:

  1. DATE_TRUNC('month', order_date) maps each order to its month.
  2. SUM(discount_amount) totals the discounts per month.
Concept

Monthly aggregation.

282. Find customers who have placed orders but never paid by credit card.

SQL
SELECT DISTINCT customer_id
FROM orders
WHERE payment_method != 'Credit Card';

Logic:

  1. The goal is customers who have orders, none of which used a credit card.
  2. Group by customer and count orders paid by credit card.
  3. Keep customers whose count is 0.
Concept

Group-level condition.

Important

The query in the PDF returns customers who have at least one non-credit-card order, even if they also paid by credit card on other orders. Check the whole group instead.

Corrected version:

SQL
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING SUM(CASE WHEN payment_method = 'Credit Card' THEN 1 ELSE 0 END) = 0;

283. Find employees whose salaries are within 10% of their department’s average salary.

SQL
WITH dept_avg AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
)
SELECT e.*
FROM employees e
JOIN dept_avg d ON e.department_id = d.department_id
WHERE e.salary BETWEEN d.avg_salary * 0.9 AND d.avg_salary * 1.1;

Logic:

  1. The CTE calculates each department's average salary.
  2. BETWEEN avg * 0.9 AND avg * 1.1 keeps salaries within ±10% of it.
Concept

Range around a group average.

284. Find customers who ordered the most products in each category.

SQL
WITH product_totals AS (
    SELECT c.customer_id, p.category_id, SUM(s.quantity) AS total_quantity,
        RANK() OVER (PARTITION BY p.category_id
        ORDER BY SUM(s.quantity) DESC) AS rank
    FROM sales s
    JOIN products p ON s.product_id = p.product_id
    JOIN customers c ON s.customer_id = c.customer_id
    GROUP BY c.customer_id, p.category_id
)
SELECT customer_id, category_id, total_quantity
FROM product_totals
WHERE rank = 1;

Logic:

  1. Total quantity per customer per category.
  2. RANK() orders customers inside each category.
  3. Rank 1 is the top customer for that category.
Concept

Top-1 per group.

Important

rank is a function name in many databases, so it is safer to alias it as rnk. Ties all receive rank 1.

285. Find the top 5 longest projects.

SQL
SELECT project_id, start_date, end_date, end_date - start_date AS duration
FROM projects
ORDER BY duration DESC
LIMIT 5;

Logic:

  1. end_date - start_date is the project duration.
  2. Sort descending and keep five rows.
Concept

Top-N with a calculated column.

286. Find employees who have not taken any leave in the last 6 months.

SQL
SELECT e.id, e.name
FROM employees e
LEFT JOIN leaves l ON e.id = l.employee_id AND l.leave_date >= CURRENT_DATE - INTERVAL '6 months'
WHERE l.leave_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all leaves columns.
  3. WHERE l.leave_id IS NULL keeps only the employees rows that have no match in leaves.
Concept

Anti-join with a date condition in ON.

Important

Keep the date condition in the ON clause, not in WHERE.

287. Find the department with the most projects completed last year.

SQL
SELECT department_id, COUNT(*) AS completed_projects
FROM projects
WHERE status = 'Completed' AND completion_date BETWEEN DATE_TRUNC('year', CURRENT_DATE) - INTERVAL '1 year' AND DATE_TRUNC('year', CURRENT_DATE) - INTERVAL '1 day'
GROUP BY department_id
ORDER BY completed_projects DESC
LIMIT 1;

Logic:

  1. Keep completed projects whose completion date falls in the previous calendar year.
  2. Count per department.
  3. Return the highest.
Concept

Date range filter with top-1.

288. Find customers who have increased their order frequency month-over-month for 3 consecutive months.

SQL
WITH monthly_orders AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month,
        COUNT(*) AS order_count
    FROM orders
    GROUP BY customer_id, month
), orders_with_lag AS (
    SELECT customer_id, month, order_count,
        LAG(order_count, 1) OVER (PARTITION BY customer_id ORDER BY month) AS prev_1,
        LAG(order_count, 2) OVER (PARTITION BY customer_id ORDER BY month) AS prev_2
    FROM monthly_orders
)
SELECT DISTINCT customer_id
FROM orders_with_lag
WHERE order_count > prev_1 AND prev_1 > prev_2;

Logic:

  1. Count orders per customer per month.
  2. LAG(…, 1) and LAG(…, 2) bring in the previous two months.
  3. Keep customers where each month is higher than the previous one.
Concept

Strictly increasing trend.

289. Find employees who have been assigned projects outside their department.

SQL
SELECT DISTINCT e.id, e.name
FROM employees e
JOIN project_assignments pa ON e.id = pa.employee_id
JOIN projects p ON pa.project_id = p.project_id
WHERE e.department_id != p.department_id;

Logic:

  1. Join employees to their assignments and the projects.
  2. e.department_id != p.department_id keeps assignments to projects of another department.
  3. DISTINCT lists each employee once.
Concept

Join with an inequality condition.

290. Calculate the average time to close tickets per support agent.

SQL
SELECT support_agent_id, AVG(closed_date - opened_date) AS avg_close_time
FROM support_tickets
WHERE closed_date IS NOT NULL
GROUP BY support_agent_id;

Logic:

  1. closed_date - opened_date is the time to close.
  2. Only closed tickets are included.
  3. AVG() per agent.
Concept

Average duration per group.

291. Find the first and last login date for each user.

SQL
SELECT user_id, MIN(login_date) AS first_login, MAX(login_date) AS last_login
FROM user_logins
GROUP BY user_id;

Logic:

  1. MIN(login_date) and MAX(login_date) per user.
Concept

MIN and MAX aggregates.

292. Find customers who made purchases only in one month of the year.

SQL
WITH customer_months AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month
    FROM orders
    GROUP BY customer_id, month
)
SELECT customer_id
FROM customer_months
GROUP BY customer_id
HAVING COUNT(*) = 1;

Logic:

  1. Reduce orders to distinct customer and month pairs.
  2. Count the months per customer.
  3. Keep customers with exactly one month.
Concept

Distinct counts.

Note

The month includes the year, so the same calendar month in two years counts as two months.

293. Find products with sales revenue above the average revenue per product.

SQL
WITH avg_revenue AS (
    SELECT AVG(total_revenue) AS avg_rev
    FROM (
        SELECT product_id, SUM(amount) AS total_revenue
        FROM sales
        GROUP BY product_id
    ) sub
)
SELECT product_id, SUM(amount) AS total_revenue
FROM sales
GROUP BY product_id
HAVING SUM(amount) > (SELECT avg_rev FROM avg_revenue);

Logic:

  1. The CTE averages the product revenue totals.
  2. Group sales by product and total them.
  3. Keep products whose total is above the average.
Concept

Group filter against an average of totals.

294. Find departments where more than 50% of employees have a salary above $60,000.

SQL
SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(CASE WHEN salary > 60000 THEN 1
        ELSE 0 END) > 0.5;

Logic:

  1. The CASE returns 1 for salaries above 60,000 and 0 otherwise.
  2. AVG() of those values is the share of employees above 60,000.
  3. > 0.5 keeps departments where the share exceeds 50%.
Concept

Proportion with AVG(CASE ...).

295. Find employees who worked on all projects in the company.

SQL
WITH total_projects AS (
    SELECT COUNT(DISTINCT project_id) AS project_count FROM projects
), employee_projects AS (
    SELECT employee_id, COUNT(DISTINCT project_id) AS projects_worked
    FROM project_assignments
    GROUP BY employee_id
)
SELECT ep.employee_id
FROM employee_projects ep
JOIN total_projects tp ON 1=1
WHERE ep.projects_worked = tp.project_count;

Logic:

  1. The first CTE counts all projects.
  2. The second CTE counts distinct projects per employee.
  3. Employees whose count equals the total worked on every project.
Concept

Relational division.

Note

Same pattern as Question 135.

296. Find customers who ordered products from all categories.

SQL
WITH category_count AS (
    SELECT COUNT(DISTINCT category_id) AS total_categories FROM products
), customer_categories AS (
    SELECT customer_id, COUNT(DISTINCT p.category_id) AS categories_ordered
    FROM sales s
    JOIN products p ON s.product_id = p.product_id
    GROUP BY customer_id
)
SELECT customer_id
FROM customer_categories
JOIN category_count ON 1=1
WHERE categories_ordered = total_categories;

Logic:

  1. The first CTE counts all categories.
  2. The second counts the distinct categories each customer ordered from.
  3. Equal counts mean the customer covered every category.
Concept

Relational division.

297. Find the average tenure of employees by department.

SQL
SELECT department_id,
    AVG(DATE_PART('year', CURRENT_DATE - hire_date)) AS avg_tenure_years
FROM employees
GROUP BY department_id;

Logic:

  1. Subtract the hire date from today to get tenure.
  2. Convert to years and average per department.
Concept

Tenure calculation.

Important

DATE_PART('year', CURRENT_DATE - hire_date) fails for DATE columns in PostgreSQL because the subtraction returns an integer. Use AVG(CURRENT_DATE - hire_date) / 365.25 (see Question 52).

298. Find the number of orders placed on weekends vs weekdays.

SQL
SELECT CASE
    WHEN EXTRACT(DOW FROM order_date) IN (0,6) THEN 'Weekend'
    ELSE 'Weekday'
END AS day_type, COUNT(*) AS order_count
FROM orders
GROUP BY day_type;

Logic:

  1. EXTRACT(DOW FROM order_date) returns the day of week (0 = Sunday, 6 = Saturday).
  2. CASE labels days 0 and 6 as weekend and the rest as weekday.
  3. Group by the label and count.
Concept

Categorizing dates with CASE.

Note

DOW numbering is PostgreSQL's. MySQL uses DAYOFWEEK() (1 = Sunday) and SQL Server uses DATEPART(weekday, ...).

299. Find the percentage of orders with discounts per month.

SQL
SELECT DATE_TRUNC('month', order_date) AS month,
    100.0 * SUM(CASE WHEN discount > 0 THEN 1
        ELSE 0 END) / COUNT(*) AS discount_percentage
FROM orders
GROUP BY month
ORDER BY month;

Logic:

  1. The CASE returns 1 when a discount exists and 0 otherwise.
  2. SUM(...) counts discounted orders and COUNT(*) counts all orders.
  3. Dividing and multiplying by 100.0 gives the percentage per month.
Concept

Percentage with conditional aggregation.

300. Find the employees who have never been late to work.

SQL
SELECT e.id, e.name
FROM employees e
LEFT JOIN attendance a ON e.id = a.employee_id
    AND a.arrival_time > a.scheduled_start_time
WHERE a.employee_id IS NULL;

Logic:

  1. LEFT JOIN attendance rows that are late (condition in ON).
  2. Employees without a late record have NULL.
  3. WHERE a.employee_id IS NULL returns them.
Concept

Anti-join with a condition in ON.

Note

Employees with no attendance rows at all are also returned.

301. Find products with sales only during holiday seasons.

SQL
SELECT product_id
FROM sales s
JOIN holidays h ON s.sale_date = h.holiday_date
GROUP BY product_id
HAVING COUNT(*) = (SELECT COUNT(*) FROM sales WHERE product_id = s.product_id);

Logic:

  1. The goal is products whose sales all fall on holiday dates.
  2. Join sales to holidays with a LEFT JOIN.
  3. COUNT(*) counts all sales and COUNT(h.holiday_date) counts only those on holidays; equal counts mean all sales were on holidays.
Concept

Comparing counts after a left join.

Important

The query in the PDF refers to s.product_id inside a subquery in HAVING, which is not allowed because s is not a grouped column; it also uses an inner join, so the total in the subquery would not match. Use the LEFT JOIN count comparison.

Corrected version:

SQL
SELECT s.product_id
FROM sales s
LEFT JOIN holidays h ON s.sale_date = h.holiday_date
GROUP BY s.product_id
HAVING COUNT(*) = COUNT(h.holiday_date);

302. Find the department with the largest increase in employee count compared to last year.

SQL
WITH current_year AS (
    SELECT department_id, COUNT(*) AS emp_count
    FROM employees
    WHERE hire_date <= CURRENT_DATE AND (termination_date IS NULL OR termination_date >= CURRENT_DATE)
    GROUP BY department_id
), last_year AS (
    SELECT department_id, COUNT(*) AS emp_count
    FROM employees
    WHERE hire_date <= CURRENT_DATE - INTERVAL '1 year' AND (termination_date IS NULL
            OR termination_date >= CURRENT_DATE - INTERVAL '1 year')
    GROUP BY department_id
)
SELECT c.department_id, c.emp_count - COALESCE(l.emp_count,0) AS increase
FROM current_year c
LEFT JOIN last_year l ON c.department_id = l.department_id
ORDER BY increase DESC
LIMIT 1;

Logic:

  1. The first CTE counts the employees currently active in each department.
  2. The second CTE counts those who were active one year ago.
  3. Subtract to get the increase and return the largest.
Concept

Comparing two point-in-time snapshots.

303. Find the average order value per customer segment.

SQL
SELECT segment, AVG(o.amount) AS avg_order_value
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
GROUP BY segment;

Logic:

  1. Join customers to orders.
  2. Group by segment.
  3. AVG(amount) per segment.
Concept

Join with aggregation.

304. Find employees who manage more than 3 projects.

SQL
SELECT manager_id, COUNT(DISTINCT project_id) AS project_count
FROM projects
GROUP BY manager_id
HAVING COUNT(DISTINCT project_id) > 3;

Logic:

  1. Group projects by manager.
  2. Count distinct projects.
  3. HAVING keeps managers with more than three.
Concept

Distinct count in HAVING.

Note

Same as Question 92.

305. Find products that have never been returned.

SQL
SELECT p.product_id
FROM products p
LEFT JOIN returns r ON p.product_id = r.product_id
WHERE r.return_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from products.
  2. Rows without a match have NULL in all returns columns.
  3. WHERE r.return_id IS NULL keeps only the products rows that have no match in returns.
Concept

Anti-join using LEFT JOIN … IS NULL.

SQL Interview Questions 306–335 — Medium to Advanced

306. Find customers with orders but no shipments.

SQL
SELECT DISTINCT o.customer_id
FROM orders o
LEFT JOIN shipments s ON o.order_id = s.order_id
WHERE s.shipment_id IS NULL;

Logic:

  1. LEFT JOIN shipments to orders.
  2. Orders with no shipment have NULL shipment columns.
  3. DISTINCT returns each customer once.
Concept

Anti-join on orders.

307. Find employees whose salaries increased every year.

SQL
WITH salary_diff AS (
    SELECT employee_id, year, salary,
        LAG(salary) OVER (PARTITION BY employee_id ORDER BY year) AS prev_salary
    FROM salaries
)
SELECT DISTINCT employee_id
FROM salary_diff
WHERE salary > prev_salary OR prev_salary IS NULL
GROUP BY employee_id
HAVING COUNT(*) = (SELECT COUNT(*) FROM salaries s2 WHERE s2.employee_id = salary_diff.employee_id);

Logic:

  1. LAG(salary) returns the previous year's salary.
  2. Count rows where the salary rose (or the first year with no previous value).
  3. Employees whose count equals their total number of salary rows increased every year.
Concept

Consistent-trend check.

308. Find the total number of unique products sold in the last quarter.

SQL
SELECT COUNT(DISTINCT product_id) AS unique_products_sold
FROM sales
WHERE sale_date >= DATE_TRUNC('quarter', CURRENT_DATE) - INTERVAL '3 months'
    AND sale_date < DATE_TRUNC('quarter', CURRENT_DATE);

Logic:

  1. The date range runs from the start of the previous quarter up to the start of the current quarter.
  2. COUNT(DISTINCT product_id) counts the unique products.
Concept

Previous-quarter date range.

309. Find the day with the highest sales in each month.

SQL
WITH daily_sales AS (
    SELECT DATE(order_date) AS day, SUM(amount) AS total_sales
    FROM orders
    GROUP BY day
), ranked_sales AS (
    SELECT day, total_sales,
        RANK() OVER (PARTITION BY DATE_TRUNC('month', day) ORDER BY total_sales DESC) AS sales_rank
    FROM daily_sales
)
SELECT day, total_sales
FROM ranked_sales
WHERE sales_rank = 1;

Logic:

  1. The first CTE totals sales per day.
  2. RANK() orders days within each month by total.
  3. Rank 1 is the best day of that month.
Concept

Top-1 per group.

Note

Ties for the best day are all returned.

310. Find the products with the highest sales increase compared to the previous month.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, month
), sales_diff AS (
    SELECT product_id, month, total_sales,
        LAG(total_sales) OVER (PARTITION BY product_id ORDER BY month) AS prev_month_sales
    FROM monthly_sales
)
SELECT product_id, month, total_sales - prev_month_sales AS increase
FROM sales_diff
WHERE prev_month_sales IS NOT NULL
ORDER BY increase DESC
LIMIT 10;

Logic:

  1. Total sales per product per month.
  2. LAG() retrieves the previous month's total.
  3. The increase is the difference; sort descending and keep the top rows.
Concept

Month-over-month increase.

311. Find the top 5 customers by total order value in the last year.

SQL
SELECT customer_id, SUM(amount) AS total_order_value
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '1 year'
GROUP BY customer_id
ORDER BY total_order_value DESC
LIMIT 5;

Logic:

  1. Keep orders from the last year.
  2. Total per customer.
  3. Sort descending and keep five.
Concept

Top-N with a filter.

312. Find the number of employees who changed departments in the last year.

SQL
SELECT COUNT(DISTINCT employee_id)
FROM employee_department_history
WHERE change_date >= CURRENT_DATE - INTERVAL '1 year';

Logic:

  1. Keep department changes from the last year.
  2. COUNT(DISTINCT employee_id) counts employees with at least one change.
Concept

Distinct count with a date filter.

313. Find the average salary for each job title within each department.

SQL
SELECT department_id, job_title, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id, job_title;

Logic:

  1. Group by department and job title.
  2. AVG(salary) per group.
Concept

Multi-column grouping.

314. Find customers who placed orders with multiple payment methods.

SQL
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(DISTINCT payment_method) > 1;

Logic:

  1. Group orders by customer.
  2. Count distinct payment methods.
  3. Keep customers with more than one.
Concept

Distinct count in HAVING.

315. Find products with the lowest average rating per category.

SQL
SELECT category_id, product_id, AVG(rating) AS avg_rating
FROM product_reviews
GROUP BY category_id,
    product_id QUALIFY ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY AVG(rating)) = 1;

Logic:

  1. The query averages ratings per product and keeps the lowest in each category.
Concept

Top-1 per group over an aggregate.

Important

QUALIFY is supported by Snowflake, BigQuery and Teradata but not by PostgreSQL, MySQL or SQL Server. The portable version uses a subquery.

Portable version:

SQL
SELECT category_id, product_id, avg_rating
FROM (
    SELECT category_id, product_id, AVG(rating) AS avg_rating,
        RANK() OVER (PARTITION BY category_id ORDER BY AVG(rating)) AS rnk
    FROM product_reviews
    GROUP BY category_id, product_id
) t
WHERE rnk = 1;

316. Find employees who have never received a promotion.

SQL
SELECT e.id, e.name
FROM employees e
LEFT JOIN promotions p ON e.id = p.employee_id
WHERE p.promotion_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from employees.
  2. Rows without a match have NULL in all promotions columns.
  3. WHERE p.promotion_id IS NULL keeps only the employees rows that have no match in promotions.
Concept

Anti-join using LEFT JOIN … IS NULL.

317. Find the total number of orders placed each day in the last week.

SQL
SELECT DATE(order_date) AS order_day, COUNT(*) AS orders_count
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY order_day
ORDER BY order_day;

Logic:

  1. Keep orders from the last 7 days.
  2. Group by date and count.
Concept

Daily counts.

318. Find customers with orders in both online and in-store channels.

SQL
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(DISTINCT order_channel) > 1;

Logic:

  1. Group orders by customer.
  2. Count distinct order channels.
  3. More than one means the customer used both.
Concept

Distinct count in HAVING.

Note

With exactly two channels this means both. With more channels, filter for the two specific ones first.

319. Find the top 3 sales reps by number of deals closed this quarter.

SQL
SELECT sales_rep_id, COUNT(*) AS deals_closed
FROM sales_deals
WHERE deal_close_date >= DATE_TRUNC('quarter', CURRENT_DATE)
GROUP BY sales_rep_id
ORDER BY deals_closed DESC
LIMIT 3;

Logic:

  1. Keep deals closed since the start of this quarter.
  2. Count per rep.
  3. Sort descending and keep three.
Concept

Top-N with a date filter.

320. Find products that have been discontinued but still have sales.

SQL
SELECT p.product_id
FROM products p
JOIN sales s ON p.product_id = s.product_id
WHERE p.discontinued = TRUE;

Logic:

  1. Join products to sales.
  2. Keep products marked as discontinued.
Concept

Join with a filter.

Note

A product with several sales appears several times; add DISTINCT to list each product once.

321. Find employees who report to a manager hired after them.

SQL
SELECT e.id, e.name, m.id AS manager_id, m.name AS manager_name
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.hire_date < m.hire_date;

Logic:

  1. Self join each employee to their manager.
  2. e.hire_date < m.hire_date keeps employees hired before their manager.
Concept

Self join with a date comparison.

Note

Same as Question 140.

322. Find the average delivery time by shipping method.

SQL
SELECT shipping_method, AVG(delivery_date - order_date) AS avg_delivery_time
FROM shipments
GROUP BY shipping_method;

Logic:

  1. delivery_date - order_date is the delivery time.
  2. AVG() per shipping method.
Concept

Average duration per group.

323. Find orders where the total quantity exceeds 100.

SQL
SELECT order_id, SUM(quantity) AS total_quantity
FROM order_items
GROUP BY order_id
HAVING SUM(quantity) > 100;

Logic:

  1. Group order items by order.
  2. SUM(quantity) per order.
  3. Keep totals above 100.
Concept

HAVING with SUM.

Note

Same as Question 215.

324. Find customers who made orders but never returned a product.

SQL
SELECT DISTINCT o.customer_id
FROM orders o
LEFT JOIN returns r ON o.order_id = r.order_id
WHERE r.return_id IS NULL;

Logic:

  1. The goal is customers none of whose orders have a return.
  2. NOT EXISTS checks that no return exists for any order of the customer.
Concept

Exclusion with NOT EXISTS.

Important

The PDF query returns customers who have at least one order without a return, even if other orders were returned. Check all of the customer's orders instead.

Corrected version:

SQL
SELECT DISTINCT o.customer_id
FROM orders o
WHERE NOT EXISTS (
    SELECT 1
    FROM returns r
    JOIN orders o2 ON r.order_id = o2.order_id
    WHERE o2.customer_id = o.customer_id
);

325. Find products that have been ordered but never reviewed.

SQL
SELECT p.product_id
FROM products p
LEFT JOIN product_reviews pr ON p.product_id = pr.product_id
JOIN sales s ON p.product_id = s.product_id
WHERE pr.review_id IS NULL
GROUP BY p.product_id;

Logic:

  1. LEFT JOIN reviews to products.
  2. JOIN sales to keep only products that were ordered.
  3. pr.review_id IS NULL keeps products without reviews.
Concept

Anti-join combined with a join.

326. Find employees who have worked on projects for more than 2 years.

SQL
SELECT employee_id
FROM project_assignments
GROUP BY employee_id
HAVING MAX(assignment_end_date) - MIN(assignment_start_date) > INTERVAL '2 years';

Logic:

  1. MAX(end_date) - MIN(start_date) is the span from the first start to the last end.
  2. HAVING keeps spans above two years.
Concept

Duration in HAVING.

Note

This measures the overall span, not the sum of project durations. For DATE columns, compare MAX(assignment_end_date) > MIN(assignment_start_date) + INTERVAL '2 years'.

327. Find the product with the highest sales for each month.

SQL
WITH monthly_sales AS (
    SELECT product_id, DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS total_sales
    FROM sales
    GROUP BY product_id, month
), ranked_sales AS (
    SELECT product_id, month, total_sales,
        ROW_NUMBER() OVER (PARTITION BY month ORDER BY total_sales DESC) AS rn
    FROM monthly_sales
)
SELECT product_id, month, total_sales
FROM ranked_sales
WHERE rn = 1;

Logic:

  1. Total per product per month.
  2. ROW_NUMBER() orders products in each month.
  3. rn = 1 returns the best product.
Concept

Top-1 per group.

Note

Use RANK() to return products that tie for first.

328. Find customers with the highest order count in each region.

SQL
WITH customer_order_counts AS (
    SELECT c.region, o.customer_id, COUNT(*) AS order_count,
        ROW_NUMBER() OVER (PARTITION BY c.region ORDER BY COUNT(*) DESC) AS rn
    FROM customers c
    JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.region, o.customer_id
)
SELECT region, customer_id, order_count
FROM customer_order_counts
WHERE rn = 1;

Logic:

  1. Join customers to orders and count orders per customer.
  2. ROW_NUMBER() ranks customers within each region by order count.
  3. rn = 1 returns the top customer per region.
Concept

Top-1 per group over an aggregate.

Important

The PDF solution is cut off after JOIN orders o; the version shown here is completed. Ties are not returned with ROW_NUMBER(); use RANK() to include them.

329. Flag customers with an increase in orders every month this year.

SQL
WITH monthly_counts AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month, COUNT(*) AS cnt
    FROM orders
    WHERE EXTRACT(YEAR FROM order_date) = EXTRACT(YEAR FROM CURRENT_DATE)
    GROUP BY customer_id, month
), increase_check AS (
    SELECT customer_id, LAG(cnt) OVER (PARTITION BY customer_id
        ORDER BY month) AS prev_cnt, cnt
    FROM monthly_counts
)
SELECT DISTINCT customer_id
FROM increase_check
WHERE cnt > prev_cnt AND prev_cnt IS NOT NULL;

Logic:

  1. Count orders per customer per month this year.
  2. LAG(cnt) brings in the previous month's count.
  3. A customer qualifies only if every month-to-month comparison is an increase.
Concept

Consistent-trend check.

Important

The PDF query returns customers who had at least one month with an increase, not an increase every month. The version below requires every comparison to be an increase.

Corrected version:

SQL
WITH monthly_counts AS (
    SELECT customer_id, DATE_TRUNC('month', order_date) AS month, COUNT(*) AS cnt
    FROM orders
    WHERE EXTRACT(YEAR FROM order_date) = EXTRACT(YEAR FROM CURRENT_DATE)
    GROUP BY customer_id, month
), increase_check AS (
    SELECT customer_id, cnt,
        LAG(cnt) OVER (PARTITION BY customer_id ORDER BY month) AS prev_cnt
    FROM monthly_counts
)
SELECT customer_id
FROM increase_check
WHERE prev_cnt IS NOT NULL
GROUP BY customer_id
HAVING MIN(CASE WHEN cnt > prev_cnt THEN 1 ELSE 0 END) = 1;

330. Find employees whose hire date is the same weekday as their manager’s.

SQL
SELECT e.id, e.name
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE EXTRACT(DOW FROM e.hire_date) = EXTRACT(DOW FROM m.hire_date);

Logic:

  1. Join each employee to their manager.
  2. EXTRACT(DOW FROM hire_date) returns the day of the week.
  3. Keep rows where both weekdays are equal.
Concept

Comparing date parts.

331. Get total working hours per employee per week.

SQL
SELECT employee_id, DATE_TRUNC('week', work_date) AS week_start,
    SUM(hours_worked) AS total_hours
FROM work_logs
GROUP BY employee_id, week_start;

Logic:

  1. DATE_TRUNC('week', work_date) gives the week start.
  2. SUM(hours_worked) per employee and week.
Concept

Weekly totals.

332. Identify suppliers who delivered to all regions.

SQL
WITH total_regions AS (
    SELECT COUNT(DISTINCT region) AS total FROM suppliers
), supplier_regions AS (
    SELECT supplier_id, COUNT(DISTINCT delivery_region) AS regions_served
    FROM deliveries
    GROUP BY supplier_id
)
SELECT supplier_id
FROM supplier_regions
JOIN total_regions ON regions_served = total;

Logic:

  1. The first CTE counts all regions.
  2. The second counts the distinct regions each supplier delivered to.
  3. Equal counts mean the supplier covered every region.
Concept

Relational division.

333. Find products ordered on their launch date.

SQL
SELECT o.product_id
FROM orders o
JOIN products p ON o.product_id = p.product_id
WHERE CAST(o.order_date AS DATE) = p.launch_date;

Logic:

  1. Join orders to products.
  2. Cast the order timestamp to a date and compare with the launch date.
Concept

Join with a date comparison.

Note

Add DISTINCT to return each product once.

334. Retrieve employees with salary in top 5% company-wide.

SQL
WITH salary_ranks AS (
    SELECT salary, PERCENT_RANK() OVER (ORDER BY salary DESC) AS pr
    FROM employees
)
SELECT e.*
FROM employees e
JOIN salary_ranks sr ON e.salary = sr.salary
WHERE sr.pr <= 0.05;

Logic:

  1. PERCENT_RANK() ranks salaries from 0 (highest) to 1 (lowest).
  2. pr <= 0.05 keeps the top 5%.
  3. The result is joined back to employees.
Concept

Percentile filtering.

Important

Joining on salary repeats rows when several employees share a salary, because the ranking CTE has one row per employee. Calculate the rank directly on employees instead.

Simpler version:

SQL
SELECT *
FROM (
    SELECT e.*, PERCENT_RANK() OVER (ORDER BY salary DESC) AS pr
    FROM employees e
) t
WHERE pr <= 0.05;

335. List departments with no open positions.

SQL
SELECT d.department_id
FROM departments d
LEFT JOIN job_openings j ON d.department_id = j.department_id AND j.status = 'Open'
WHERE j.job_id IS NULL;

Logic:

  1. LEFT JOIN keeps every row from departments.
  2. Rows without a match have NULL in all job_openings columns.
  3. WHERE j.job_id IS NULL keeps only the departments rows that have no match in job_openings.
Concept

Anti-join with a condition in ON.

Important

j.status = 'Open' must stay in the ON clause. In WHERE it would remove the NULL rows.