100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
SQL

Common SQL Interview Questions

A curated walkthrough of the SQL interview questions asked most often, with clear, technically accurate answers.

Interview PrepIntermediate14 min readJul 8, 2026
Analogies

Overview

SQL interviews rarely test exotic syntax. Instead, they probe whether you understand core relational concepts well enough to explain them clearly and apply them correctly: how filtering differs before and after grouping, what makes a key a key, how deletion commands differ in cost and reversibility, and how three-valued NULL logic changes the way comparisons behave. This topic collects the questions that come up again and again across junior-to-mid-level SQL interviews, paired with answers that go beyond a one-liner so you understand the reasoning, not just the result.

🏏

Cricket analogy: Just as a selector's interview probes whether a player truly understands field placements and not just memorized stats, a SQL interview probes whether you understand WHERE vs HAVING and keys, not just recite syntax.

Frequently Asked Questions

Q: What is the difference between WHERE and HAVING?

WHERE filters individual rows before any grouping or aggregation happens, and it cannot reference aggregate functions like SUM() or COUNT(). HAVING filters groups after GROUP BY has produced them, and it is specifically designed to filter on aggregate results, such as HAVING COUNT(*) > 5. A query can use both: WHERE narrows the rows that get grouped, then HAVING narrows which resulting groups are kept. If you write a condition on a raw column with no aggregation, put it in WHERE for better performance, since WHERE can eliminate rows before the (often expensive) grouping work happens.

🏏

Cricket analogy: WHERE is like a selector cutting players before trials even form squads, while HAVING is like cutting entire squads after they've been formed and their combined stats, like total runs, are known.

Q: What are the different types of JOIN, and how do they differ?

INNER JOIN returns only rows that have matching values in both tables. LEFT (OUTER) JOIN returns all rows from the left table plus matched rows from the right table, filling unmatched right-side columns with NULL. RIGHT (OUTER) JOIN is the mirror image, keeping all rows from the right table. FULL OUTER JOIN keeps all rows from both tables, matching where possible and filling NULLs elsewhere. CROSS JOIN produces the Cartesian product of both tables with no matching condition at all. A SELF JOIN is not a distinct join type mechanically — it's any join (usually INNER or LEFT) where a table is joined to itself, typically used for hierarchical or comparative data like employee-manager relationships.

🏏

Cricket analogy: INNER JOIN keeps only batters who also bowled, LEFT JOIN keeps every batter even if they never bowled (NULL bowling stats), and CROSS JOIN pairs every batter with every possible bowler with no matching condition.

Q: What is the difference between a primary key and a unique key?

Both enforce uniqueness of values in a column or set of columns, and both are typically backed by an index. The differences: a table can have only one primary key but multiple unique keys/constraints. A primary key's columns cannot contain NULL, while a unique key generally allows one or more NULLs (since NULL is not considered equal to another NULL, so multiple NULLs don't violate uniqueness in most databases). The primary key is conventionally the column(s) other tables reference via foreign keys, signaling 'this is the canonical identifier for a row', while a unique key just guarantees no duplicate values exist for that column, such as an email address.

🏏

Cricket analogy: A primary key is like a player's unique jersey number that can never be blank and is what other tables reference, while a unique key is like a player's passport number, also unique but allowed to be missing for some records.

Q: What is the difference between DELETE, TRUNCATE, and DROP?

DELETE is a DML statement that removes rows one at a time (optionally filtered by WHERE), logs each row deletion, can be rolled back within a transaction, and fires any ON DELETE triggers. TRUNCATE is a DDL-like statement that deallocates the data pages holding all rows in one fast operation, cannot use WHERE (it always removes everything), typically cannot be rolled back in many databases (or requires the truncate to occur inside an explicit transaction, depending on the engine), and resets identity/auto-increment counters. DROP removes the entire table object itself — structure, data, indexes, constraints, and permissions all disappear. In short: DELETE removes some or all rows and keeps the table; TRUNCATE removes all rows fast and keeps the table; DROP removes the table entirely.

🏏

Cricket analogy: DELETE is like removing specific dismissed batters from a scorecard one by one, which can be undone before the innings closes; TRUNCATE is like wiping the whole scorecard clean instantly; DROP is like tearing up the scorecard sheet entirely.

Q: What is a Common Table Expression (CTE), and why use one?

A CTE, defined with WITH name AS (SELECT ...), is a named, temporary result set that exists only for the duration of the query that follows it. It improves readability by letting you break a complex query into logical, named steps instead of nesting subqueries. CTEs can also be referenced multiple times in the same query without repeating the subquery logic, and a recursive CTE (WITH RECURSIVE in many databases) is the standard way to walk hierarchical data such as an org chart or category tree. Unlike a view, a CTE is not persisted in the database schema — it's scoped entirely to one statement.

🏏

Cricket analogy: A CTE is like a temporary net-practice drill set up just for one training session and torn down after, letting a coach break a complex strategy review into named steps like 'top_order_stats' without saving it permanently.

Q: How does NULL behave in comparisons, and why does it trip people up?

NULL represents 'unknown', not zero or empty string, so any direct comparison with NULL using =, !=, <, or > evaluates to UNKNOWN rather than TRUE or FALSE — including NULL = NULL. This means WHERE column = NULL never matches any row, even rows that are NULL, which surprises many developers. The correct way to test for NULL is IS NULL or IS NOT NULL. NULL also affects aggregate functions (most ignore NULLs, e.g., AVG and COUNT(column) skip them, while COUNT(*) counts all rows) and logical operators (UNKNOWN propagates through AND/OR using three-valued logic, so a row is only returned by WHERE if the final result is TRUE, not UNKNOWN).

