Home›Knowledge Bank›SQL Interview Questions: Concepts and Topics for Data Roles
Data & Analytics

SQL Interview Questions: Concepts and Topics for Data Roles

Key SQL concepts interviewers test, with worked examples and common pitfalls.

Share
Quick answer

SQL interviews test whether you can write correct, efficient queries and explain how relational databases work under the hood, not just memorize syntax. Expect questions spanning joins, aggregation, subqueries, window functions, indexing, and normalization, plus at least one live query-writing or debugging exercise. The strongest candidates can explain the tradeoffs behind a query, not just produce one that runs.

SQL interviews rarely fail candidates because they don't know what a SELECT statement does. They fail candidates because the questions are designed to expose how you think about data: whether you can reason about row multiplication, spot a filtering trap, or explain why a query is slow. This article walks through the core concept areas interviewers draw from, with worked examples and the pitfalls that trip up even experienced practitioners.

What SQL Interviews Actually Test

Every SQL interview is really testing five overlapping skills, even when the question looks like a simple syntax check.

  • Syntax fluency: can you write correct, idiomatic SQL without hesitating over basic clause order?
  • Query logic: do you understand what a query actually returns, including edge cases with NULLs or duplicate rows?
  • Data modeling: can you reason about how tables relate and whether a schema supports the question being asked?
  • Performance awareness: do you notice when a query will be slow at scale, not just when it's technically correct?
  • Communication: can you narrate your reasoning so an interviewer can follow your thought process, not just your final answer?

Difficulty scales sharply by role. An analyst interview leans on joins, aggregation, and clean reporting logic. An engineer interview adds window functions, query optimization, and schema design trade-offs. A DBA interview pushes further into indexing strategy, isolation levels, and transaction behavior under concurrent load.

It's worth knowing where SQL sits relative to other tools you might be asked about, since interviewers sometimes probe judgment as much as syntax — the Python vs SQL debate comes up often when a role touches both data engineering and analysis.

Joins, Set Operations, and Relational Logic

Joins are the single most-tested SQL concept, and most mistakes come from not visualizing what happens to row counts.

  • INNER JOIN returns only rows with matches in both tables — mismatched rows vanish silently, which surprises candidates who expect every row to appear.
  • LEFT JOIN keeps every row from the left table, filling unmatched right-side columns with NULL. This is the join interviewers use most to test NULL handling.
  • RIGHT JOIN mirrors LEFT JOIN from the other side and is rarely used in practice since you can usually just flip the table order.
  • FULL JOIN keeps unmatched rows from both sides, which is useful for finding mismatches between two datasets.
  • CROSS JOIN produces every combination of rows from both tables — a classic source of accidental row explosion when a join condition is missing.
  • SELF JOIN joins a table to itself, typically used for hierarchical data like an employee-manager relationship.

Consider a customers table and an orders table. A LEFT JOIN from customers to orders returns one row per order, but customers with zero orders appear once with NULL order columns. If you then run COUNT(order_id), those NULL rows are correctly excluded — but COUNT(*) would count them, which is a frequent source of wrong totals.

UNION vs UNION ALL is another recurring question. UNION removes duplicate rows across the combined result sets, which means the database has to sort and compare every row. UNION ALL keeps everything, including duplicates, and is almost always faster. Default to UNION ALL unless you specifically need deduplication.

A join doesn't combine two tables — it asks a question about how two sets of facts relate, and the answer you get depends entirely on which rows you're willing to lose.

Get trained in Data & Analytics

Start your SQL for Data journey — get a free 1:1 consultation.

Related courses

What do these skills pay? Check the IT Salary Calculator → salaries by role, country and experience.

Aggregation, Grouping, and Filtering

GROUP BY collapses rows that share a value in one or more columns, letting you apply aggregate functions like SUM, COUNT, AVG, MIN, and MAX to each group separately.

The classic trap interviewers set is WHERE vs HAVING. WHERE filters rows before grouping happens, so it can't reference an aggregate function. HAVING filters groups after aggregation, so it's the only place you can write something like HAVING SUM(amount) > 1000.

  • Filtering before aggregation: use WHERE to exclude raw rows — for example, only orders placed this year — before they're ever grouped.
  • Filtering after aggregation: use HAVING to exclude entire groups based on a computed value, such as customers whose total spend exceeds a threshold.
  • Mixing them up is a common mistake: putting an aggregate condition in WHERE throws an error, and putting a row-level condition in HAVING works but silently hurts performance because it filters far later than necessary.

