SQL Interview Questions and Answers for Data Analyst and Engineering Roles
Practice SQL interview questions across joins, aggregations, window functions, CTEs, ranking, date logic, case statements, optimization basics, and business cases.
Published by PrepNPlaced. Last updated 2026-05-31. Preparation guidance, not a hiring guarantee.
Beginner rounds usually check whether you understand filtering, joins, grouping, null handling, and reading table relationships.
Explain inner join vs left join with an example
Find customers with no orders
Count orders by month and status
Answer hint
For no-order questions, start from customers and left join orders, then filter where the order key is null.
Common mistake
Filtering the right table in WHERE after a left join can accidentally turn it into an inner join.
Intermediate SQL questions
Intermediate questions test CTEs, subqueries, case statements, date functions, and converting business wording into query logic.
Calculate repeat purchase rate
Segment users by activity bands
Find the first transaction per customer
Advanced SQL questions
Advanced rounds usually involve window functions, ranking, cohort logic, rolling metrics, deduplication, and query performance tradeoffs.
Rank top products per category
Calculate 7-day rolling revenue
Deduplicate records using row_number
Window function hint
Use partition by for the group, order by for sequence, and choose row_number, rank, or dense_rank based on tie behavior.
Optimization hint
Explain filters, join keys, selected columns, indexes/partitioning, and why a query scans too much data.
Business case SQL questions
For data roles, interviewers often care less about syntax tricks and more about whether your query matches the metric definition.
Define active user before writing SQL
Clarify date range and timezone
State assumptions about refunds, cancellations, and duplicates
SQL interview questions with sample answers
These are the answered questions interviewers reuse most for analyst and data roles. Practice saying the approach first, then writing the query.
Window functions and ranking
Joins and NULL handling
Aggregation and dedup logic
Find the second highest salary
Rank distinct salaries and pick rank 2: SELECT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees GROUP BY salary) t WHERE rnk = 2. DENSE_RANK shares a rank across ties so equal salaries are handled.
RANK vs DENSE_RANK vs ROW_NUMBER
All number rows within a partition. ROW_NUMBER is always unique, RANK leaves gaps after ties (1,1,3), and DENSE_RANK does not (1,1,2). Choose by whether ties should share a number and whether gaps matter.
WHERE vs HAVING
WHERE filters rows before grouping; HAVING filters groups after aggregation. You cannot reference an aggregate like COUNT(*) in WHERE, but you can in HAVING.
Remove duplicate rows but keep one
Number duplicates with ROW_NUMBER() OVER (PARTITION BY the_key_columns ORDER BY id) and keep rows where the number equals 1, deleting the rest.
The LEFT JOIN NULL-filter trap
After a LEFT JOIN, putting a condition on the right table in WHERE silently turns it into an INNER JOIN. Move that condition into the ON clause to keep unmatched rows.
7-day rolling revenue
Use SUM(amount) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). Switch to UNBOUNDED PRECEDING for a cumulative running total.
Customers with no orders
LEFT JOIN customers to orders and filter WHERE orders.id IS NULL, or use NOT EXISTS. Be careful with NOT IN when the subquery can return NULLs.
COUNT(*) vs COUNT(col) vs COUNT(DISTINCT col)
COUNT(*) counts all rows including NULLs, COUNT(col) skips NULLs, and COUNT(DISTINCT col) counts unique non-null values. GROUP BY also collapses all NULLs into one group.
Question bank
23 interview questions with answers
Real questions from beginner to advanced, each with a concise model answer — practice them, then rehearse live in a mock interview.
BeginnerWhat is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY and can use aggregate functions like COUNT or SUM. Use WHERE for row conditions and HAVING for conditions on aggregates.
BeginnerWhat are the different types of JOINs in SQL?
INNER JOIN returns only matching rows; LEFT/RIGHT JOIN keep all rows from one side and NULLs for non-matches; FULL OUTER JOIN keeps all rows from both; CROSS JOIN returns the Cartesian product. A SELF JOIN joins a table to itself.
BeginnerWhat is the difference between UNION and UNION ALL?
UNION combines two result sets and removes duplicate rows, which costs a sort/dedupe step; UNION ALL keeps all rows including duplicates and is faster. Use UNION ALL unless you specifically need distinct rows.
BeginnerWhat is the difference between DELETE, TRUNCATE, and DROP?
DELETE removes selected rows and is logged and rollback-able; TRUNCATE removes all rows quickly with minimal logging and resets identity; DROP removes the entire table. DELETE and TRUNCATE keep the schema, DROP does not.
BeginnerWhat is a primary key versus a foreign key?
A primary key uniquely identifies each row in a table and cannot be NULL. A foreign key references a primary key in another table to enforce referential integrity between the two tables.
BeginnerHow does NULL behave in SQL, and how do you handle it?
NULL means unknown, so comparisons with NULL return unknown, not true. Use IS NULL / IS NOT NULL to test it, and COALESCE to substitute a default. Aggregates like COUNT(column) ignore NULLs.
BeginnerWhat is the logical execution order of a SELECT query?
FROM and JOINs run first, then WHERE, then GROUP BY, then HAVING, then SELECT, then DISTINCT, then ORDER BY, and finally LIMIT. This is why a SELECT alias can't be used in WHERE.
IntermediateWhat is the difference between RANK, DENSE_RANK, and ROW_NUMBER?
ROW_NUMBER gives every row a unique sequential number. RANK gives ties the same rank but leaves gaps afterward (1,1,3). DENSE_RANK gives ties the same rank with no gaps (1,1,2). All are window functions used with OVER(ORDER BY ...).
IntermediateHow do you find the second highest salary in a table?
Use a window function: SELECT DISTINCT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) rk FROM employees) t WHERE rk = 2. Alternatively use a correlated subquery or OFFSET 1 FETCH NEXT 1 ROW.
IntermediateWhat is a window function and how is it different from GROUP BY?
A window function (OVER clause) computes an aggregate across related rows without collapsing them, so each row keeps its detail. GROUP BY reduces the result to one row per group. Use windows for running totals, rankings, and moving averages.
IntermediateWhat is the difference between a CTE and a subquery?
Both produce an intermediate result. A CTE (WITH clause) is named, can be referenced multiple times, and can be recursive, which improves readability. A subquery is inline and can be correlated with the outer query. CTEs don't inherently perform better.
IntermediateWhat is the difference between EXISTS and IN?
IN checks membership against a list or subquery and can be slow with large lists and tricky with NULLs. EXISTS returns true as soon as the subquery finds a matching row and is usually more efficient for correlated existence checks.
IntermediateWhat is a correlated subquery?
A subquery that references a column from the outer query, so it is evaluated once per outer row. It's useful for row-by-row comparisons, such as rows above the average for their group, but can be slower than a JOIN or window function.
IntermediateHow do you calculate a running total in SQL?
Use a window function: SUM(amount) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). Add PARTITION BY a key to get per-group running totals.
IntermediateHow do you find and remove duplicate rows?
Find them with GROUP BY the duplicate columns HAVING COUNT(*) > 1. Remove them by keeping one row per group using ROW_NUMBER() OVER (PARTITION BY dup_cols ORDER BY id) and deleting rows where the number is greater than 1.
IntermediateWhat is the difference between a clustered and a non-clustered index?
A clustered index defines the physical order of the table's rows, so there can be only one per table. A non-clustered index is a separate structure with pointers to the rows, and you can have many. Both speed up reads but add write cost.
IntermediateWhat are LAG and LEAD used for?
LAG and LEAD are window functions that access a value from a previous or following row without a self-join. They're used for period-over-period comparisons, like the difference between this month and last month.
IntermediateWhat is the difference between DISTINCT and GROUP BY?
Both remove duplicates. DISTINCT simply returns unique rows. GROUP BY groups rows so you can apply aggregate functions per group; use it when you need counts, sums, or other aggregates alongside the distinct values.
AdvancedWhat is database normalization and why does it matter?
Normalization organizes data to reduce redundancy and update anomalies, through 1NF (atomic values), 2NF (no partial dependencies), and 3NF (no transitive dependencies). Analytics workloads often deliberately denormalize into star schemas for query speed.
AdvancedWhat are ACID properties in a database?
Atomicity (all-or-nothing transactions), Consistency (valid state transitions), Isolation (concurrent transactions don't interfere), and Durability (committed data survives failures). Together they guarantee reliable transaction processing.
AdvancedHow would you optimize a slow SQL query?
Read the execution plan, add indexes on filtered and joined columns, select only needed columns, filter early, avoid functions on indexed columns in WHERE, replace correlated subqueries with joins or windows, and refresh statistics.
AdvancedHow do you pivot rows into columns in SQL?
Use conditional aggregation: SUM(CASE WHEN category = 'A' THEN value END) as one column per category, grouped by the row key. Some databases also offer a PIVOT operator, but conditional aggregation is the portable approach.
AdvancedWhat is the difference between a materialized view and a regular view?
A regular view is a saved query that runs each time it's referenced, always showing live data. A materialized view stores the result physically for fast reads and must be refreshed to reflect new data, trading freshness for speed.
Related Guides
Continue The Cluster
Move between roadmap, interview-question, and product pages without losing the preparation thread.