🏏

Cricket analogy: WHERE column = NULL is like asking an umpire 'is this delivery equal to unknown outcome,' which never resolves to yes; you must ask IS NULL instead, just as three-valued logic means NULL never equals NULL.

Q: What's the difference between UNION and UNION ALL?

UNION combines the result sets of two or more SELECT statements and removes duplicate rows, which requires an implicit sort/deduplication step and is therefore slower. UNION ALL combines the result sets and keeps every row, including duplicates, making it faster since no deduplication work is done. Both require the SELECT statements to have the same number of columns with compatible data types in the same order. Use UNION ALL whenever you know duplicates either can't occur or don't matter, since it avoids unnecessary overhead.

🏏

Cricket analogy: UNION merging two squad lists and removing duplicate players requires sorting and checking for repeats, while UNION ALL just stacks both lists together instantly, even if a player appears on both rosters.

Q: What is a correlated subquery, and how does it differ from a regular subquery?

A regular (non-correlated) subquery runs once, independently of the outer query, and its result is used by the outer query. A correlated subquery references a column from the outer query, so conceptually it re-executes once per row processed by the outer query, using that row's values as input. For example, finding employees who earn more than the average salary in their own department requires a correlated subquery that recalculates the department average per row. Correlated subqueries are powerful but can be slow on large datasets since naive execution is row-by-row; modern query optimizers often rewrite them as joins internally when possible.

🏏

Cricket analogy: A correlated subquery finding batters who scored above their own team's average is like recalculating a team's average score fresh for each player being checked, versus a non-correlated subquery that computes one overall average once.

Q: What is the difference between a clustered and a non-clustered index?

A clustered index determines the physical order in which table rows are stored on disk — there can be only one per table because data can only be sorted one way physically. A non-clustered index is a separate structure that stores the indexed column values plus a pointer (or the clustered key) back to the actual row, and a table can have many non-clustered indexes. Reading via a clustered index is generally faster for range scans since the data is already in order, while non-clustered indexes add an extra lookup step to fetch the full row unless the query is 'covered' by the index alone.

🏏

Cricket analogy: A clustered index is like a scorecard physically sorted by batting order, so there's only one true physical order, while a non-clustered index is like a separate quick-reference sheet pointing back to each entry, and you can have several.

Q: How would you find duplicate rows in a table?

The classic approach groups by the columns that define a 'duplicate' and filters groups with a count greater than one: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1. To then delete duplicates while keeping one copy, a common pattern uses a window function like ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) in a CTE, then deletes rows where the row number is greater than 1. This is asked frequently because it tests whether a candidate can combine GROUP BY/HAVING or window functions correctly rather than writing a slow self-join.

🏏

Cricket analogy: Deduplicating players registered twice by GROUP BY email HAVING COUNT(*) > 1 is like a scorer flagging any player listed twice on a roster; ROW_NUMBER() PARTITION BY email then lets you keep only the first registration and drop the rest.

Q: What is the difference between a scalar function and an aggregate function?

A scalar function operates on a single value and returns a single value for each row it's applied to, such as UPPER(), ROUND(), or DATEDIFF(). An aggregate function operates across a set of rows (typically a group, or the whole table) and collapses them into one summary value, such as SUM(), AVG(), COUNT(), MIN(), and MAX(). This distinction matters for where each can legally appear: scalar functions can be used almost anywhere including WHERE, while aggregate functions require GROUP BY context and can't be used directly in a WHERE clause, only in HAVING or SELECT.

🏏

Cricket analogy: A scalar function like ROUND() applied to one batter's strike rate at a time is like adjusting one player's individual stat, while an aggregate function like AVG() collapses an entire team's scores into one summary number, usable only with GROUP BY context.

Quick Reference

  • WHERE filters rows before grouping; HAVING filters groups after aggregation.
  • INNER, LEFT, RIGHT, FULL OUTER, CROSS, and SELF joins each answer a different 'which rows survive' question.
  • Primary key: one per table, no NULLs, canonical row identifier. Unique key: many allowed, NULLs usually permitted.
  • DELETE removes rows (logged, filterable, rollback-able); TRUNCATE clears all rows fast; DROP removes the table itself.
  • A CTE is a named, query-scoped temporary result set, useful for readability and recursion.
  • NULL comparisons with =/!= always evaluate to UNKNOWN; use IS NULL / IS NOT NULL instead.
  • UNION deduplicates and sorts; UNION ALL keeps all rows and is faster.
  • A correlated subquery references the outer query's row values and conceptually runs per row.
  • A table has at most one clustered index but can have many non-clustered indexes.
  • GROUP BY + HAVING COUNT(*) > 1, or ROW_NUMBER() window functions, are the standard duplicate-detection tools.
  • Scalar functions return one value per row; aggregate functions collapse many rows into one value.

Key Takeaways

  • Interviewers care more about *why* an answer is correct than the syntax itself — practice explaining, not just writing queries.
  • Filtering order (WHERE before grouping, HAVING after) is one of the most commonly misunderstood fundamentals.
  • Knowing the practical differences between DELETE/TRUNCATE/DROP signals you understand transactional and operational risk, not just syntax.
  • NULL's three-valued logic is a frequent source of subtle bugs and a favorite interview trap.
  • Being able to write a duplicate-detection or top-N-per-group query fluently is one of the best signals of real SQL fluency.

Practice what you learned

Was this page helpful?

Topics covered

#SQL#DatabaseSQLStudyNotes#Database#CommonSQLInterviewQuestions#Common#Interview#Questions#Frequently#StudyNotes#SkillVeris