Another subtle trap: columns in the SELECT list that aren't wrapped in an aggregate function generally need to appear in the GROUP BY clause, or the query becomes ambiguous about which row's value to show.

Subqueries, CTEs, and Window Functions

Subqueries come in two flavors, and interviewers like to ask you to tell them apart. A non-correlated subquery runs once, independently of the outer query — for example, finding all orders above the overall average order value. A correlated subquery re-runs once per row of the outer query, referencing a value from that outer row each time, which makes it far more expensive on large tables.

Common Table Expressions (CTEs), written with a WITH clause, don't change what's computationally possible but dramatically improve readability. Breaking a complex query into named, sequential steps makes it easier to debug and easier for an interviewer to follow your reasoning aloud.

Window functions are where mid-to-senior interviews separate strong candidates from average ones.

  • ROW_NUMBER() assigns a unique, sequential number to each row within a partition, useful for picking "the latest record per customer."
  • RANK() and DENSE_RANK() assign the same rank to ties, with RANK() leaving gaps in the sequence and DENSE_RANK() not.
  • Running totals use SUM() OVER (ORDER BY date) to accumulate a value row by row without collapsing the result the way GROUP BY would.

The key conceptual difference from GROUP BY: window functions let you compute aggregates while still returning every individual row, which is exactly what reporting queries usually need.

Indexes, Query Optimization, and Execution Plans

An index is a separate data structure, usually a B-tree, that lets the database locate rows without scanning the whole table. It speeds up reads on the indexed column but adds overhead to every write, since the index has to be updated too.

  • Index when a column is frequently used in WHERE clauses, JOIN conditions, or ORDER BY, especially on large tables.
  • Avoid over-indexing tables that see heavy write volume, since each additional index slows down every INSERT and UPDATE.
  • Composite indexes help when queries consistently filter on the same combination of columns, but column order in the index matters.

Reading an execution plan (via EXPLAIN or EXPLAIN ANALYZE) is a skill interviewers increasingly test directly. Look for full table scans on large tables, nested loop joins where a hash join would be cheaper, and steps with unexpectedly high estimated row counts — these are usually where a query's time is actually being spent.

When diagnosing a slow query, start by checking whether the WHERE and JOIN columns are indexed, then look for functions wrapped around indexed columns, since that usually prevents the index from being used at all.

Transactions, Normalization, and Database Design

ACID properties — Atomicity, Consistency, Isolation, Durability — describe what a transaction guarantees. Interviewers often ask you to explain what breaks if one of these is weakened, especially Isolation.

  • Read Uncommitted allows dirty reads, where one transaction sees another's uncommitted changes.
  • Read Committed prevents dirty reads but still allows non-repeatable reads within the same transaction.
  • Repeatable Read locks rows it has read, preventing other transactions from changing them until it finishes.
  • Serializable is the strictest level, effectively making transactions behave as if run one at a time.

Normalization questions test whether you understand why redundancy causes update anomalies. First normal form eliminates repeating groups, second normal form removes partial dependencies on a composite key, and third normal form removes transitive dependencies on non-key columns. Interviewers also like asking when it makes sense to denormalize deliberately — typically for read-heavy reporting workloads where join cost outweighs redundancy risk, a trade-off that comes up constantly when designing schemas for cloud database services.

Constraint design is another integrity check: primary keys enforce uniqueness, foreign keys enforce referential integrity, and NOT NULL or CHECK constraints push validation down into the database rather than leaving it entirely to application code.

Scenario-Based and Live Coding Questions

Live SQL problems test process as much as output. The strongest candidates work through a consistent sequence rather than jumping straight to code.

  1. Clarify requirements first: ask what counts as a duplicate, how NULLs should be treated, and what the expected grain of the result is before writing anything.
  2. Write incrementally: start with a simple SELECT to confirm you understand the table structure, then add joins, filters, and aggregation one layer at a time.
  3. Test edge cases: deliberately consider empty tables, duplicate rows, and NULL values rather than assuming clean data.
  4. Narrate your thinking: say out loud why you chose a LEFT JOIN over an INNER JOIN, or why you added a HAVING clause — interviewers are grading the reasoning, not just the final query.

If a problem involves especially large datasets or distributed processing, it's reasonable to mention how the approach would differ at scale — this is also where familiarity with Apache Spark architecture can come up if the conversation shifts from single-database SQL to distributed query engines.

