SQL Interview Notes
Medium to Advanced SQL Interview Questions with Solutions and Explanations: Joins, Subqueries, Window Functions, CTEs, Recursive Queries, Gaps and Islands and more
Table of Contents
SQL Interview Questions 1–40 — Medium to Advanced
1. Find the second highest salary from the Employee table.
SELECT MAX(salary) AS SecondHighestSalary
FROM employees
WHERE salary < (
SELECT MAX(salary)
FROM employees
);Logic:
- The inner query finds the highest salary.
WHERE salary <that value removes the top salary.MAX(salary)of the remaining rows is the second-highest distinct salary.
Subquery with an aggregate function.
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.
SELECT name, COUNT(*)
FROM employees
GROUP BY name
HAVING COUNT(*) > 1;Logic:
GROUP BY nameputs identical names in one group.COUNT(*)counts the rows in each group.HAVING COUNT(*) > 1keeps only the groups that appear more than once.
Duplicate detection with GROUP BY and HAVING.
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.
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:
- Join
employeesto itself:eis the employee,mis the manager. e.manager_id = m.idlinks each employee to their manager's row.WHERE e.salary > m.salarykeeps employees who earn more than their manager.
Self join.
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.
SELECT department_id, COUNT(*) AS num_employees
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 5;Logic:
GROUP BY department_idcreates one group per department.COUNT(*)counts the employees in each group.HAVING COUNT(*) > 5filters the groups after aggregation.
HAVING filters groups; WHERE filters rows.
5. Find employees who joined in the last 6 months.
SELECT *
FROM employees
WHERE join_date >= CURRENT_DATE - INTERVAL '6 months';Logic:
CURRENT_DATE - INTERVAL '6 months'computes the date six months ago.join_date >=that date keeps recent joiners.
Date arithmetic in WHERE.
This is PostgreSQL syntax. MySQL: DATE_SUB(CURDATE(), INTERVAL 6 MONTH). SQL Server: DATEADD(month, -6, GETDATE()).
6. Get departments with no employees.
SELECT d.department_name
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
WHERE e.id IS NULL;Logic:
LEFT JOINkeeps every row fromdepartments.- Rows without a match have
NULLin allemployeescolumns. WHERE e.id IS NULLkeeps only thedepartmentsrows that have no match inemployees.
Anti-join to find parents without children.
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.
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:
- Count the rows (
N). The middle position is(N - 1) / 2(integer division), used as theOFFSET. LIMIT 2 - N % 2fetches 1 row whenNis odd and 2 rows whenNis even.AVG(salary)of those one or two middle rows is the median.
Median using ORDER BY, LIMIT and OFFSET.
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.
SELECT name, department_id, salary,
SUM(salary) OVER (PARTITION BY department_id ORDER BY id) AS running_total
FROM employees;Logic:
PARTITION BY department_idrestarts the total for each department.ORDER BY iddefines the order in which rows are added.SUM(salary) OVER (...)adds salaries from the first row up to the current row.
Running total with SUM() OVER.
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.
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:
ROW_NUMBER()numbers each user's login dates in order.- Subtracting that number of days from the date gives the same value (
grp) for every date in an unbroken streak. - Group by
user_idandgrp;COUNT(*)is the streak length andMIN/MAXgive its start and end.
Gaps and islands technique.
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:
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.
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:
- The anchor query starts with the top employee (
manager_id IS NULL) at level 1. - The recursive part joins employees to the rows already found through
manager_id = rc.id, adding 1 to the level each time. - Recursion stops when no more employees are found; the final query orders by level.
Showing the chain as text:
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;Recursive CTE for hierarchies.
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
(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:
- For each
id, check whether a row withid + 1exists. NOT EXISTSis true when the next number is missing.id + 1is reported as the missing ID.
Gap detection using NOT EXISTS.
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:
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.
SELECT name, salary, CUME_DIST() OVER (ORDER BY salary) AS salary_cdf
FROM employees;Logic:
ORDER BY salarysorts employees from lowest to highest salary.CUME_DIST()returns the fraction of rows with a salary less than or equal to the current salary.
Cumulative distribution window function.
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).
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:
FULL OUTER JOINkeeps rows that exist in only one of the tables.IS DISTINCT FROMcompares values and treatsNULLas a normal value (twoNULLs are equal).- 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):
(SELECT * FROM table1 EXCEPT SELECT * FROM table2)
UNION ALL
(SELECT * FROM table2 EXCEPT SELECT * FROM table1);Table comparison with null-safe operators.
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.
SELECT name, salary, RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees;Logic:
ORDER BY salary DESCranks the highest salary first.RANK()gives equal salaries the same rank.- The next rank skips numbers after a tie (1, 2, 2, 4).
RANK() window function.
Use DENSE_RANK() when you do not want gaps after ties (1, 2, 2, 3).
15. Find customers who have not made any purchase.
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:
LEFT JOINkeeps every row fromcustomers.- Rows without a match have
NULLin allsalescolumns. WHERE s.sale_id IS NULLkeeps only thecustomersrows that have no match insales.
Anti-join to find customers without activity.
16. Write a query to perform a conditional aggregation
(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:
CASE WHEN gender = 'M' THEN 1 ENDreturns 1 for males andNULLotherwise.COUNT()ignoresNULLvalues, so it counts only the matching rows.GROUP BY department_idproduces one row per department.
Conditional aggregation.
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).
SELECT name, salary, salary - LAG(salary) OVER (ORDER BY id) AS salary_diff
FROM employees;Logic:
LAG(salary)returns the salary from the previous row in theORDER BY idorder.- Subtracting it from the current salary gives the difference.
LAG() window function.
The first row has no previous row, so its difference is NULL.
18. Identify overlapping date ranges for bookings.
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:
- Join the
bookingstable to itself to compare every pair of bookings. - Two ranges overlap when each one starts on or before the other one ends:
start1 <= end2 AND end1 >= start2. b1.booking_id <> b2.booking_idprevents comparing a booking with itself.
Interval overlap test with a self join.
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.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees)
ORDER BY salary DESC;Logic:
- The scalar subquery calculates the company's average salary.
WHERE salary >keeps employees above it.ORDER BY salary DESClists the highest earners first.
Scalar subquery in WHERE.
20. Aggregate JSON data (if supported) to list all employee names in a department as a JSON array.
SELECT department_id, JSON_AGG(name) AS employee_names
FROM employees
GROUP BY department_id;Logic:
GROUP BY department_idcreates one group per department.JSON_AGG(name)collects the names of each group into one JSON array.
JSON aggregation.
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.
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:
- The self join links each employee
eto their managerm. WHERE e.salary = m.salarykeeps employees who earn exactly their manager's salary.
Self join with an equality comparison.
22. Write a query to get the first and last purchase date for each customer.
SELECT customer_id, MIN(purchase_date) AS first_purchase,
MAX(purchase_date) AS last_purchase
FROM sales
GROUP BY customer_id;Logic:
GROUP BY customer_idcreates one group per customer.MIN(purchase_date)is the first purchase andMAX(purchase_date)is the last.
MIN and MAX aggregates.
Customers with no purchases are not returned. Question 73 shows how to include them.
23. Find departments with the highest average salary.
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:
- The CTE calculates the average salary of each department.
- The subquery finds the largest of those averages.
- The outer query keeps departments whose average equals that maximum.
CTE with a nested aggregate.
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.
SELECT job_title, COUNT(*) AS num_employees
FROM employees
GROUP BY job_title;Logic:
GROUP BY job_titlecreates one group per title.COUNT(*)counts the employees in each group.
Basic GROUP BY with COUNT.
25. Find employees who don’t have a department assigned.
SELECT *
FROM employees
WHERE department_id IS NULL;Logic:
department_id IS NULLselects rows where no department was assigned.
NULL handling.
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.
SELECT id, DATEDIFF(day, start_date, end_date) AS days_difference
FROM projects;Logic:
DATEDIFF(day, start_date, end_date)returns the number of days between the two dates for each project.
Date difference function.
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.
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:
ORDER BY hire_datedefines the order of employees.ROWS BETWEEN 2 PRECEDING AND CURRENT ROWcreates a window of the current row and the two rows before it.AVG(salary)averages the salaries inside that window.
Moving average with a window frame.
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.
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY purchase_date DESC) AS rn
FROM sales
) sub
WHERE rn = 1;Logic:
PARTITION BY customer_id ORDER BY purchase_date DESCnumbers each customer's purchases from newest to oldest.rn = 1selects the newest purchase of each customer.
ROW_NUMBER() for top-1 per group.
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.
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:
- The anchor row is the top employee at depth 1.
- Each recursion joins the employees who report to the rows found so far and adds 1 to the depth.
- The final query returns every employee with their depth.
Recursive CTE for hierarchy depth.
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.
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:
- Self join
employeesondepartment_idto pair employees within a department. e1.id < e2.idremoves self-pairs and prevents the same pair from appearing in both orders.
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).
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:
- Each
CASEexpression returns 1 for one job title and 0 for the others. SUM()of those values counts employees of that title.GROUP BY department_idgives one row per department, with one column per title.
Pivoting with conditional aggregation.
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.
SELECT customer_id
FROM sales s
GROUP BY customer_id
HAVING COUNT(DISTINCT category_id) = (SELECT COUNT(DISTINCT category_id) FROM sales);Logic:
- Count the distinct categories each customer bought from.
- The subquery counts all distinct categories in
sales. HAVINGkeeps customers whose own count equals the total.
Relational division with COUNT(DISTINCT).
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.
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:
- Join employees to their raise history.
MAX(raise_date)is each employee's latest raise.HAVINGkeeps employees whose latest raise is more than a year old.
Aggregation with a date condition in HAVING.
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.
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:
- The subquery totals each salesperson's sales per month.
PARTITION BY sale_monthrestarts the ranking for every month.ORDER BY total_sales DESCgives rank 1 to the best seller.
Ranking within partitions.
35. Calculate the percentage change in sales compared to the previous month for each product.
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:
- The subquery totals sales per product per month.
LAG(total_sales)retrieves the same product's previous month.(current - previous) * 100.0 / previousis the percentage change.
Month-over-month change with LAG().
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.
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:
- The first condition compares the salary with the company average.
- The correlated subquery finds the highest salary in the employee's own department.
- Both conditions must be true.
Correlated subquery combined with a scalar subquery.
37. Retrieve the last 5 orders for each customer.
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:
ROW_NUMBER()numbers each customer's orders from newest to oldest.rn <= 5keeps the five most recent.
Top-N per group.
38. Find employees with no salary changes in the last 2 years.
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:
LEFT JOINsalary changes, but only those from the last two years (condition inON).- Employees with no such change get
NULLvalues. WHERE sh.employee_id IS NULLkeeps them.
Anti-join with a date filter.
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.
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
ORDER BY avg_salary
LIMIT 1;Logic:
AVG(salary)is calculated for each department.ORDER BY avg_salarysorts from lowest to highest.LIMIT 1returns the lowest.
Top-1 with ORDER BY and LIMIT.
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.
SELECT *
FROM employees
WHERE LEFT(name, 1) = RIGHT(name, 1);Logic:
LEFT(name, 1)is the first character andRIGHT(name, 1)is the last.- The
WHEREclause keeps rows where both are equal.
String functions.
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).
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:
- The query below walks upward from each employee through
manager_id, remembering where it started. - If the walk returns to the starting employee, that employee is part of a loop.
steps < (SELECT COUNT(*) ...)stops the recursion in loops that never return to the start.
Cycle detection in a recursive CTE.
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:
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.
SELECT customer_id, sale_date, amount,
SUM(amount) OVER (PARTITION BY customer_id ORDER BY sale_date) AS running_total
FROM sales;Logic:
PARTITION BY customer_idgives each customer a separate total.ORDER BY sale_dateadds sales in date order.SUM(amount) OVER (...)returns the cumulative amount.
Running total with a window function.
43. Find the department-wise salary percentile (e.g., 90th percentile) using window functions.
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:
PERCENTILE_CONT(0.9)returns the value below which 90% of the salaries fall, interpolating between rows if needed.WITHIN GROUP (ORDER BY salary)defines the sort order used to find it.- The result is calculated for each department.
Percentiles.
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):
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.
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:
- Generate candidate divisors from 2 up to the square root of each salary.
- A salary is prime if no divisor divides it evenly (
NOT EXISTS). - Salaries below 2 are excluded.
Prime test with a set-generating function.
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:
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.
SELECT employee_id
FROM employee_department_history
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id) > 1;Logic:
GROUP BY employee_idgroups the history rows of each employee.COUNT(DISTINCT department_id) > 1keeps employees who worked in more than one department.
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.
SELECT product_id, sale_date, amount,
amount - LAG(amount) OVER (PARTITION BY product_id ORDER BY sale_date) AS sales_diff
FROM sales;Logic:
PARTITION BY product_idcompares rows only within the same product.ORDER BY sale_datedefines the row order.amount - LAG(amount)is the change from the previous sale.
LAG() with partitions.
47. Write a query to find all employees who are at the lowest level in the hierarchy (no subordinates).
SELECT *
FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM employees sub WHERE sub.manager_id = e.id
);Logic:
NOT EXISTSchecks whether any employee has this employee as their manager.- Employees with no subordinates are returned.
Leaf nodes of a hierarchy.
48. Find average order value per month and product category.
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:
DATE_TRUNC('month', order_date)converts each date to the first day of its month.- Grouping by month and category gives one row per combination.
AVG(order_value)is the average within each group.
Time bucketing with DATE_TRUNC.
49. Write a query to create a running count of how many employees joined in each year.
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:
- The inner query extracts the hire year.
COUNT(*)counts hires per year.SUM(COUNT(*)) OVER (ORDER BY join_year)adds the yearly counts cumulatively.
Window function on top of an aggregate.
50. Write a query to find the second most recent order date per customer.
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:
- Number each customer's orders from newest to oldest.
rn = 2selects the second one.
Nth row per group.
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.
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:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allsalescolumns. WHERE s.sale_id IS NULLkeeps only theemployeesrows that have no match insales.
Anti-join using LEFT JOIN … IS NULL.
52. Find the average tenure of employees by department.
SELECT department_id,
AVG(DATE_PART('year', CURRENT_DATE - hire_date)) AS avg_tenure_years
FROM employees
GROUP BY department_id;Logic:
- Subtract the hire date from today's date to get the tenure.
DATE_PART('year', ...)converts it to years.AVG()per department gives the average tenure.
Date arithmetic with aggregation.
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:
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.
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:
NTILE(10)splits each department's employees into 10 equal groups, sorted by salary descending.- Group 1 contains the highest-paid 10%.
NTILE() for percentile buckets.
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.
SELECT customer_id, purchase_date, COUNT(*) AS purchase_count
FROM sales
GROUP BY customer_id, purchase_date
HAVING COUNT(*) > 1;Logic:
- Group by customer and date.
COUNT(*)counts the purchases on each date.HAVING COUNT(*) > 1keeps the days with multiple purchases.
Grouping on a customer and date.
55. List all departments and their employee counts, including departments with zero employees.
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:
LEFT JOINkeeps all departments.COUNT(e.id)counts only non-NULLemployee ids, so departments without employees get 0.
Left join with a count.
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.
SELECT column1, column2, COUNT(*)
FROM table_name
GROUP BY column1, column2
HAVING COUNT(*) > 1;Logic:
- Group by the columns that define a duplicate.
HAVING COUNT(*) > 1keeps combinations that appear more than once.
Multi-column duplicate detection.
57. Write a recursive query to calculate factorial of a number (e.g., 5).
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:
- The anchor row is
n = 1, fact = 1. - Each recursion increases
nby 1 and multipliesfactby the newn. WHERE n < 5stops the recursion; the final query reads the row wheren = 5(120).
Recursive CTE for calculations.
58. Write a query to calculate the cumulative percentage of total sales per product.
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:
SUM(sale_amount) OVER (ORDER BY sale_amount DESC)is the running total from the largest amount downward.SUM(sale_amount) OVER ()is the grand total.- Dividing and multiplying by 100 gives the cumulative percentage.
Running share of a total (Pareto analysis).
If sales has many rows per product, aggregate by product first; otherwise the percentages are per row, not per product.
Aggregating per product first:
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).
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:
- The anchor selects the manager's direct reports.
- The recursive part adds the people who report to anyone already found.
- The final query returns the full reporting tree below the manager.
Recursive hierarchy traversal.
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.
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:
- The subquery counts the orders of each customer.
AVG()andSTDDEV()summarize those counts.
Aggregating an aggregate.
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
(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:
LAG(purchase_date)gets each customer's previous purchase date.- If the current date is more than one day after the previous date, there is a gap.
prev_date + 1 dayis the first missing day.
Gap detection with LAG().
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.
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:
RANK()ranks employees by salary within each department.PERCENT_RANK()converts the position to a value between 0 and 1:(rank - 1) / (rows - 1).
RANK() and PERCENT_RANK().
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.
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:
LEFT JOINkeeps every row fromproducts.- Rows without a match have
NULLin allsalescolumns. WHERE s.sale_id IS NULLkeeps only theproductsrows that have no match insales.
Anti-join using LEFT JOIN … IS NULL.
64. Write a query to find consecutive days where sales were above a threshold.
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:
- A
CASEflag marks days with sales above 1000. - Only flagged days are kept and numbered in date order.
- Subtracting the row number from the date gives a constant group value for consecutive days; each group is one run.
Gaps and islands with a threshold.
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).
SELECT department_id, STRING_AGG(name, ', ') AS employee_names
FROM employees
GROUP BY department_id;Logic:
STRING_AGG(name, ', ')joins all names of a group into one comma-separated string.GROUP BY department_idcreates one string per department.
String aggregation.
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.
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:
- The correlated subquery calculates the average salary of the employee's own department.
- The second subquery calculates the company-wide average.
- Both conditions must hold.
Correlated and scalar subqueries together.
67. List the customers who purchased all products in a specific category.
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:
- Keep only sales in category 10.
- Count the distinct products each customer bought.
- Compare with the number of products in that category using
HAVING.
Relational division.
68. Retrieve the Nth highest salary from the employees table.
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET N-1;Logic:
DISTINCT salaryremoves duplicate salaries.ORDER BY salary DESCsorts from highest to lowest.OFFSET N-1skips the firstN-1salaries andLIMIT 1returns the next one.
Nth highest value with LIMIT/OFFSET.
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.
SELECT e.*
FROM employees e
LEFT JOIN salary_history sh ON e.id = sh.employee_id
WHERE sh.employee_id IS NULL;Logic:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allsalary_historycolumns. WHERE sh.employee_id IS NULLkeeps only theemployeesrows that have no match insalary_history.
Anti-join using LEFT JOIN … IS NULL.
70. Show the department with the highest number of employees and the count.
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
ORDER BY employee_count DESC
LIMIT 1;Logic:
- Count employees per department.
ORDER BY employee_count DESCputs the largest first.LIMIT 1returns it.
Top-1 group.
Ties are not returned. Use a RANK() window function to include all tied departments.
71. Write a recursive query to list all ancestors
(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:
- The anchor row is the given employee (id 123).
- Each recursion joins to the employee whose
idequals the current row'smanager_id, moving one level up. - The final query removes the starting employee, leaving only the managers above them.
Recursive CTE walking up a hierarchy.
72. Calculate the median salary by department using window functions.
SELECT DISTINCT department_id,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) OVER (PARTITION BY department_id) AS median_salary
FROM employees;Logic:
PERCENTILE_CONT(0.5)returns the median of the sorted salaries.OVER (PARTITION BY department_id)calculates it for each department.DISTINCTcollapses the repeated row for every employee into one row per department.
Median per group.
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:
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.
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:
LEFT JOINkeeps every customer.MINandMAXof the purchase date are calculated per customer.- Customers without purchases get
NULLfor both dates.
Left join with aggregates.
74. Find the percentage difference between each month’s total sales and the previous month’s total sales.
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:
- The CTE totals sales per month.
LAG(total_sales)retrieves the previous month's total.(current - previous) * 100.0 / previousgives the percentage difference.
Month-over-month growth.
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.
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:
RANK() OVER (PARTITION BY department_id ORDER BY hire_date ASC)ranks employees by hire date within each department.- Rank 1 is the earliest hire.
Ranking within groups.
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.
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:
- The CTE totals sales per month.
- The self join matches each month (
ms1) with the same month one year earlier (ms2):ms1.month = ms2.month + INTERVAL '1 year'. - The growth percentage compares the two totals.
Year-over-year comparison with a self join.
LEFT JOIN keeps months that have no prior-year data; their growth is NULL.
77. Write a query to identify overlapping shifts for employees.
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:
- Join each shift to the other shifts of the same employee.
- Two shifts overlap when each starts before the other ends.
s1.shift_id <> s2.shift_idexcludes comparing a shift with itself.
Interval overlap with a self join.
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.
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:
SUM(amount)is the total revenue per customer.RANK() OVER (ORDER BY SUM(amount) DESC)ranks customers by that total.
Window function applied to an aggregate.
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.
SELECT e.*
FROM employees e
LEFT JOIN promotions p ON e.id = p.employee_id
WHERE p.employee_id IS NULL;Logic:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allpromotionscolumns. WHERE p.employee_id IS NULLkeeps only theemployeesrows that have no match inpromotions.
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.
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:
- The first CTE totals sales per product per month.
- The second CTE ranks products within each month.
- The final query keeps ranks 1 to 3.
Top-N per group using RANK().
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.
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:
- Find customers with at least one order in the last 30 days.
- 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):
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING MIN(order_date) >= CURRENT_DATE - INTERVAL '30 days';Filtering with a subquery.
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.
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:
LEFT JOINkeeps every row fromproducts.- Rows without a match have
NULLin allorderscolumns. WHERE o.order_id IS NULLkeeps only theproductsrows that have no match inorders.
Anti-join using LEFT JOIN … IS NULL.
83. Find employees whose salary is above their department’s average but below the overall average salary.
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:
- The first subquery is correlated: it calculates the average salary of the employee's own department.
- The second subquery calculates the overall average.
- Both conditions must hold.
Correlated subquery.
This is the same pattern as Question 66.
84. Calculate the total sales amount and number of orders per customer in the last year.
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:
- Filter sales from the last year with
WHERE. - Group by customer.
COUNT(*)gives the number of orders andSUM(amount)the total sales.
Filtered aggregation.
85. List the top 5 highest-paid employees per department.
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:
ROW_NUMBER()ranks employees by salary inside each department.rn <= 5keeps the top five.
Top-N per group.
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).
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:
- Number each employee's attendance dates in order.
- Subtracting that row number (as days) from the date gives the same value for consecutive dates.
- Grouping by that value produces the islands, with start date, end date and length.
Gaps and islands technique.
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.
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:
- The anchor selects the manager's direct reports (
manager_id = 100). - Each recursion adds the employees who report to anyone already found.
- The result contains everyone below the manager at all levels.
Recursive CTE walking down a hierarchy.
88. Calculate a 3-month moving average of monthly sales per product.
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:
- The CTE totals sales per product per month.
ROWS BETWEEN 2 PRECEDING AND CURRENT ROWcreates a window of the current and previous two months.AVG(total_sales)averages that window.
Moving average per group.
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.
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:
- Self join each employee to their manager.
- Keep rows where both hire dates are equal.
Self join with an equality comparison.
90. Write a query to find products with increasing sales over the last 3 months.
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:
- The first CTE totals sales per product per month.
- The second CTE numbers months from newest (
rn = 1) to oldest. - Joining the latest three months, the query keeps products where month 3 < month 2 < month 1.
Trend detection with ranked rows.
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.
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:
ROW_NUMBER()numbers salaries from highest to lowest within each department.rn = Nkeeps the Nth row.
Nth value per group.
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.
SELECT manager_id, COUNT(DISTINCT project_id) AS project_count
FROM projects
GROUP BY manager_id
HAVING COUNT(DISTINCT project_id) > 3;Logic:
- Group projects by manager.
COUNT(DISTINCT project_id)counts the unique projects.HAVINGkeeps managers with more than three.
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.
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:
- Self join each employee to their manager.
DATEDIFF(day, m.hire_date, e.hire_date)returns the days from the manager's hire date to the employee's.
Date difference in a self join.
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.
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:
- Subtract the hire date from today to get years of experience.
AVG()per department gives the average.ORDER BY ... DESC LIMIT 1returns the highest.
Aggregation with ORDER BY and LIMIT.
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.
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:
- Join each assignment to other assignments of the same employee.
- Two assignments overlap when each starts before the other ends.
Interval overlap test.
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.
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:
- The first CTE (
months) lists 1 to 12, although the final query does not need it. - The second CTE finds the distinct months in which each customer purchased this year.
- Customers with 12 distinct months qualify.
Relational division with counts.
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.
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:
- The subquery returns the salaries of the employee's direct reports.
salary > ALL (...)is true when the salary is higher than every one of them.
ALL with a correlated subquery.
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.
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:
- Total the sales of each product within its category.
RANK()orders products by total sales inside each category.- Rank 1 is the top product.
Top-1 per group.
Tied products all receive rank 1.
99. Find customers who haven’t ordered in the last 6 months.
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:
LEFT JOINcustomers to their orders.MAX(o.order_date)is each customer's most recent order.- Customers whose latest order is older than six months, or who never ordered, are returned.
Aggregation after a left join.
customer_id exists in both tables, so SELECT customer_id is ambiguous and raises an error. Use c.customer_id.
Corrected version:
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.
SELECT department_id, MAX(salary) - MIN(salary) AS salary_gap
FROM employees
GROUP BY department_id;Logic:
- In each department,
MAX(salary) - MIN(salary)is the largest difference between any two employees.
Range of values per group.
101. Write a recursive query to compute the total budget under each manager (including subordinates).
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:
- The recursion collects every unit that reports, directly or indirectly, to each starting unit.
- Summing the budgets of the collected units gives the total under each manager.
Recursive roll-up of a hierarchy.
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:
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.
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:
- Number the invoices in sorted order (
rn). - For each invoice, compare
invoice_number + 1with the next invoice (rn + 1). - If they differ, the number after the current invoice is missing.
Gap detection with row numbers.
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.
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:
ROW_NUMBER()numbers employees by salary within each department.((rn - 1) / 10) + 1converts the position into a block number (1 for rows 1–10, 2 for rows 11–20, and so on).
Bucketing rows with integer division.
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.
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:
- The CTE totals sales per product per day.
- The median is calculated over a 7-row window.
- The result is one moving median per product and day.
Moving statistics.
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:
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.
SELECT customer_id
FROM sales
WHERE product_id IN ('A', 'B')
GROUP BY customer_id
HAVING COUNT(DISTINCT product_id) = 2;Logic:
- Keep only sales of products A and B.
- Group by customer and count the distinct products.
- A count of 2 means the customer bought both.
Relational division with COUNT(DISTINCT).
106. Write a query to generate a calendar table with all dates for the current year.
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:
generate_series(start, end, step)produces one row per day.- The start is the first day of the current year and the end is the last day (one year later minus one day).
Date generation.
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.
SELECT employee_id
FROM employee_department_history
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id) > 3;Logic:
- Group the department history by employee.
- Count the distinct departments.
- Keep employees with more than three.
Distinct count in HAVING.
108. Calculate the percentage contribution of each product’s sales to the total sales per month.
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:
- The first CTE totals each product's sales per month.
- The second CTE totals all sales per month.
- Joining them,
product_sales * 100.0 / total_salesis each product's share of the month.
Share of total using CTEs.
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.
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:
- Each
CASEreturns the sale amount for one month and 0 for all others. SUM()adds up the amounts for that month.GROUP BY product_idreturns one row per product with one column per month.
Pivot with conditional aggregation.
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.
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:
- Number each customer's orders from newest to oldest.
- Keep rows where the number is 3 or less.
Top-N per group.
111. Find employees who have never taken any leave.
SELECT e.*
FROM employees e
LEFT JOIN leaves l ON e.id = l.employee_id
WHERE l.leave_id IS NULL;Logic:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allleavescolumns. WHERE l.leave_id IS NULLkeeps only theemployeesrows that have no match inleaves.
Anti-join using LEFT JOIN … IS NULL.
112. List customers who placed orders in January but not in February.
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:
- The first CTE lists customers who ordered in January.
- The second CTE lists customers who ordered in February.
- The final query keeps January customers who are not in the February list.
Set difference with NOT IN.
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.
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:
LAG(price)returns the previous price of the same product.- Rows where the current price is higher than the previous price are price increases.
DISTINCTreturns each product once.
Change detection with LAG().
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.
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:
- The first CTE calculates each department's average salary.
DENSE_RANK()ranks those averages from highest to lowest.- Rank 2 is the second-highest average.
Nth value using DENSE_RANK().
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.
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:
- Self join employees on equal hire month and hire year.
e1.id <> e2.idavoids pairing an employee with themselves.
Self join on derived date parts.
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).
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:
- The anchor selects the CEO (no manager) at level 1.
- Each recursion adds employees who report to the previous level with
level + 1. - The final query shows every employee with their distance from the CEO.
Recursive CTE with a level counter.
117. Find the second highest salary per department without using window functions.
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:
- The correlated subquery finds each department's highest salary.
salary <that value removes the top earners.MAX(salary)of the remaining rows is the second highest.
Second highest per group using subqueries.
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.
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:
- The CTE totals sales per product per month.
LAG()retrieves the previous month for the same product.- The percentage change is
(current - previous) * 100.0 / previous.
Month-over-month change per product.
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.
SELECT *, COUNT(*) OVER (PARTITION BY col1, col2, col3, ...) AS cnt
FROM table_name
WHERE cnt > 1;Logic:
COUNT(*) OVER (PARTITION BY ...)counts how many rows share the same column values.- Rows whose count is above 1 are duplicates.
Duplicate detection with a window function.
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):
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.
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:
- Each
SELECTtakes one quarter column and turns it into a row with a quarter label. UNION ALLstacks the four result sets into one.
Unpivot with UNION ALL.
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.
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:
- The first subquery is correlated and returns the employee's department average.
- The second returns the company-wide average.
- Both conditions must be true.
Correlated subquery.
This is the same pattern as Questions 66 and 83.
122. Write a query to find customers with the highest purchase amount per year.
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:
- The first CTE totals each customer's purchases per year.
RANK()orders customers by total within each year.- Rank 1 is the top customer for that year.
Top-1 per group.
123. Write a query to list all employees who have a salary equal to the average salary of their department.
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:
- The derived table calculates each department's average salary.
- Joining on department and
salary = avg_salaryreturns employees who earn exactly that average.
Join to an aggregated subquery.
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.
SELECT customer_id, MIN(order_date) AS first_order_date
FROM orders
GROUP BY customer_id;Logic:
GROUP BY customer_idcreates one group per customer.MIN(order_date)is the first order.
MIN aggregate.
125. Find employees who have been promoted more than twice.
SELECT employee_id, COUNT(*) AS promotion_count
FROM promotions
GROUP BY employee_id
HAVING COUNT(*) > 2;Logic:
- Group promotions by employee.
COUNT(*)counts promotions.HAVING COUNT(*) > 2keeps employees with at least three.
Counting rows per group.
126. Find employees who have not been assigned to any project.
SELECT e.*
FROM employees e
LEFT JOIN project_assignments pa ON e.id = pa.employee_id
WHERE pa.project_id IS NULL;Logic:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allproject_assignmentscolumns. WHERE pa.project_id IS NULLkeeps only theemployeesrows that have no match inproject_assignments.
Anti-join using LEFT JOIN … IS NULL.
127. Find the total sales per customer including those with zero sales.
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:
LEFT JOINkeeps every customer.SUM(s.amount)isNULLfor customers without sales.COALESCE(..., 0)converts it to 0.
Left join with COALESCE.
128. Find the highest salary by department and the employee(s) who earn it.
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:
- The CTE finds each department's maximum salary.
- Joining back to
employeeson department and salary returns the employee(s) who earn it.
Join back to a group maximum.
All employees tied for the highest salary are returned.
129. Find customers with no orders in the last year.
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:
LEFT JOINorders, but only those from the last year (condition inON).- Customers without such orders have
NULLorder columns. WHERE o.order_id IS NULLreturns them.
Anti-join with a date filter.
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.
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:
- The CTE finds each department's maximum salary.
salary >= 0.9 * max_salarykeeps employees earning at least 90% of it.
Threshold relative to a group maximum.
131. Find the running total of sales by date.
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:
ORDER BY sale_dateorders the rows.ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWadds all rows from the beginning up to the current row.
Running total with an explicit frame.
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.
SELECT *
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);Logic:
- The subquery calculates the company average.
- The outer query keeps salaries above it.
Scalar subquery.
133. Get the last 3 orders placed by each customer.
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:
- Number each customer's orders from newest to oldest.
- Keep the first three.
Top-N per group.
134. Find the difference in days between the earliest and latest orders per customer.
SELECT customer_id, MAX(order_date) - MIN(order_date) AS days_between
FROM orders
GROUP BY customer_id;Logic:
MAX(order_date) - MIN(order_date)is the number of days between a customer's first and last order.
Date arithmetic with aggregates.
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.
SELECT employee_id
FROM project_assignments
GROUP BY employee_id
HAVING COUNT(DISTINCT project_id) = (SELECT COUNT(*) FROM projects);Logic:
- Count the distinct projects each employee worked on.
- Compare with the total number of projects.
- Equal counts mean the employee worked on every project.
Relational division.
136. Find customers who placed orders only in the last 6 months.
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING MIN(order_date) >= CURRENT_DATE - INTERVAL '6 months';Logic:
MIN(order_date)is a customer's oldest order.- If the oldest order is within the last six months, every order is.
Condition on MIN() in HAVING.
137. Get the total number of orders per day, including days with zero orders.
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:
- The CTE generates every date between the first and last order.
LEFT JOINorders to the dates.COUNT(o.order_id)returns 0 for days without orders.
Filling missing dates with generate_series.
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.
SELECT department_id, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id
ORDER BY employee_count DESC
LIMIT 1;Logic:
- Count employees per department.
- Sort by the count in descending order.
LIMIT 1returns the largest department.
Top-1 group.
139. Write a query to find gaps in employee IDs.
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:
- Look at each ID and the next ID in order (
LEAD). - A gap exists when the next ID is more than 1 higher.
- The missing range runs from
id + 1tonext_id - 1.
Gap detection.
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:
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.
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:
- Self join each employee to their manager.
e.hire_date < m.hire_datekeeps employees who joined before their manager.
Self join with a date comparison.
SQL Interview Questions 141–165 — Advanced Level
141. List departments with average salary greater than the overall average.
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
HAVING AVG(salary) > (SELECT AVG(salary)
FROM employees);Logic:
GROUP BY department_idgives each department's average salary.- The scalar subquery calculates the overall average.
HAVINGkeeps departments above it.
Group filter with a subquery.
142. Find employees with the highest number of dependents.
SELECT employee_id, COUNT(*) AS dependent_count
FROM dependents
GROUP BY employee_id
ORDER BY dependent_count DESC
LIMIT 1;Logic:
- Count dependents per employee.
- Sort by the count descending and return the first row.
Top-1 group.
Ties are not returned. Use RANK() to include all tied employees.
143. Find customers with the longest gap between two consecutive orders.
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:
LAG(order_date)finds each customer's previous order date.- The difference between the two dates is the gap.
MAX(gap_days)per customer is the longest gap.
Gap analysis with LAG().
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.
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:
- Keep sales of products in category 1.
- Count the distinct products each customer bought.
- Compare with the number of products in the category.
Relational division.
This is the same pattern as Question 67.
145. Get the most recent order date per customer.
SELECT customer_id, MAX(order_date) AS last_order_date
FROM orders
GROUP BY customer_id;Logic:
MAX(order_date)per customer is the latest order.
MAX aggregate.
146. List all employees and their manager names.
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;Logic:
LEFT JOINemployees to themselves onmanager_id = id.- Employees without a manager are kept with
NULLfor the manager name.
Self left join.
147. Find employees with the same salary as their manager.
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:
- Self join each employee to their manager.
- Keep rows with equal salaries.
Self join with an equality comparison.
148. List products with sales above the average sales amount.
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:
- The CTE calculates the average amount of an individual sale.
- Group sales by product and total them.
HAVINGkeeps products whose total exceeds that average.
Group filter with a CTE.
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.
SELECT EXTRACT(YEAR FROM hire_date) AS hire_year, COUNT(*) AS count
FROM employees
GROUP BY hire_year
ORDER BY hire_year;Logic:
EXTRACT(YEAR FROM hire_date)gets the hire year.- Grouping by year and counting gives hires per year.
Date part grouping.
150. Find the number of employees with the same job title per department.
SELECT department_id, job_title, COUNT(*) AS employee_count
FROM employees
GROUP BY department_id, job_title;Logic:
- Group by department and job title.
COUNT(*)is the number of employees in each pair.
Multi-column grouping.
151. Find employees with no manager assigned.
SELECT *
FROM employees
WHERE manager_id IS NULL;Logic:
manager_id IS NULLfinds employees without a manager.
NULL handling.
152. Calculate average salary by department and job title.
SELECT department_id, job_title, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id, job_title;Logic:
- Grouping by department and title gives one row per combination.
AVG(salary)is the average for that group.
Multi-column grouping.
153. Find the median salary of employees.
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees;Logic:
PERCENTILE_CONT(0.5)returns the middle value of the sorted salaries, averaging the two middle values when the count is even.
Median using an ordered-set aggregate.
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.
SELECT employee_id, COUNT(*) AS promotion_count
FROM promotions
GROUP BY employee_id
HAVING COUNT(*) > 1;Logic:
- Group promotions by employee.
HAVING COUNT(*) > 1keeps employees promoted at least twice.
Counting rows per group.
155. Calculate total sales by product category.
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:
- Join sales to products to get each sale's category.
- Group by category and
SUM(amount).
Join plus aggregation.
156. Find the top 3 products by sales amount.
SELECT product_id, SUM(amount) AS total_sales
FROM sales
GROUP BY product_id
ORDER BY total_sales DESC
LIMIT 3;Logic:
- Total sales per product.
- Sort descending and keep the first three rows.
Top-N with LIMIT.
Tied products at third place may be cut off. Use RANK() to include ties.
157. Get employees who joined after their department was created.
SELECT e.*
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE e.hire_date > d.creation_date;Logic:
- Join employees to their department.
hire_date > creation_datekeeps employees hired after the department's creation date.
Join with a date comparison.
158. Find customers with no sales records.
SELECT c.*
FROM customers c
LEFT JOIN sales s ON c.customer_id = s.customer_id
WHERE s.sale_id IS NULL;Logic:
LEFT JOINkeeps every row fromcustomers.- Rows without a match have
NULLin allsalescolumns. WHERE s.sale_id IS NULLkeeps only thecustomersrows that have no match insales.
Anti-join using LEFT JOIN … IS NULL.
159. Find the second highest salary in the company.
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);Logic:
- The subquery finds the highest salary.
MAX(salary)among salaries below it is the second highest.
Subquery with MAX.
Same pattern as Question 1.
160. Find products with sales only in the current month.
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:
MIN(sale_date)andMAX(sale_date)are each product's first and last sales.- If the first sale is in the current month, all sales are in the current month or later.
Date boundaries in HAVING.
Add an upper bound (< DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month') if future-dated sales are possible.
161. Find employees with consecutive workdays.
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:
- Number each employee's work dates in order.
- Subtract that number of days from the date; consecutive dates then share the same
grp. COUNT(*)per group is the length of the streak.
Gaps and islands technique.
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.
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:
- The subquery counts orders per customer.
AVG()of those counts is the average.
Aggregate over an aggregate.
163. Find employees who have worked on more than 5 projects.
SELECT employee_id, COUNT(DISTINCT project_id) AS project_count
FROM project_assignments
GROUP BY employee_id
HAVING COUNT(DISTINCT project_id) > 5;Logic:
COUNT(DISTINCT project_id)per employee.HAVINGkeeps counts above 5.
Distinct count in HAVING.
164. Find the total number of products sold each day.
SELECT sale_date, SUM(quantity) AS total_quantity_sold
FROM sales
GROUP BY sale_date
ORDER BY sale_date;Logic:
- Group sales by date.
SUM(quantity)is the number of items sold that day.
Daily totals.
165. Find customers with orders totaling more than $10,000.
SELECT customer_id, SUM(amount) AS total_amount
FROM sales
GROUP BY customer_id
HAVING SUM(amount) > 10000;Logic:
- Group by customer.
SUM(amount)is each customer's total.HAVINGkeeps totals above 10,000.
HAVING with SUM.
SQL Interview Questions 166–200 — Medium to Advanced
166. Find employees who have never received a bonus.
SELECT e.*
FROM employees e
LEFT JOIN bonuses b ON e.id = b.employee_id
WHERE b.bonus_id IS NULL;Logic:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allbonusescolumns. WHERE b.bonus_id IS NULLkeeps only theemployeesrows that have no match inbonuses.
Anti-join using LEFT JOIN … IS NULL.
167. Find the department with the lowest average salary.
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
ORDER BY avg_salary
LIMIT 1;Logic:
- Average salary per department.
- Sort ascending and return the first row.
Top-1 group.
Same pattern as Question 39.
168. Get cumulative count of orders per customer over time.
SELECT customer_id, order_date, COUNT(*) OVER (PARTITION BY customer_id
ORDER BY order_date) AS cumulative_orders
FROM orders;Logic:
PARTITION BY customer_idhandles each customer separately.COUNT(*) OVER (... ORDER BY order_date)counts orders from the first one up to the current row.
Running count.
169. Find customers who ordered products only from one category.
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:
- Join sales to products to find each sale's category.
- Count the distinct categories per customer.
- Keep customers with exactly one.
Distinct count in HAVING.
170. Write a query to display employee names alongside their manager names, including those without managers.
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:
LEFT JOINthe table to itself.- Employees without a manager show
NULLas the manager name.
Self left join.
Same as Question 146.
171. Find products with sales increasing every month for the last 3 months.
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:
- Total sales per product per month for the last 3 months.
LAG(total_sales, 1)andLAG(total_sales, 2)bring the previous two months into the current row.- Keep products where each month is higher than the one before it.
Strictly increasing trend with LAG().
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:
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.
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:
- The anchor row is the manager (
:manager_idis a parameter). - Each recursion adds employees who report to anyone already found.
- The final query removes the manager.
Recursive CTE with a parameter.
173. Find the department with the highest variance in salaries.
SELECT department_id, VAR_SAMP(salary) AS salary_variance
FROM employees
GROUP BY department_id
ORDER BY salary_variance DESC
LIMIT 1;Logic:
VAR_SAMP(salary)is the sample variance of each department's salaries.- Sort descending and return the first.
Statistical aggregate.
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.
SELECT customer_id, order_date, amount,
amount - LAG(amount) OVER (PARTITION BY customer_id ORDER BY order_date) AS diff
FROM orders;Logic:
LAG(amount)returns the customer's previous order amount.- Subtract it from the current amount.
LAG() per customer.
175. Find customers who purchased both Product A and Product B.
SELECT customer_id
FROM sales
WHERE product_id IN ('A', 'B')
GROUP BY customer_id
HAVING COUNT(DISTINCT product_id) = 2;Logic:
- Keep sales of A and B.
- Count the distinct products per customer.
- Count 2 means both were bought.
Relational division.
Same pattern as Question 105.
176. Find the top N customers by total sales amount.
SELECT customer_id, SUM(amount) AS total_sales
FROM sales
GROUP BY customer_id
ORDER BY total_sales DESC
LIMIT N;Logic:
- Total sales per customer.
- Sort descending and
LIMIT N.
Top-N with LIMIT.
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.
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:
- Keep sales of the current year.
- Total by month.
- Sort descending and return the first month.
Top-1 month.
178. Write a query to display all employees who have worked on a project longer than 6 months.
SELECT employee_id
FROM project_assignments
WHERE end_date - start_date > INTERVAL '6 months';Logic:
- The condition compares the project's duration with a 6-month interval.
DISTINCTis needed to list each employee once.
Duration filter.
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:
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).
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
OFFSET n - 1 ROWS FETCH NEXT 1 ROW ONLY;Logic:
DISTINCT salaryremoves duplicate salaries.- Sort descending, skip the first
n - 1values and fetch one row.
OFFSET/FETCH for the Nth value.
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.
SELECT EXTRACT(YEAR FROM hire_date) AS year, AVG(salary) AS avg_salary
FROM employees
GROUP BY year
ORDER BY year;Logic:
- Group by hire year.
AVG(salary)per year.
Group by a date part.
181. Find employees whose salaries are between the 25th and 75th percentile.
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:
- The CTE calculates the 25th and 75th percentile salaries.
- The main query keeps salaries between them (the interquartile range).
Percentile filtering.
182. Find employees with salaries higher than their department average.
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:
- The derived table calculates each department's average.
- Join it to employees and keep those above their department average.
Join to an aggregated subquery.
183. Find the difference between each row's value and the previous row’s value in sales.
SELECT sale_date, amount, amount - LAG(amount) OVER (ORDER BY sale_date) AS diff
FROM sales;Logic:
LAG(amount)gives the previous row's amount in date order.- Subtract it from the current amount.
LAG() window function.
184. List employees who have been in the company for more than 10 years.
SELECT *
FROM employees
WHERE CURRENT_DATE - hire_date > INTERVAL '10 years';Logic:
- The condition keeps employees whose service time is over 10 years.
Date filter.
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:
SELECT *
FROM employees
WHERE hire_date < CURRENT_DATE - INTERVAL '10 years';185. Find the department with the most promotions.
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:
- Join promotions to employees to find each promotion's department.
- Count promotions per department.
- Return the highest.
Join, group and top-1.
186. Find customers who ordered products from at least 3 different categories.
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:
- Join sales to products to get the category.
- Count distinct categories per customer.
HAVING >= 3keeps those with three or more.
Distinct count in HAVING.
187. Find the average gap (in days) between orders per customer.
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:
LAG(order_date)finds the previous order date for each customer.- The difference is the gap between two orders.
AVG(gap)per customer is the average gap.
Gap analysis with LAG().
The first order of each customer has no previous order, so it is excluded.
188. List all customers who have never ordered product X.
SELECT customer_id
FROM customers
WHERE customer_id NOT IN (
SELECT DISTINCT customer_id
FROM sales
WHERE product_id = 'X'
);Logic:
- The subquery lists customers who ordered product X.
NOT INreturns the customers not in that list.
Alternative using NOT EXISTS:
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'
);Exclusion with a subquery.
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.
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:
- Join customers to their orders.
- Group by country.
COUNT(o.order_id)andSUM(o.amount)summarize each country.
Join with aggregation.
190. Find the employees who were hired on the same day as their managers.
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:
- Self join employees to their managers.
- Keep rows where the hire dates are equal.
Self join.
Same as Question 89.
191. Find the top 3 products by quantity sold in each category.
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:
- The inner query totals quantity per product and category.
ROW_NUMBER()ranks products within each category by that total.rn <= 3keeps the top three.
Top-N per group over an aggregate.
192. Find the difference in days between the first and last order for each customer.
SELECT customer_id, MAX(order_date) - MIN(order_date) AS days_between
FROM orders
GROUP BY customer_id;Logic:
MAX(order_date) - MIN(order_date)is the span between the first and last order.
Date difference with aggregates.
Same as Question 134.
193. Find customers who have increased their order volume every month for the last 3 months.
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:
- The CTE counts orders per customer per month for the last 3 months.
MIN(orders_count) < MAX(orders_count)only proves the counts are not all equal; it does not prove an increase every month.
Trend detection.
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:
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.
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:
- The derived table calculates the average salary per job title.
- Join on job title and keep employees whose salary equals it.
Join to an aggregated subquery.
195. Write a query to calculate the difference in salary between employees and their managers.
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:
- Self join each employee to their manager.
e.salary - m.salaryis the difference (negative when the employee earns less).
Self join with arithmetic.
196. List the departments with no employees.
SELECT d.*
FROM departments d
LEFT JOIN employees e ON d.department_id = e.department_id
WHERE e.id IS NULL;Logic:
LEFT JOINkeeps every row fromdepartments.- Rows without a match have
NULLin allemployeescolumns. WHERE e.id IS NULLkeeps only thedepartmentsrows that have no match inemployees.
Anti-join using LEFT JOIN … IS NULL.
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.
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:
- The CTE calculates the maximum salary per department.
- Join back to employees to find who earns it.
Join back to a group maximum.
Same as Question 128; ties are all returned.
198. Find customers with orders on every day in the last week.
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:
- The CTE generates the last 7 dates.
- Join orders to those dates.
COUNT(DISTINCT order_date) = 7keeps customers with an order on each day.
Relational division over dates.
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.
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:
MAX(quantity)per product is the largest quantity in one sale.- Sort descending and return the first product.
Top-1 with MAX.
200. Find employees who joined before their department was created.
SELECT e.*
FROM employees e
JOIN departments d ON e.department_id = d.department_id
WHERE e.hire_date < d.creation_date;Logic:
- Join employees to their department.
hire_date < creation_datefinds the unusual (inconsistent) cases.
Join with a date comparison.
SQL Interview Questions 201–235 — Medium to Advanced
201. Find customers with sales in at least 3 different years.
SELECT customer_id
FROM sales
GROUP BY customer_id
HAVING COUNT(DISTINCT EXTRACT(YEAR
FROM sale_date)) >= 3;Logic:
- Extract the year from each sale.
- Count distinct years per customer.
- Keep customers with three or more.
Distinct count of a date part.
202. Find employees whose salary is above the company’s average but below their department’s average.
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:
- The first CTE is the company average and the second is each department's average.
- Join employees to both averages.
- Keep employees above the company average and below their department average.
Combining company and department averages.
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:
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.
SELECT customer_id, EXTRACT(YEAR FROM order_date) AS year,
AVG(amount) AS avg_order_amount
FROM orders
GROUP BY customer_id, year;Logic:
- Group by customer and order year.
AVG(amount)for each group.
Multi-column grouping.
204. Find employees who have worked on at least one project with a budget over $1,000,000.
SELECT DISTINCT pa.employee_id
FROM project_assignments pa
JOIN projects p ON pa.project_id = p.project_id
WHERE p.budget > 1000000;Logic:
- Join assignments to projects.
- Keep projects over the budget.
DISTINCTreturns each employee once.
Join with a filter.
205. Find the most recent promotion date per employee.
SELECT employee_id, MAX(promotion_date) AS last_promotion_date
FROM promotions
GROUP BY employee_id;Logic:
MAX(promotion_date)per employee.
MAX aggregate.
206. Find customers who made orders totaling more than the average order amount.
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:
- The CTE calculates the average amount of a single order.
- Group orders by customer and total them.
- Keep customers whose total exceeds the average.
Group filter with a CTE.
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.
SELECT product_id
FROM products
WHERE product_id NOT IN (SELECT DISTINCT product_id FROM sales);Logic:
- The subquery lists product ids that appear in
sales. NOT INkeeps products not in that list.
Exclusion with a subquery.
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.
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:
- Keep sales from the last year.
- Total by month.
- Sort ascending and return the first.
Top-1 month.
209. Calculate the number of employees hired each month in the last year.
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:
- Keep employees hired in the last year.
- Group by month and count.
Monthly counts.
210. Find the department with the highest number of projects.
SELECT department_id, COUNT(*) AS project_count
FROM projects
GROUP BY department_id
ORDER BY project_count DESC
LIMIT 1;Logic:
- Count projects per department.
- Return the department with the highest count.
Top-1 group.
211. Find employees who do not have dependents.
SELECT e.*
FROM employees e
LEFT JOIN dependents d ON e.id = d.employee_id
WHERE d.dependent_id IS NULL;Logic:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin alldependentscolumns. WHERE d.dependent_id IS NULLkeeps only theemployeesrows that have no match independents.
Anti-join using LEFT JOIN … IS NULL.
212. Get the total sales amount for each product category including categories with zero sales.
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:
LEFT JOINcategories to products, then products to sales, so every category is kept.SUM(s.amount)isNULLfor categories without sales.COALESCE(..., 0)replacesNULLwith 0.
Chained left joins with COALESCE.
213. Find employees who have been promoted but their salary didn’t increase.
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:
- Join employees to their promotions.
- The subquery fetches the salary recorded before the latest promotion.
- The current salary being less than or equal to it means no increase.
Correlated subquery for the latest record.
The query assumes a promotion_history table with salary_before and promotion_date.
214. Find customers with average order amount above $500.
SELECT customer_id, AVG(amount) AS avg_order_amount
FROM orders
GROUP BY customer_id
HAVING AVG(amount) > 500;Logic:
- Group by customer.
AVG(amount)is the customer's average order.HAVING AVG(amount) > 500keeps those above 500.
HAVING with AVG.
215. Find orders where the total quantity exceeds 100 units.
SELECT order_id, SUM(quantity) AS total_quantity
FROM order_items
GROUP BY order_id
HAVING SUM(quantity) > 100;Logic:
- Group order items by order.
SUM(quantity)is the total units per order.HAVINGkeeps totals above 100.
HAVING with SUM.
216. Find products whose sales have doubled compared to the previous month.
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:
- The first CTE totals sales per product per month.
LAG()brings the previous month's total into the row.total_sales >= 2 * prev_month_saleskeeps months where sales at least doubled.
Growth threshold with LAG().
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.
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:
- Keep assignments dated in 2023.
- Count distinct projects per employee.
- Keep counts above 3.
Date filter with a distinct count.
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.
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:
MAX(order_date)is each customer's last order.HAVINGkeeps those older than one year.
Condition on MAX() in HAVING.
219. Find the average salary increase percentage per department.
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:
- The percentage increase is
(current salary - old salary) / old salary * 100. - Join employees to their promotions to get the old salary.
AVG()per department summarizes the increases.
Aggregating a calculated percentage.
If an employee has several promotions, each one is counted as a separate row.
220. Find employees who have never been promoted.
SELECT *
FROM employees
WHERE id NOT IN (SELECT DISTINCT employee_id FROM promotions);Logic:
- The subquery lists employees who have been promoted.
NOT INreturns the others.
Exclusion with a subquery.
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.
SELECT product_id
FROM sales
GROUP BY product_id
HAVING COUNT(DISTINCT customer_id) = (SELECT COUNT(*) FROM customers);Logic:
- Count the distinct customers who ordered each product.
- Compare with the total number of customers.
- Equal counts mean every customer ordered the product.
Relational division.
222. Find customers with orders totaling more than $5000 in the last 6 months.
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:
- Keep orders from the last six months.
- Total per customer.
HAVINGkeeps totals above 5000.
Filter, group and HAVING.
223. Find the rank of employees based on salary within their department.
SELECT *,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS salary_rank
FROM employees;Logic:
PARTITION BY department_idranks inside each department.ORDER BY salary DESCgives rank 1 to the highest salary.
RANK() per group.
224. Find customers who purchased a product but never reordered it.
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:
- Count how many times each customer bought each product.
- A count of exactly 1 means the product was bought once and never reordered.
Counting repeat purchases.
225. Find the day with the highest number of new hires.
SELECT hire_date, COUNT(*) AS hires
FROM employees
GROUP BY hire_date
ORDER BY hires DESC
LIMIT 1;Logic:
- Group employees by hire date.
- Count per day, sort descending and return the first.
Top-1 day.
Ties are not returned.
226. Find the number of employees who have worked in more than one department.
SELECT employee_id
FROM employee_department_history
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id) > 1;Logic:
- Group the history by employee.
- Count distinct departments.
- Keep counts above 1.
Distinct count in HAVING.
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.
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:
- Keep sales from 2023.
SUM(quantity)per customer.- Sort descending and return the first.
Top-1 with a filter.
Ties are not returned.
228. Find the average days taken to ship orders per shipping method.
SELECT shipping_method, AVG(shipping_date - order_date) AS avg_shipping_days
FROM orders
GROUP BY shipping_method;Logic:
shipping_date - order_dateis the number of days between order and shipping.AVG()per shipping method.
Date difference with AVG.
For DATE columns PostgreSQL returns an integer number of days.
229. Find employees with overlapping project assignments.
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:
- Join each assignment to others of the same employee.
- Ranges overlap when each starts on or before the other ends.
Interval overlap test.
Same logic as Question 95. Each pair is returned twice.
230. Find the total number of unique customers per product category.
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:
- Join sales to products for the category.
COUNT(DISTINCT customer_id)per category.
Distinct count per group.
231. Find customers whose orders increased by at least 20% compared to the previous month.
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:
- The first CTE counts orders per customer per month.
LAG()retrieves the previous month's count.order_count >= 1.2 * prev_order_countkeeps months with at least a 20% increase.
Growth threshold with LAG().
232. Find employees with no projects assigned in the last 6 months.
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:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allproject_assignmentscolumns. WHERE pa.project_id IS NULLkeeps only theemployeesrows that have no match inproject_assignments.
Anti-join with a date condition in ON.
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.
SELECT employee_id
FROM employee_department_history
GROUP BY employee_id
HAVING COUNT(DISTINCT department_id) > 2;Logic:
- Group the department history by employee.
- Count distinct departments.
- Keep employees with more than two.
Distinct count in HAVING.
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.
SELECT product_id, AVG(rating) AS avg_rating
FROM product_reviews
GROUP BY product_id
ORDER BY avg_rating DESC
LIMIT 1;Logic:
AVG(rating)per product.- Sort descending and return the first.
Top-1 average.
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.
SELECT DISTINCT customer_id
FROM orders
WHERE discount_used = FALSE;Logic:
- The goal is customers whose orders all have
discount_used = FALSE. - Group by customer and count orders where a discount was used.
- Keep customers whose count is 0.
Group-level condition.
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:
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.
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:
- Join each employee to all projects of their department.
LEFT JOINthe employee's assignments to those projects.- If the number of department projects equals the number of matched assignments, the employee worked on all of them.
Relational division per group.
237. Find the average order amount excluding the top 5% largest orders.
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:
NTILE(100)splits orders into 100 buckets from the largest amount down.- Buckets 1 to 5 are the top 5%.
AVG(amount)of the remaining buckets is the trimmed average.
Trimmed mean with NTILE.
238. Find the top 3 employees with the highest salary increase over last year.
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:
- The first CTE selects last year's salary and the second selects this year's.
- Join them on
employee_idand subtract. - Sort by the increase and keep three rows.
Year-over-year difference.
239. Find employees with the longest consecutive workdays.
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:
- Remove duplicate dates, then number each employee's dates in order.
- Subtract the row number (as days) from the date to get a group value shared by consecutive days.
COUNT(*)per group is the streak length;MAXper employee is the longest.
Gaps and islands technique.
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):
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.
SELECT DISTINCT manager_id
FROM employees
WHERE manager_id NOT IN (SELECT DISTINCT id
FROM employees);Logic:
- The subquery lists all employee ids.
manager_id NOT IN (...)findsmanager_idvalues that do not match any employee.
Orphaned references.
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:
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.
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:
- Extract year and month from
hire_date. - Group by both so months from different years stay separate.
AVG(salary)per month.
Grouping by date parts.
242. Find the first 5 orders after a customer's registration date.
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:
- Join orders to customers and keep orders on or after registration.
ROW_NUMBER()numbers each customer's orders by date.rn <= 5keeps the first five.
Top-N per group with a join.
customer_id and order_date could be ambiguous in the inner query. Qualify them with table aliases.
Corrected version:
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.
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:
- The first CTE generates the last six months.
- The second CTE lists the distinct months in which each customer ordered.
- Joining and counting distinct months equal to 6 keeps customers with an order in every month.
Relational division over months.
244. Calculate the moving average of sales over the last 3 days.
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:
PARTITION BY product_idkeeps products separate.ROWS BETWEEN 2 PRECEDING AND CURRENT ROWcreates a 3-row window.AVG(amount)is the moving average.
Moving average.
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.
SELECT birth_date, COUNT(*) AS count_employees
FROM employees
GROUP BY birth_date
HAVING COUNT(*) > 1;Logic:
- Group employees by
birth_date. HAVING COUNT(*) > 1keeps dates shared by several employees.
Grouping and HAVING.
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:
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.
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:
- Group by customer, product and date.
HAVING COUNT(*) > 1finds repeated purchases.
Duplicate detection.
247. Find the total sales for each product including products with zero sales.
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:
LEFT JOINkeeps every product.COALESCE(SUM(...), 0)turnsNULLtotals into 0.
Left join with COALESCE.
248. List the top 5 employees by number of projects in each department.
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:
- The inner query counts distinct projects per employee.
ROW_NUMBER()ranks employees inside each department by that count.rn <= 5keeps the top five.
Top-N per group over an aggregate.
249. Find the day with the largest difference between maximum and minimum temperature.
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:
- Group readings by day.
MAX - MINis the daily temperature range.- Sort descending and return the first day.
Range per group.
250. Find the 3 most recent orders per customer.
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:
ROW_NUMBER()numbers each customer's orders from newest to oldest.rn <= 3keeps three.
Top-N per group.
251. Find products with sales only in a specific country.
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:
- Join sales to customers to find each sale's country.
- Count the distinct countries per product.
- A count of 1 means the product was sold in only one country.
Distinct count in HAVING.
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.
SELECT *
FROM employees
WHERE salary > ALL (
SELECT salary FROM employees WHERE department_id = 10
);Logic:
- The subquery returns every salary in department 10.
> ALLkeeps employees earning more than the highest of them.
ALL operator.
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.
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:
- Count employees per department.
- Divide by the total count and multiply by 100.
Alternative using a window function:
SELECT department_id,
COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () AS percentage
FROM employees
GROUP BY department_id;Percentage of total.
254. Find the median salary per department.
SELECT department_id,
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) AS median_salary
FROM employees
GROUP BY department_id;Logic:
PERCENTILE_CONT(0.5)is the median of each group's sorted salaries.GROUP BY department_idcalculates it per department.
Median per group.
255. Find the employee who worked the most hours in a project.
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:
- Group by employee and project.
MAX(hours_worked)is the largest hours value per pair.- Sort descending and return the first.
Top-1 with MAX.
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.
SELECT customer_id, MIN(order_date) AS first_order_date
FROM orders
GROUP BY customer_id;Logic:
MIN(order_date)per customer.
MIN aggregate.
Same as Question 124.
257. Find the second most expensive product per category.
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:
ROW_NUMBER()ranks products by price within each category.rn = 2selects the second.
Nth value per group.
If prices can tie, use DENSE_RANK() to get the second distinct price.
258. Find employees with the highest salary in each job title.
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:
- The CTE finds the maximum salary per job title.
- Join back to employees to list who earns it.
Join back to a group maximum.
259. Calculate the ratio of males to females in each department.
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:
- Count males and females in each department with conditional sums.
- Divide males by females.
NULLIF(..., 0)prevents division by zero when a department has no females.
Ratio with safe division.
260. Find customers who spent more than average in their country.
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:
- The intended comparison is each customer's total spend against the average total spend in their country.
- First total each customer's spend, then compute the country average with a window function.
- Keep customers above it.
Comparison with a partition average.
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:
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.
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:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allproject_assignmentscolumns. WHERE pa.project_id IS NULLkeeps only theemployeesrows that have no match inproject_assignments.
Anti-join with a date condition in ON.
Keep the date condition in the ON clause, not in WHERE.
262. Find the top 3 customers by total order amount in each region.
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:
- The inner query totals orders per customer within each region.
ROW_NUMBER()ranks customers by total inside each region.rn <= 3keeps three per region.
Top-N per group over an aggregate.
263. Find employees hired after their managers.
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:
- Self join each employee to their manager.
e.hire_date > m.hire_datekeeps employees hired later than the manager.
Self join with a date comparison.
264. Find customers who ordered all products from a specific category.
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:
- The first CTE lists products of the category.
- The second CTE lists distinct products each customer bought from them.
- Customers whose count equals the number of category products ordered all of them.
Relational division with CTEs.
:category_id is a bind parameter.
265. Find employees with the highest number of direct reports.
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:
- Count employees per
manager_id. - Return the manager with the highest count.
Top-1 group.
266. Calculate the retention rate of customers month-over-month.
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:
- Get the distinct customers active in each month.
- For every month, find the customers who were also active in the following month.
- Retention = retained customers ÷ customers of the earlier month × 100.
Cohort-style retention.
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:
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.
SELECT AVG(delivery_date - order_date) AS avg_delivery_time
FROM orders
WHERE delivery_date IS NOT NULL;Logic:
delivery_date - order_dateis the delivery time.AVG()averages it for delivered orders.WHERE delivery_date IS NOT NULLexcludes undelivered orders.
Date difference with AVG.
268. Find the department with the youngest average employee age.
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:
AGE(CURRENT_DATE, birth_date)gives each employee's age.EXTRACT(YEAR FROM ...)converts it to whole years.- Average per department, sorted ascending, first row.
Age calculation.
AGE() is PostgreSQL. MySQL uses TIMESTAMPDIFF(YEAR, birth_date, CURDATE()).
269. Find products that were sold in every quarter of the current year.
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:
DATE_TRUNC('quarter', sale_date)maps each sale to its quarter.- Count the distinct quarters per product in the current year.
- Count 4 means the product sold in all quarters.
Relational division over periods.
270. Find customers whose orders decreased consecutively for 3 months.
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:
- Count orders per customer per month.
LAG(…, 1)andLAG(…, 2)bring in the previous two months.- Keep customers where each month is lower than the one before.
Trend detection with LAG().
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.
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:
- Keep rows where the arrival time is after the scheduled start.
- Count them per employee.
- Return the highest.
Top-1 with a filter.
Ties are not returned.
272. Find the most common product combinations in orders (pairs).
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:
- Join
order_itemsto itself on the same order. o1.product_id < o2.product_idremoves self-pairs and avoids counting each pair twice.- Count how many orders contain each pair and return the most frequent.
Market-basket analysis with a self join.
273. Find employees who have worked more than 40 hours in a week.
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:
DATE_TRUNC('week', work_date)groups days into weeks.SUM(hours_worked)totals each employee's weekly hours.- Keep weeks above 40.
Weekly totals.
274. Find the total revenue generated per sales representative.
SELECT sales_rep_id, SUM(amount) AS total_revenue
FROM sales
GROUP BY sales_rep_id;Logic:
- Group sales by
sales_rep_id. SUM(amount)is each rep's revenue.
Basic aggregation.
275. Find customers with no orders in the last year.
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:
- The subquery lists customers who ordered in the last year.
NOT INreturns the other customers.
Exclusion with a subquery.
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.
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:
- Total sales per product per month for the last three months.
LAG()brings in the previous two months.- Keep products where each month is higher than the previous one.
Strictly increasing trend.
277. Find departments where average salary is higher than the company average.
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:
- The CTE calculates the company average.
- Group by department.
HAVINGkeeps departments above it.
Group filter with a CTE.
Same as Question 141.
278. Find customers with orders where no product quantity is less than 5.
SELECT DISTINCT order_id
FROM order_items
GROUP BY order_id
HAVING MIN(quantity) >= 5;Logic:
- Group order items by order.
MIN(quantity) >= 5means no line is below 5.
Condition on MIN().
The query returns order ids. Join to orders to get the customers.
279. Find products ordered only by customers from one country.
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:
- Join sales to customers to find the country of each buyer.
- Count distinct countries per product.
- Keep products with exactly one.
Distinct count in HAVING.
Same as Question 251.
280. Find employees who have not submitted their timesheets in the last month.
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:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin alltimesheetscolumns. WHERE t.timesheet_id IS NULLkeeps only theemployeesrows that have no match intimesheets.
Anti-join with a date condition in ON.
Keep the date condition in the ON clause, not in WHERE.
281. Find the total discount given in each month.
SELECT DATE_TRUNC('month', order_date) AS month,
SUM(discount_amount) AS total_discount
FROM orders
GROUP BY month
ORDER BY month;Logic:
DATE_TRUNC('month', order_date)maps each order to its month.SUM(discount_amount)totals the discounts per month.
Monthly aggregation.
282. Find customers who have placed orders but never paid by credit card.
SELECT DISTINCT customer_id
FROM orders
WHERE payment_method != 'Credit Card';Logic:
- The goal is customers who have orders, none of which used a credit card.
- Group by customer and count orders paid by credit card.
- Keep customers whose count is 0.
Group-level condition.
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:
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.
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:
- The CTE calculates each department's average salary.
BETWEEN avg * 0.9 AND avg * 1.1keeps salaries within ±10% of it.
Range around a group average.
284. Find customers who ordered the most products in each category.
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:
- Total quantity per customer per category.
RANK()orders customers inside each category.- Rank 1 is the top customer for that category.
Top-1 per group.
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.
SELECT project_id, start_date, end_date, end_date - start_date AS duration
FROM projects
ORDER BY duration DESC
LIMIT 5;Logic:
end_date - start_dateis the project duration.- Sort descending and keep five rows.
Top-N with a calculated column.
286. Find employees who have not taken any leave in the last 6 months.
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:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allleavescolumns. WHERE l.leave_id IS NULLkeeps only theemployeesrows that have no match inleaves.
Anti-join with a date condition in ON.
Keep the date condition in the ON clause, not in WHERE.
287. Find the department with the most projects completed last year.
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:
- Keep completed projects whose completion date falls in the previous calendar year.
- Count per department.
- Return the highest.
Date range filter with top-1.
288. Find customers who have increased their order frequency month-over-month for 3 consecutive months.
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:
- Count orders per customer per month.
LAG(…, 1)andLAG(…, 2)bring in the previous two months.- Keep customers where each month is higher than the previous one.
Strictly increasing trend.
289. Find employees who have been assigned projects outside their department.
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:
- Join employees to their assignments and the projects.
e.department_id != p.department_idkeeps assignments to projects of another department.DISTINCTlists each employee once.
Join with an inequality condition.
290. Calculate the average time to close tickets per support agent.
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:
closed_date - opened_dateis the time to close.- Only closed tickets are included.
AVG()per agent.
Average duration per group.
291. Find the first and last login date for each user.
SELECT user_id, MIN(login_date) AS first_login, MAX(login_date) AS last_login
FROM user_logins
GROUP BY user_id;Logic:
MIN(login_date)andMAX(login_date)per user.
MIN and MAX aggregates.
292. Find customers who made purchases only in one month of the year.
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:
- Reduce orders to distinct customer and month pairs.
- Count the months per customer.
- Keep customers with exactly one month.
Distinct counts.
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.
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:
- The CTE averages the product revenue totals.
- Group sales by product and total them.
- Keep products whose total is above the average.
Group filter against an average of totals.
294. Find departments where more than 50% of employees have a salary above $60,000.
SELECT department_id
FROM employees
GROUP BY department_id
HAVING AVG(CASE WHEN salary > 60000 THEN 1
ELSE 0 END) > 0.5;Logic:
- The
CASEreturns 1 for salaries above 60,000 and 0 otherwise. AVG()of those values is the share of employees above 60,000.> 0.5keeps departments where the share exceeds 50%.
Proportion with AVG(CASE ...).
295. Find employees who worked on all projects in the company.
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:
- The first CTE counts all projects.
- The second CTE counts distinct projects per employee.
- Employees whose count equals the total worked on every project.
Relational division.
Same pattern as Question 135.
296. Find customers who ordered products from all categories.
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:
- The first CTE counts all categories.
- The second counts the distinct categories each customer ordered from.
- Equal counts mean the customer covered every category.
Relational division.
297. Find the average tenure of employees by department.
SELECT department_id,
AVG(DATE_PART('year', CURRENT_DATE - hire_date)) AS avg_tenure_years
FROM employees
GROUP BY department_id;Logic:
- Subtract the hire date from today to get tenure.
- Convert to years and average per department.
Tenure calculation.
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.
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:
EXTRACT(DOW FROM order_date)returns the day of week (0 = Sunday, 6 = Saturday).CASElabels days 0 and 6 as weekend and the rest as weekday.- Group by the label and count.
Categorizing dates with CASE.
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.
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:
- The
CASEreturns 1 when a discount exists and 0 otherwise. SUM(...)counts discounted orders andCOUNT(*)counts all orders.- Dividing and multiplying by 100.0 gives the percentage per month.
Percentage with conditional aggregation.
300. Find the employees who have never been late to work.
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:
LEFT JOINattendance rows that are late (condition inON).- Employees without a late record have
NULL. WHERE a.employee_id IS NULLreturns them.
Anti-join with a condition in ON.
Employees with no attendance rows at all are also returned.
301. Find products with sales only during holiday seasons.
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:
- The goal is products whose sales all fall on holiday dates.
- Join sales to holidays with a
LEFT JOIN. COUNT(*)counts all sales andCOUNT(h.holiday_date)counts only those on holidays; equal counts mean all sales were on holidays.
Comparing counts after a left join.
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:
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.
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:
- The first CTE counts the employees currently active in each department.
- The second CTE counts those who were active one year ago.
- Subtract to get the increase and return the largest.
Comparing two point-in-time snapshots.
303. Find the average order value per customer segment.
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:
- Join customers to orders.
- Group by segment.
AVG(amount)per segment.
Join with aggregation.
304. Find employees who manage more than 3 projects.
SELECT manager_id, COUNT(DISTINCT project_id) AS project_count
FROM projects
GROUP BY manager_id
HAVING COUNT(DISTINCT project_id) > 3;Logic:
- Group projects by manager.
- Count distinct projects.
HAVINGkeeps managers with more than three.
Distinct count in HAVING.
Same as Question 92.
305. Find products that have never been returned.
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:
LEFT JOINkeeps every row fromproducts.- Rows without a match have
NULLin allreturnscolumns. WHERE r.return_id IS NULLkeeps only theproductsrows that have no match inreturns.
Anti-join using LEFT JOIN … IS NULL.
SQL Interview Questions 306–335 — Medium to Advanced
306. Find customers with orders but no shipments.
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:
LEFT JOINshipments to orders.- Orders with no shipment have
NULLshipment columns. DISTINCTreturns each customer once.
Anti-join on orders.
307. Find employees whose salaries increased every year.
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:
LAG(salary)returns the previous year's salary.- Count rows where the salary rose (or the first year with no previous value).
- Employees whose count equals their total number of salary rows increased every year.
Consistent-trend check.
308. Find the total number of unique products sold in the last quarter.
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:
- The date range runs from the start of the previous quarter up to the start of the current quarter.
COUNT(DISTINCT product_id)counts the unique products.
Previous-quarter date range.
309. Find the day with the highest sales in each month.
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:
- The first CTE totals sales per day.
RANK()orders days within each month by total.- Rank 1 is the best day of that month.
Top-1 per group.
Ties for the best day are all returned.
310. Find the products with the highest sales increase compared to the previous month.
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:
- Total sales per product per month.
LAG()retrieves the previous month's total.- The increase is the difference; sort descending and keep the top rows.
Month-over-month increase.
311. Find the top 5 customers by total order value in the last year.
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:
- Keep orders from the last year.
- Total per customer.
- Sort descending and keep five.
Top-N with a filter.
312. Find the number of employees who changed departments in the last year.
SELECT COUNT(DISTINCT employee_id)
FROM employee_department_history
WHERE change_date >= CURRENT_DATE - INTERVAL '1 year';Logic:
- Keep department changes from the last year.
COUNT(DISTINCT employee_id)counts employees with at least one change.
Distinct count with a date filter.
313. Find the average salary for each job title within each department.
SELECT department_id, job_title, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id, job_title;Logic:
- Group by department and job title.
AVG(salary)per group.
Multi-column grouping.
314. Find customers who placed orders with multiple payment methods.
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(DISTINCT payment_method) > 1;Logic:
- Group orders by customer.
- Count distinct payment methods.
- Keep customers with more than one.
Distinct count in HAVING.
315. Find products with the lowest average rating per category.
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:
- The query averages ratings per product and keeps the lowest in each category.
Top-1 per group over an aggregate.
QUALIFY is supported by Snowflake, BigQuery and Teradata but not by PostgreSQL, MySQL or SQL Server. The portable version uses a subquery.
Portable version:
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.
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:
LEFT JOINkeeps every row fromemployees.- Rows without a match have
NULLin allpromotionscolumns. WHERE p.promotion_id IS NULLkeeps only theemployeesrows that have no match inpromotions.
Anti-join using LEFT JOIN … IS NULL.
317. Find the total number of orders placed each day in the last week.
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:
- Keep orders from the last 7 days.
- Group by date and count.
Daily counts.
318. Find customers with orders in both online and in-store channels.
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(DISTINCT order_channel) > 1;Logic:
- Group orders by customer.
- Count distinct order channels.
- More than one means the customer used both.
Distinct count in HAVING.
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.
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:
- Keep deals closed since the start of this quarter.
- Count per rep.
- Sort descending and keep three.
Top-N with a date filter.
320. Find products that have been discontinued but still have sales.
SELECT p.product_id
FROM products p
JOIN sales s ON p.product_id = s.product_id
WHERE p.discontinued = TRUE;Logic:
- Join products to sales.
- Keep products marked as discontinued.
Join with a filter.
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.
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:
- Self join each employee to their manager.
e.hire_date < m.hire_datekeeps employees hired before their manager.
Self join with a date comparison.
Same as Question 140.
322. Find the average delivery time by shipping method.
SELECT shipping_method, AVG(delivery_date - order_date) AS avg_delivery_time
FROM shipments
GROUP BY shipping_method;Logic:
delivery_date - order_dateis the delivery time.AVG()per shipping method.
Average duration per group.
323. Find orders where the total quantity exceeds 100.
SELECT order_id, SUM(quantity) AS total_quantity
FROM order_items
GROUP BY order_id
HAVING SUM(quantity) > 100;Logic:
- Group order items by order.
SUM(quantity)per order.- Keep totals above 100.
HAVING with SUM.
Same as Question 215.
324. Find customers who made orders but never returned a product.
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:
- The goal is customers none of whose orders have a return.
NOT EXISTSchecks that no return exists for any order of the customer.
Exclusion with NOT EXISTS.
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:
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.
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:
LEFT JOINreviews to products.JOINsales to keep only products that were ordered.pr.review_id IS NULLkeeps products without reviews.
Anti-join combined with a join.
326. Find employees who have worked on projects for more than 2 years.
SELECT employee_id
FROM project_assignments
GROUP BY employee_id
HAVING MAX(assignment_end_date) - MIN(assignment_start_date) > INTERVAL '2 years';Logic:
MAX(end_date) - MIN(start_date)is the span from the first start to the last end.HAVINGkeeps spans above two years.
Duration in HAVING.
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.
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:
- Total per product per month.
ROW_NUMBER()orders products in each month.rn = 1returns the best product.
Top-1 per group.
Use RANK() to return products that tie for first.
328. Find customers with the highest order count in each region.
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:
- Join customers to orders and count orders per customer.
ROW_NUMBER()ranks customers within each region by order count.rn = 1returns the top customer per region.
Top-1 per group over an aggregate.
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.
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:
- Count orders per customer per month this year.
LAG(cnt)brings in the previous month's count.- A customer qualifies only if every month-to-month comparison is an increase.
Consistent-trend check.
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:
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.
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:
- Join each employee to their manager.
EXTRACT(DOW FROM hire_date)returns the day of the week.- Keep rows where both weekdays are equal.
Comparing date parts.
331. Get total working hours per employee per week.
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:
DATE_TRUNC('week', work_date)gives the week start.SUM(hours_worked)per employee and week.
Weekly totals.
332. Identify suppliers who delivered to all regions.
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:
- The first CTE counts all regions.
- The second counts the distinct regions each supplier delivered to.
- Equal counts mean the supplier covered every region.
Relational division.
333. Find products ordered on their launch date.
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:
- Join orders to products.
- Cast the order timestamp to a date and compare with the launch date.
Join with a date comparison.
Add DISTINCT to return each product once.
334. Retrieve employees with salary in top 5% company-wide.
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:
PERCENT_RANK()ranks salaries from 0 (highest) to 1 (lowest).pr <= 0.05keeps the top 5%.- The result is joined back to employees.
Percentile filtering.
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:
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.
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:
LEFT JOINkeeps every row fromdepartments.- Rows without a match have
NULLin alljob_openingscolumns. WHERE j.job_id IS NULLkeeps only thedepartmentsrows that have no match injob_openings.
Anti-join with a condition in ON.
j.status = 'Open' must stay in the ON clause. In WHERE it would remove the NULL rows.