SQL Questions Asked in Interview: Practical Guide with Answers
SQL questions asked in interview rounds usually test more than memorized syntax: interviewers want to see whether you can translate a business requirement into a correct query, explain your assumptions, handle missing or duplicate data, and improve a solution when scale or performance becomes important. The strongest preparation therefore combines core concepts, practical query writing, debugging, optimization, and clear communication.
This guide is designed for students, analysts, developers, data engineers, business-intelligence professionals, quality engineers, and experienced candidates preparing for SQL screening rounds. It covers common beginner, intermediate, and advanced questions; sample answers; query patterns; scenario-based tasks; mistakes to avoid; and a structured preparation plan. Examples use broadly supported SQL concepts, but exact syntax can differ across MySQL, PostgreSQL, Microsoft SQL Server, Oracle Database, and cloud data platforms.
A good interview answer should be technically correct and operationally clear. State the database assumptions, define the expected output, mention edge cases, and explain why you chose a join, subquery, common table expression, window function, index, or transaction strategy. When the interviewer provides incomplete requirements, ask a precise clarification question rather than silently making a risky assumption.
For organizations hiring database, analytics, reporting, or development specialists, the same principles help improve candidate evaluation. A practical assessment should reflect the data problems the role will actually solve, not only textbook definitions. Rudrriv can support technology and data requirements through defined projects, dedicated professionals, ongoing specialist support, or managed teams when that model is genuinely appropriate.