Common Mistakes and Misconceptions Candidates Make

  • Ignoring NULLs: forgetting that NULL doesn't equal anything, including itself, which breaks naive equality checks and COUNT assumptions.
  • Misusing DISTINCT: applying DISTINCT to mask a join that's producing duplicate rows instead of fixing the underlying join condition.
  • Confusing HAVING and WHERE: trying to filter on an aggregate in WHERE, or filtering row-level conditions in HAVING where it's needlessly expensive.
  • Over-indexing: adding indexes reactively to every column mentioned in a slow query without checking write-side cost.
  • Treating COUNT(*) and COUNT(column) as identical: the former counts all rows, the latter skips NULLs in that column, and mixing them up quietly changes totals.
  • Staying silent while coding: going quiet during a live problem makes it impossible for an interviewer to give partial credit for correct reasoning behind an incomplete answer.

Many of these mistakes come from treating SQL as purely declarative syntax rather than as a tool for reasoning about sets. Newer data roles layer additional concepts on top of this foundation — similarity search over embeddings, for instance, has pushed vector search databases into interviews for roles touching machine learning pipelines, even when the core job is still SQL-heavy. Building fluency across both relational and newer data paradigms is part of why broader programmes, such as a Data Science with Python programme, pair SQL fundamentals with the surrounding ecosystem rather than teaching it in isolation.

Key takeaways
  • Interviewers care more about your reasoning process than a perfect query on the first try — narrate your logic as you write.
  • Know the difference between filtering rows (WHERE) and filtering groups (HAVING) cold; it's one of the most common trick questions.
  • Window functions (ROW_NUMBER, RANK, LAG/LEAD) come up constantly for deduplication, ranking, and running-total problems.
  • Being able to read an execution plan and explain why an index would or wouldn't help signals senior-level SQL understanding.
  • Practice explaining normalization and ACID tradeoffs in plain language — many roles test communication as much as syntax.

Glossary

  • ACID: The set of properties (Atomicity, Consistency, Isolation, Durability) that guarantee reliable database transactions.
  • Normalization: The process of structuring tables to reduce data redundancy, typically described in stages called normal forms.
  • Index: A data structure that speeds up row lookups on specific columns at the cost of extra storage and slower writes.
  • CTE (Common Table Expression): A named temporary result set defined with WITH, used to make complex queries more readable and reusable.
  • Execution Plan: The database's step-by-step strategy for running a query, used to diagnose performance bottlenecks.
  • Window Function: A function that computes a value across a set of related rows (a 'window') without collapsing them into one row, e.g. ROW_NUMBER() or SUM() OVER().

Frequently asked questions

What's the difference between WHERE and HAVING?

WHERE filters individual rows before any grouping happens, while HAVING filters groups after GROUP BY has been applied. You can use aggregate functions like COUNT() or SUM() in HAVING but not in WHERE. A common mistake is trying to filter on an aggregate in WHERE, which throws an error.

What's the difference between a primary key and a unique key?

A primary key uniquely identifies each row and cannot contain NULLs, and a table can only have one. A unique key also enforces uniqueness but allows a single NULL value (in most databases) and a table can have several unique keys. Both create an index automatically in most systems.

How do you find duplicate rows in a table?

Group by the columns that define a duplicate and use HAVING COUNT(*) > 1 to surface the offending groups. For row-level duplicate removal, pair ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) with a filter to keep only the first occurrence. This approach also works for deciding which duplicate to keep based on a tiebreaker column.

What's the difference between RANK, DENSE_RANK, and ROW_NUMBER?

ROW_NUMBER assigns a unique sequential number to every row regardless of ties. RANK gives tied rows the same rank but skips subsequent numbers, while DENSE_RANK gives tied rows the same rank without skipping. Interviewers use this to check if you understand how ties are handled, not just that you know the function names.

How would you optimize a slow-running query?

Start by reading the execution plan to find full table scans, missing index usage, or expensive joins/sorts. Then check if an index on the filter or join columns would help, whether the query is pulling more columns or rows than needed, and whether a subquery can be rewritten as a join or CTE. Always validate the fix by comparing before/after plans, not just execution time.

What's the difference between UNION and UNION ALL?

UNION combines result sets and removes duplicate rows, which requires an internal sort or hash step and costs more performance. UNION ALL combines result sets and keeps all rows including duplicates, making it faster when you know duplicates aren't a concern. Default to UNION ALL unless you specifically need deduplication.


← Back to Knowledge Bank

Ready to build this capability?

Browse our upcoming batches — live, instructor-led, delivered on Orbit.