Skip to content

SQL Interview Questions

Practical SQL questions covering joins, aggregation, window functions and query design.

mathshian•5 Nov 2026
INNER JOIN returns only rows with a match in both tables. LEFT JOIN returns all rows from the left table, with NULLs for the right table's columns when there is no match. Use LEFT JOIN when you must keep every record on the left, such as customers with no orders.
WHERE filters individual rows before grouping. HAVING filters groups after aggregation, so it can use aggregate functions such as COUNT or SUM.
UNION combines results and removes duplicates, which costs extra work. UNION ALL keeps every row and is faster. Use UNION ALL unless you specifically need de-duplication.
Select customer_id from orders where order_date is within the last 30 days, group by customer_id and use HAVING COUNT(*) > 3. Mention how you would handle time zones and cancelled orders.
Use a window function: rank the products with DENSE_RANK() OVER (PARTITION BY category ORDER BY revenue DESC) in a subquery or CTE, then filter where the rank is at most 3. Explain the difference between ROW_NUMBER, RANK and DENSE_RANK for ties.
Use SUM(sales) OVER (ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). Add PARTITION BY if the total should restart for each store or product.
Use LAG(revenue) OVER (ORDER BY month) to bring in the prior value, then compute the difference or percentage change. Handle the first month where the previous value is NULL.
Group by the columns that define a duplicate and keep groups where COUNT(*) > 1. To delete duplicates while keeping one, use ROW_NUMBER() partitioned by those columns and remove rows with a number above 1.
LEFT JOIN customers to orders and keep rows where the order key IS NULL, or use NOT EXISTS with a correlated subquery. Avoid NOT IN when the subquery can return NULLs, since it can give wrong results.
Read the execution plan, check for full table scans, missing or unused indexes, large joins and functions applied to indexed columns. Reduce the data early with filters, select only needed columns and compare timing after each change.
An index is a sorted structure that lets the database find rows without scanning the whole table. It speeds up reads that match its columns but slows writes and uses storage. Index columns used in filters, joins and ordering, and verify with the plan.
A common table expression is a named temporary result defined with WITH. It makes complex queries readable, can be referenced several times and supports recursion for hierarchical data. Performance depends on the database, so check the plan.