Quick Answer: What SQL Questions Are Asked in Interviews?
Most SQL interviews include four types of questions: concept checks, query-writing exercises, database-design discussions, and scenario-based troubleshooting. Entry-level rounds often focus on SELECT statements, filtering, sorting, aggregate functions, GROUP BY, joins, subqueries, primary and foreign keys, and NULL handling. Intermediate rounds commonly add common table expressions, window functions, conditional logic, date operations, duplicate detection, ranking, and query optimization. Senior rounds may cover indexing, execution plans, transactions, isolation, partitioning, data modeling, concurrency, and production trade-offs.
Prepare by writing queries on realistic tables rather than reading answers only. For every problem, first define the output grain, identify the tables and relationships, decide how duplicate rows and NULL values should behave, and then write the simplest correct query. Afterward, test edge cases and explain how the query might perform on a larger dataset.
The most important caution is that SQL dialects differ. In an interview, say which dialect you are using and avoid pretending that every function is universal. If a feature is platform-specific, explain the equivalent approach conceptually.
Key Takeaways
- Expect practical tasks: interviewers frequently ask you to write, correct, or explain a query rather than recite definitions.
- Start with the required output: determine the row-level grain before selecting joins, grouping, or window functions.
- Handle data quality: consider duplicates, NULLs, missing relationships, invalid dates, and inconsistent values.
- Explain trade-offs: show why one approach is clearer, safer, or faster than another.
- Know your dialect: syntax for dates, limits, string functions, and upserts varies by database platform.
- Test edge cases: a query that works on the sample rows may fail when ties, duplicates, or empty sets appear.
- Communicate clearly: state assumptions and ask focused clarification questions when requirements are incomplete.
What This Page Covers
- Common SQL interview questions with concise, interview-ready answers.
- Beginner, intermediate, and advanced query patterns.
- Join, aggregation, subquery, CTE, and window-function exercises.
- Scenario questions involving duplicates, rankings, gaps, and reporting logic.
- Performance, indexing, transactions, and database-design discussion points.
- A preparation checklist and a practical seven-day study plan.
- Guidance for employers designing realistic SQL assessments.
Table of Contents
- How this guide was prepared
- Core SQL concepts
- Beginner questions
- Intermediate questions
- Advanced and scenario questions
- Query patterns and examples
- Performance and design
- Interview strategy
- Common mistakes
- Preparation checklist
How This Guide Was Prepared
The question set is organized around recurring skills evaluated in database, analytics, reporting, software-development, and data-engineering interviews. The emphasis is on practical reasoning: selecting the correct rows, preserving the intended grain, combining data safely, producing deterministic results, and explaining performance implications.
Because database products evolve and differ, verify exact syntax in the official documentation for the platform named in the job description. The conceptual answers remain useful, but functions such as DATEADD, INTERVAL, TOP, LIMIT, FETCH FIRST, QUALIFY, MERGE, and string aggregation are not implemented identically across systems.
Interview rule: When you are unsure about a dialect-specific function, explain the logic first, identify the assumed database, and then write the closest valid syntax. Clear reasoning is better than confident but invalid code.
Core SQL Concepts Interviewers Expect You to Know
What is SQL?
SQL, or Structured Query Language, is used to define, read, change, and control data in relational database systems. In interviews, distinguish SQL as a language from a database product such as PostgreSQL, MySQL, SQL Server, or Oracle Database.
What are DDL, DML, DQL, DCL, and TCL?
- DDL: defines database objects, using commands such as CREATE, ALTER, and DROP.
- DML: changes stored data, commonly through INSERT, UPDATE, DELETE, and sometimes MERGE.
- DQL: retrieves data, principally through SELECT.
- DCL: controls permissions, commonly through GRANT and REVOKE.
- TCL: controls transactions, using COMMIT, ROLLBACK, and SAVEPOINT where supported.
What is the difference between a primary key and a foreign key?
A primary key uniquely identifies each row in a table and normally disallows NULL values. A foreign key references a candidate key, usually a primary key, in another or the same table and helps enforce referential integrity. A table can have one primary-key constraint, possibly composed of multiple columns, and many foreign keys.
What is normalization?
Normalization organizes data to reduce unnecessary duplication and update anomalies. First normal form requires atomic values and a consistent row structure. Second normal form removes partial dependency on part of a composite key. Third normal form removes non-key dependencies on other non-key attributes. In production systems, selective denormalization may be justified for read performance, but it should be deliberate and governed.
What is NULL?
NULL represents an unknown or missing value; it is not equal to zero, an empty string, or another NULL. Use IS NULL or IS NOT NULL for direct checks. Three-valued logic means predicates may evaluate to TRUE, FALSE, or UNKNOWN, which can affect filters, joins, CHECK constraints, and NOT IN subqueries.
Beginner SQL Questions Asked in Interview
What is the logical order of SELECT query processing?
A useful conceptual order is FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, and row limiting. Optimizers may execute operations differently, but this logical order explains why a SELECT alias is often unavailable in WHERE and why aggregate filters belong in HAVING.
What is the difference between WHERE and HAVING?
WHERE filters rows before grouping. HAVING filters groups after GROUP BY and can use aggregate conditions. For example, WHERE can restrict orders to the current year, while HAVING can retain only customers whose yearly order total exceeds a threshold.
What is the difference between DELETE, TRUNCATE, and DROP?
| Command | Purpose | Typical characteristics |
|---|---|---|
| DELETE | Removes selected rows | Supports a WHERE clause; fully logged behavior and identity handling vary by platform. |
| TRUNCATE | Removes all rows efficiently | Usually no WHERE clause; restrictions, logging, identity reset, and rollback behavior vary. |
| DROP | Removes the database object | Deletes the table definition and its data, subject to dependencies and permissions. |
Avoid absolute claims such as “TRUNCATE can never be rolled back.” Transaction behavior depends on the database platform and execution context.
What is the difference between UNION and UNION ALL?
UNION combines compatible result sets and removes duplicates. UNION ALL preserves all rows and is usually faster because it avoids duplicate elimination. Choose based on the business meaning, not only performance.
How do INNER JOIN and LEFT JOIN differ?
INNER JOIN returns rows with matching join conditions on both sides. LEFT JOIN returns every row from the left table and matching rows from the right; unmatched right-side columns become NULL. A common error is applying a right-table filter in WHERE after a LEFT JOIN, unintentionally converting the result to inner-join behavior. Put the condition in the ON clause when unmatched left rows must remain.
How do you find duplicate values?
Group by the columns that define duplication and filter groups with COUNT(*) greater than one. The business definition matters: duplicate email addresses, duplicate customer records, and exact duplicate rows are different problems.
Example: SELECT email, COUNT(*) FROM customers GROUP BY email HAVING COUNT(*) > 1; identifies repeated non-NULL email values in many systems. Decide separately how NULL email values should be treated.
Intermediate SQL Interview Questions
What is a subquery, and when would you use one?
A subquery is a query nested inside another statement. It may return a scalar value, one column, or a table-shaped result. Use it when it clearly expresses filtering, comparison, or staged calculation. Correlated subqueries refer to the outer row and can be elegant, but they may require careful performance review.
What is a common table expression?
A common table expression, introduced with WITH, names an intermediate result for the duration of a statement. It can improve readability, support recursive logic, and separate complex transformations into understandable stages. A CTE is not automatically materialized; optimization behavior depends on the platform and query.
What are window functions?
Window functions calculate across related rows while preserving individual rows. Common examples include ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, and aggregate functions with OVER. The PARTITION BY clause defines independent groups, and ORDER BY defines sequence within each group.
ROW_NUMBER, RANK, and DENSE_RANK: what is the difference?
| Function | Tie behavior | Example ranks for values 100, 100, 90 |
|---|---|---|
| ROW_NUMBER | Assigns a unique sequence; ties need a deterministic tie-breaker | 1, 2, 3 |
| RANK | Tied values share rank and create gaps | 1, 1, 3 |
| DENSE_RANK | Tied values share rank without gaps | 1, 1, 2 |
How do you get the second-highest salary?
Clarify whether the question means the second distinct salary or the employee in the second row after sorting. For the second distinct salary, DENSE_RANK over salary descending is clear. Another approach selects MAX(salary) below the overall maximum. Handle cases with fewer than two distinct salaries.
What is a self join?
A self join joins a table to itself using aliases. It is useful for hierarchical relationships such as employees and managers, comparisons between rows in the same table, or matching related events. Recursive CTEs are often more appropriate for traversing multiple hierarchy levels.
EXISTS versus IN: which should you use?
Use the form that most clearly expresses the requirement and test the execution plan. EXISTS checks whether at least one related row exists and often suits correlated membership tests. IN compares against a set. Be cautious with NOT IN when the subquery can return NULL, because the result may become UNKNOWN; NOT EXISTS is frequently safer.
Advanced and Scenario-Based SQL Questions
How would you return the latest order for each customer?
Use ROW_NUMBER partitioned by customer and ordered by order date descending, with a stable secondary key such as order_id descending. Filter to row number one. Without a tie-breaker, results may be nondeterministic when two orders share the same timestamp.
How would you calculate a running total?
Use SUM(amount) OVER with an appropriate partition and ordering. Specify the window frame when peer rows or duplicate dates could affect the result. For a row-by-row running total, ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is usually explicit and predictable.
How would you find gaps in a sequence?
Compare each value with the previous value using LAG, generate an expected sequence and anti-join it to actual values, or use a calendar or numbers table. Choose based on whether you need only gap boundaries or every missing value.
How would you delete duplicates but keep one row?
First define the duplicate key and the retention rule. Assign ROW_NUMBER within each duplicate group, ordered by the row that should be kept, then delete rows numbered above one using a platform-supported method. Run the ranking as a SELECT first, back up critical data, and perform the change within an appropriate transaction and review process.
How would you identify customers with no orders?
Use a LEFT JOIN from customers to orders and filter where the joined order key is NULL, or use NOT EXISTS. NOT EXISTS often communicates the requirement directly and avoids accidental duplication from multiple orders.
How do you calculate month-over-month growth?
Aggregate the metric by month, use LAG to retrieve the previous month, and calculate the percentage difference with protection against NULL or zero denominators. Decide how missing months should behave; a calendar table may be required to display explicit zero-activity periods.
What is a transaction?
A transaction groups operations into a logical unit of work. ACID commonly refers to atomicity, consistency, isolation, and durability. Interviews may ask how failures, concurrent updates, deadlocks, retries, and isolation levels affect correctness. Explain that higher isolation can reduce anomalies but may increase locking, contention, or resource use.
What are dirty reads, non-repeatable reads, and phantom reads?
- Dirty read: a transaction reads another transaction’s uncommitted change.
- Non-repeatable read: the same row is read twice and its committed values differ.
- Phantom read: repeating a range query returns a changed set of rows because another transaction inserted or deleted matching rows.
Database engines implement isolation differently, including locking and multi-version concurrency control. Discuss the specific platform when precision matters.
Common Query Patterns with Interview Examples
The following patterns recur because they reveal whether a candidate understands grain, ordering, grouping, and relationship logic. In an interview, explain the assumptions before writing the query.
| Problem | Preferred pattern | Important check |
|---|---|---|
| Top N rows per group | ROW_NUMBER or DENSE_RANK with PARTITION BY | Define how ties should be handled. |
| Rows with no related record | NOT EXISTS or LEFT JOIN with NULL check | Avoid right-table filters that remove unmatched rows. |
| Latest row per entity | ROW_NUMBER ordered by timestamp and stable key | Add a deterministic tie-breaker. |
| Duplicate detection | GROUP BY plus HAVING COUNT(*) > 1 | Define the columns that make a duplicate. |
| Running total | SUM over an ordered window | Choose ROWS or RANGE deliberately. |
| Compare current with previous row | LAG | Define partition and order. |
| Conditional aggregation | SUM or COUNT with CASE | Check NULL and denominator behavior. |
| Hierarchy traversal | Recursive CTE | Protect against cycles and excessive depth. |
Mini case study 1: ecommerce order reporting
A candidate is asked to show one row per customer with total order value, latest order date, and number of completed orders. The key is to aggregate orders at customer level before joining to customer attributes. Joining customers, orders, and order items without controlling grain can multiply rows and overstate totals. A strong answer explicitly defines whether order value comes from an order header or item-level sum and how cancelled or refunded orders are treated.
Mini case study 2: employee salary ranking
The interviewer asks for the three highest salaries in each department. The candidate should clarify whether ties can produce more than three employees. ROW_NUMBER returns exactly three rows per department when ordering is deterministic; DENSE_RANK may return more than three employees if salaries tie. The correct choice depends on the requested business rule.
Mini case study 3: subscription retention
The task is to identify customers active in consecutive months. A robust approach first normalizes activity to one row per customer per month, then compares each month with the previous month using LAG or joins month keys. The candidate should discuss timezone, late-arriving events, reactivations, and the definition of active.
Performance, Indexing, and Database Design Questions
What is an index?
An index is a data structure that helps the database locate rows more efficiently for certain access patterns. It can improve reads but consumes storage and adds maintenance cost to inserts, updates, and deletes. The value of an index depends on selectivity, column order, predicates, joins, sorting, included columns, table size, and workload.
What is a composite index?
A composite index contains multiple columns. Column order matters because many engines can efficiently use a leading portion of the index. Design it around real query predicates and ordering, not a generic rule. An index on every frequently mentioned column is not automatically beneficial.
Why might a query ignore an index?
- The optimizer estimates that a scan is cheaper because many rows match.
- A function or implicit conversion prevents an efficient seek.
- The indexed column is not the leading useful part of a composite index.
- Statistics are stale or estimates are inaccurate.
- The table is small enough that scanning is cheaper.
- The predicate is not selective or uses a pattern that cannot exploit the index.
How do you optimize a slow SQL query?
- Reproduce the issue with representative parameters and data volume.
- Review the actual execution plan where available.
- Check row estimates, scans, joins, sorts, spills, lookups, and expensive operators.
- Confirm predicates are sargable and data types match.
- Reduce unnecessary columns and rows early without changing semantics.
- Validate indexes, statistics, partition pruning, and join order assumptions.
- Test changes under realistic concurrency and measure total workload impact.
Optimization is not merely shortening the query. A concise query can still be expensive, and a longer staged query can be safer and faster. Preserve correctness and compare evidence before and after changes.
What is the difference between clustered and nonclustered indexes?
The terminology and implementation are platform-specific. In SQL Server, a clustered index determines the physical order of data pages at the leaf level, while a nonclustered index is a separate structure containing key values and row locators. Other systems organize tables and indexes differently, so identify the platform before giving a product-specific answer.
How to Answer SQL Interview Questions Effectively
A technically correct query is stronger when the interviewer can follow your reasoning. Use a repeatable answer structure: clarify, model, write, test, and improve.
- Clarify the output: What should one result row represent? Are ties allowed? Which date and status rules apply?
- Identify the source grain: Is each table at customer, order, item, event, or daily-summary level?
- Choose the simplest correct pattern: join, aggregation, subquery, CTE, or window function.
- Write readable SQL: use meaningful aliases, consistent formatting, and explicit join conditions.
- Test edge cases: no matches, duplicate keys, ties, NULLs, zero denominators, and boundary dates.
- Discuss performance: explain likely indexes, data volume concerns, and what you would verify in an execution plan.
- State platform assumptions: identify the SQL dialect and any product-specific syntax.
Useful clarification: “Should the result return exactly three employees per department, or all employees tied within the top three salary levels?” This single question determines whether ROW_NUMBER or DENSE_RANK is appropriate.
How to respond when you cannot remember exact syntax
Describe the intended operation accurately, write pseudocode or the closest syntax you know, and identify the part you would verify in documentation. Do not invent a function. Interviewers often value sound reasoning and honesty more than flawless recall of a rarely used keyword.
Common SQL Interview Mistakes
- Writing before clarifying: this often solves the wrong definition of “latest,” “duplicate,” or “top.”
- Ignoring result grain: careless joins multiply rows and distort aggregates.
- Using SELECT DISTINCT as a repair: it may hide a join or modeling error rather than solve it.
- Forgetting NULL behavior: comparisons, NOT IN, aggregates, and outer joins can behave unexpectedly.
- Returning nondeterministic results: TOP or LIMIT without a complete ORDER BY may not be repeatable.
- Overusing nested subqueries: deeply nested logic can be difficult to verify and maintain.
- Claiming one universal optimization rule: indexing and execution depend on data distribution and workload.
- Confusing syntax across platforms: functions and row-limiting clauses are not interchangeable.
- Skipping safety for data changes: UPDATE and DELETE statements should be previewed, scoped, and controlled.
- Giving unsupported absolutes: transaction, locking, and DDL behavior vary by database engine.
SQL Interview Preparation Checklist
- Review SELECT, WHERE, ORDER BY, DISTINCT, CASE, and NULL handling.
- Practice INNER, LEFT, RIGHT where supported, FULL where supported, CROSS, and self joins.
- Write GROUP BY and HAVING queries with multiple aggregates.
- Solve duplicate, top-N, latest-row, missing-row, and running-total problems.
- Practice subqueries, EXISTS, CTEs, and window functions.
- Review keys, constraints, normalization, and relationship design.
- Understand indexes, statistics, execution plans, and sargable predicates.
- Review transactions, ACID properties, isolation, locking, and deadlocks.
- Practice explaining query assumptions aloud.
- Use realistic datasets and verify output manually for small samples.
Seven-day preparation plan
| Day | Focus | Practical task |
|---|---|---|
| 1 | Core querying | Write filters, sorting, CASE expressions, and NULL-safe conditions. |
| 2 | Joins and grain | Combine customer, order, and item tables without double counting. |
| 3 | Aggregation | Solve totals, averages, conditional counts, and HAVING questions. |
| 4 | Subqueries and CTEs | Rewrite the same problem using alternative readable approaches. |
| 5 | Window functions | Practice ranking, running totals, LAG, LEAD, and top-N per group. |
| 6 | Performance and transactions | Read execution plans and review index and isolation concepts. |
| 7 | Mock interview | Solve timed questions while explaining assumptions and edge cases aloud. |
Guidance for Employers Designing SQL Assessments
A useful assessment should reflect the role. An analyst may need aggregation, window functions, data-quality checks, and metric definitions. An application developer may need transactions, schema design, constraints, query safety, and performance. A data engineer may need large-scale transformations, incremental loading, partitioning, and pipeline reliability.
Use a small but realistic schema, provide a data dictionary, and distinguish must-have requirements from optional improvements. Score correctness, reasoning, edge-case handling, readability, and communication separately. Avoid puzzle questions that depend on obscure syntax unless that knowledge is genuinely required for the job.
For take-home work, define expected time, permitted tools, confidentiality rules, and whether external documentation or AI assistance is allowed. Review the candidate’s explanation and validation approach, not only the final query text.
Summary: SQL Questions Asked in Interview
SQL interviews assess whether you can convert a requirement into reliable data logic. Prepare core concepts, joins, grouping, subqueries, CTEs, window functions, indexing, transactions, and execution-plan reasoning. More importantly, practice defining the output grain, asking precise questions, handling edge cases, and explaining trade-offs.
For each exercise, verify correctness before optimization. Confirm how ties, duplicates, missing rows, NULL values, dates, and status rules should behave. When a query changes data, discuss previewing the target rows, transaction controls, permissions, backups, and rollback or recovery procedures appropriate to the platform.
Candidates should select preparation depth based on the role, database platform, and expected responsibilities. Employers should design assessments around realistic work and evaluate reasoning, quality, communication, ownership, delivery verification, and handover—not memorization alone.
Frequently Asked Questions
What SQL questions are commonly asked in interviews?
Common questions cover SELECT statements, joins, GROUP BY, HAVING, subqueries, CTEs, window functions, duplicate detection, ranking, keys, normalization, indexes, transactions, and query optimization. The mix depends on the role and experience level.
How should a beginner prepare for SQL interview questions?
Start with filtering, sorting, joins, grouping, aggregates, CASE expressions, and NULL handling. Then solve practical problems on small datasets and explain each query aloud. Add subqueries and window functions after the fundamentals are reliable.
Are SQL interview questions different for analysts and developers?
Yes. Analyst interviews often emphasize reporting logic, data quality, metrics, aggregation, and window functions. Developer interviews may add schema design, transactions, constraints, concurrency, security, and application performance.
What is the best way to answer a SQL query-writing question?
Clarify the required output, identify the grain of each table, state assumptions, write the simplest correct query, test edge cases, and then discuss performance. Use meaningful aliases and explain dialect-specific syntax.
Do I need to memorize every SQL function?
No. You should know common functions and patterns, but exact syntax can be verified. In an interview, accurately explain the logic, name the assumed database, and avoid inventing unsupported functions.
Why are window functions important in SQL interviews?
Window functions solve ranking, running totals, previous-row comparisons, top-N-per-group, and related analytical problems while preserving row detail. They reveal whether a candidate understands partitioning and ordering.
How do I explain SQL query optimization in an interview?
Describe a measurement-led process: reproduce the issue, review the execution plan, check estimates and expensive operators, validate predicates and data types, review indexes and statistics, test changes, and confirm that correctness is preserved.
What SQL mistakes do interviewers notice most often?
Frequent mistakes include ambiguous joins, incorrect grouping, misuse of DISTINCT, poor NULL handling, nondeterministic ordering, ignoring ties, unsafe DELETE or UPDATE statements, and unsupported claims about database behavior.
Which SQL dialect should I use in an interview?
Use the dialect stated in the job description or interview. When none is specified, declare your assumption, such as PostgreSQL or SQL Server, and explain any syntax that may differ in other systems.
Can Rudrriv help businesses hire SQL or data specialists?
Rudrriv can support relevant technology and data requirements through specialist matching, defined projects, dedicated professionals, ongoing support, or managed teams. The appropriate model depends on scope, access, security, delivery ownership, timeline, and required expertise.
Need SQL, Data, or Development Support?
Define the business problem, required database platform, data sensitivity, expected deliverables, access model, timeline, review process, quality checks, ownership, and handover requirements. Rudrriv can help structure a defined project, dedicated-professional engagement, ongoing specialist support plan, or managed team where appropriate.
Discuss your requirementAt Rudrriv, we make it easier for businesses to access the right expertise, execute important work, and scale with confidence.