In this authoritative article, I’ve compiled high-level SQL interview questions that separate juniors from architects.
Advanced SQL Interview Questions and Answers
Fundamentals & ACID Compliance (Questions 1–15)
- What are ACID properties? Atomicity (all or nothing), Consistency (valid state), Isolation (no interference), Durability (persists after crash).
- SQL vs. NoSQL? SQL is relational (rigid schema, vertical scaling); NoSQL is non-relational (flexible, horizontal scaling).
- What is a Primary Key? A unique identifier for a row; cannot be NULL.
- Foreign Key? A field that links to a Primary Key in another table to maintain referential integrity.
- Unique Constraint? Ensures all values in a column are different, but allows one NULL (unlike Primary Key).
- Composite Key? A primary key made of 2+ columns.
- What is a Schema? The logical structure or container for database objects (tables, views, etc.).
- DML vs. DDL vs. DCL? Data Manipulation (SELECT, INSERT), Data Definition (CREATE, DROP), Data Control (GRANT, REVOKE).
- What is TCL? Transaction Control Language (COMMIT, ROLLBACK, SAVEPOINT).
- Difference between CHAR and VARCHAR? CHAR is fixed length (padded with spaces); VARCHAR is variable length.
- What is a NULL value? Represents missing or unknown data; not the same as zero or an empty string.
- IS NULL vs. = NULL? You must use
IS NULL;= NULLalways evaluates to false. - What is COALESCE? Returns the first non-null value in a list.
- What is NULLIF? Returns NULL if two arguments are equal.
- What is an Alias? A temporary name for a table or column (using
AS).
Advanced Joins & Subqueries (Questions 16–35)
- INNER vs. LEFT vs. RIGHT JOIN? INNER (matches only), LEFT (all from left + matches), RIGHT (all from right + matches).
- What is a FULL OUTER JOIN? Returns all rows when there is a match in either left or right table.
- What is a CROSS JOIN? A Cartesian product (every row of A paired with every row of B).
- What is a Self Join? Joining a table to itself (useful for manager/employee hierarchies).
- Natural Join? Joins tables based on columns with the same name and data type automatically.
- Equi Join vs. Non-Equi Join? Equi join uses
=; Non-equi uses!=,<, or>. - What is a Subquery? A query nested inside another query.
- Correlated vs. Non-Correlated Subquery? Correlated subqueries reference the outer query and execute once per row of the outer query.
- When to use JOIN vs. Subquery? Joins are generally faster; subqueries are better for readability or existence checks.
- What is
EXISTS? Returns true if the subquery returns any rows (stops searching early). INvs.EXISTS?EXISTSis usually faster for large datasets;INis better for small literal lists.- What is
ANYandALL? Used to compare a value to a set of values from a subquery. - What is an Anti-Join? Returns rows from the first table that have no match in the second.
- What is a Semi-Join? Returns rows from the first table that have at least one match in the second (like
EXISTS). - UNION vs. UNION ALL?
UNIONremoves duplicates;UNION ALLis faster and keeps duplicates. - INTERSECT vs. EXCEPT?
INTERSECTreturns common rows;EXCEPTreturns rows in the first query not in the second. - Can you join a table on a range? Yes, using
BETWEENor comparison operators in theONclause. - What is a Lateral Join (CROSS APPLY)? Allows a subquery to reference columns from a preceding table in the
FROMclause. - How do you join on a JSON column? Use dialect-specific functions like
JSON_TABLE(MySQL) orOPENJSON(SQL Server). - How to avoid “Join Explosion”? Pre-aggregate data to the join grain before performing the join.
Window Functions & Aggregates (Questions 36–50)
- What is a Window Function? Performs calculations across a set of rows related to the current row without collapsing them.
- ROW_NUMBER() vs. RANK() vs. DENSE_RANK()?
ROW_NUMBERis unique;RANKskips numbers after ties;DENSE_RANKdoes not skip. - What do LEAD() and LAG() do? Access data from the next or previous row.
- FIRST_VALUE() and LAST_VALUE()? Returns the first or last value in a window frame.
- What is the
OVER()clause? Defines the window partition and order for the function. - PARTITION BY vs. GROUP BY?
GROUP BYcollapses rows;PARTITION BYkeeps original rows while aggregating. - What is a Window Frame (ROWS BETWEEN)? Defines a subset of rows within the partition (e.g.,
3 PRECEDING). - How to calculate a Running Total?
SUM(val) OVER(ORDER BY date). - How to calculate a Moving Average?
AVG(val) OVER(ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW). - What is NTILE? Divides rows into a specified number of ranked groups (e.g., quartiles).
- Difference between COUNT(*) and COUNT(col)?
COUNT(*)counts all rows;COUNT(col)ignores NULLs. - What is STRING_AGG / GROUP_CONCAT? Concatenates values from multiple rows into a single string.
- How to find the Nth highest salary? Use
DENSE_RANK()in a CTE and filter forRank = N. - Can you use Window Functions in a WHERE clause? No, you must use a CTE or Subquery.
- What is
QUALIFY? A BigQuery/Snowflake clause to filter window function results (likeHAVINGforGROUP BY).
CTEs & Recursive Queries (Questions 51–60)
- What is a CTE (Common Table Expression)? A temporary result set defined using the
WITHclause. - CTE vs. Temp Table? CTEs exist only for the scope of the query; Temp tables are physical objects in
tempdb. - What is a Recursive CTE? A CTE that references itself to traverse hierarchical data (like org charts).
- What is the Anchor Member in recursion? The base query that initializes the recursive process.
- Recursive Member? The part of the query that references the CTE name to perform the next step.
- How to prevent infinite loops in recursion? Use a depth counter or
MAXRECURSIONhint. - Can a CTE be used for UPDATE/DELETE? Yes, you can update a table by joining it with a CTE.
- Multiple CTEs in one query? Yes, separate them by commas under one
WITHkeyword. - Nested CTEs? A later CTE can reference an earlier one in the same
WITHblock. - Performance of CTEs? In some engines (like older PostgreSQL), CTEs act as an optimization fence (materialize).
Optimization & Performance (Questions 61–80)
- What is an Execution Plan? A roadmap showing how the DB engine will execute a query (use
EXPLAIN). - Index Seek vs. Index Scan? Seek is fast (finding specific rows); Scan reads the whole index (slower).
- What is a Clustered Index? Determines the physical order of data on disk (one per table).
- Non-Clustered Index? A separate structure with pointers to the data (multiple allowed).
- What is a Covering Index? An index that contains all columns requested by a query.
- Composite Index? An index on multiple columns.
- What is SARGability? “Search ARGumentable”—writing queries so the engine can use indexes (avoiding functions on columns).
- What is Index Fragmentation? When the physical order of index pages doesn’t match the logical order.
- How to handle a slow query? Check execution plan, add indexes, remove
SELECT *, or update statistics. - What are Database Statistics? Metadata about data distribution used by the optimizer to choose a plan.
- What is a Deadlock? When two transactions block each other indefinitely.
- How to prevent deadlocks? Access tables in the same order, keep transactions short.
- What is Isolation Level? Defines how changes made by one transaction are visible to others (e.g., Read Committed).
- Dirty Read? Reading uncommitted data from another transaction.
- Phantom Read? When new rows added by another transaction appear in your range search mid-transaction.
- What is Partitioning? Splitting a large table into smaller physical pieces based on a key (e.g., Year).
- Horizontal vs. Vertical Partitioning? Horizontal splits rows; Vertical splits columns into separate tables.
- What is Sharding? Distributing data across multiple physical database instances.
- What is a Hint? An instruction to the optimizer to use a specific index or join type (e.g.,
/*+ INDEX(t1) */). - What is Parameter Sniffing? When the engine creates an execution plan based on specific parameters that may not be optimal for others.
Programmability & Design (Questions 81–100)
- Stored Procedure vs. Function? Procedures can modify data and return multiple values; Functions must return a value and are “read-only.”
- What is a Trigger? Code that executes automatically in response to an event (INSERT/UPDATE/DELETE).
- What is a View? A virtual table based on a stored query.
- Materialized View? A view that physically stores data for performance; requires refreshing.
- What is Normalization? Organizing data to reduce redundancy (1NF, 2NF, 3NF).
- What is Denormalization? Adding redundancy to improve read performance (common in Data Warehousing).
- Star Schema vs. Snowflake Schema? Star has a central fact table with flat dimensions; Snowflake normalizes dimensions.
- What is a Surrogate Key? An artificial unique identifier (like an Identity column).
- What is a Cursor? A mechanism to process query results one row at a time (generally avoided for performance).
- What is an Upsert (MERGE)? A command that inserts a row if it doesn’t exist or updates it if it does.
- TRUNCATE vs. DELETE?
TRUNCATEis faster, DDL, and removes all rows;DELETEis DML, can be filtered, and is logged. - DROP vs. TRUNCATE?
DROPremoves the table structure;TRUNCATEonly removes the data. - What is an Identity/Sequence? Auto-generating numbers for primary keys.
- What is Row-Level Security (RLS)? Restricting which rows a user can see based on their identity.
- What is Dynamic SQL? Constructing SQL queries as strings at runtime (risk of SQL injection).
- How to prevent SQL Injection? Use Parameterized Queries or Prepared Statements.
- What is Data Redundancy? Storing the same data in multiple places leads to inconsistency.
- What is an OLTP system? Online Transaction Processing (fast, frequent updates, e.g., Banking).
- What is an OLAP system? Online Analytical Processing (complex queries, large volumes, e.g., Data Warehousing).
- What is a Data Warehouse? A central repository for integrated data from one or more sources for analysis.
Conclusion:
Answering advanced SQL interview questions is about demonstrating that you can protect the database’s health while delivering complex business insights. Your goal is to show that you understand the mechanics beneath the surface of T-SQL.
Master these concepts, and you won’t just pass the interview—you’ll set the standard for the entire team. Good luck!
You may also like the following articles:
After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a Microsoft MVP. Check out more here.