Jump to section
- Basic SQL Questions (25)
- Intermediate SQL Questions (25)
- Advanced SQL Questions (25)
- Practical Query Challenges (20)
- Database Design Questions (15)
- Performance & Optimization Questions (15)
- Top 15 Recommended for MockIF Page (8)
- Easy Level (16)
- Medium Level (16)
- Window Function Deep Dive (11)
- Facebook (3)
- Amazon (3)
- Google (3)
- Advanced SQL Concepts (18)
- Advanced Practical Challenges (10)
- FAQ
SQL interview questions test your ability to write queries, design schemas, and optimize database performance. Interviewers evaluate your command of joins, subqueries, window functions, indexing strategies, and normalization. These questions appear in interviews for backend engineers, data engineers, data analysts, and any role that involves working with relational databases.
Basic SQL Questions (25)
What is SQL and what is it used for?
What they're really asking
This tests basic SQL knowledge and whether you understand SQL's role in data management. The interviewer wants to see if you can explain SQL's purpose clearly and distinguish it from other programming languages.
How you'll be scored
Gives a vague answer like 'SQL is for databases' without explaining what it actually does.
Correctly identifies SQL as a query language for relational databases with basic examples.
Explains SQL's declarative nature, mentions key operations, and demonstrates understanding of its role in data management workflows.
How to structure your answer
- Define what SQL stands for and its fundamental purpose.
- Explain the declarative nature of SQL.
- List the main categories of operations SQL handles.
- Give concrete examples of common SQL use cases.
- Mention SQL's role in database management systems.
Key points to hit
- SQL is declarative, meaning you specify what you want, not how to get it.
- SQL operates on sets of data, not individual records like procedural languages.
- SQL is standardized across different database systems with vendor-specific extensions.
- SQL handles both data definition (structure) and data manipulation (queries)
Common mistakes
- Confusing SQL with procedural programming languages.
- Not mentioning that SQL works with relational data specifically.
Sample answer
SQL stands for Structured Query Language, and it's a declarative language designed specifically for managing data in relational databases. Unlike procedural languages where you write step-by-step instructions, with SQL you describe what data you want and the database engine figures out how to retrieve it efficiently.
SQL handles four main types of operations: defining database structure with CREATE TABLE, manipulating data with INSERT and UPDATE, querying data with SELECT, and controlling access with GRANT statements. It's used everywhere from web applications querying user data to data analysts generating business reports.
How to level up
- Mention SQL's set-based operations and how they differ from row-by-row processing.
- Discuss how SQL optimization works at the engine level.
- Reference SQL standards like ANSI SQL and common extensions.
Follow-up questions to expect
- What are some differences between SQL and NoSQL databases?
- Can you explain what makes SQL declarative versus imperative?
- What SQL dialect have you worked with most?
What are the different types of SQL commands (DDL, DML, DCL, TCL)?
What they're really asking
This tests whether you understand SQL's organizational structure and can categorize different SQL statements by their purpose. The interviewer wants to see if you know when to use each command type.
How you'll be scored
Lists some command types but can't explain what they do or gives incorrect examples.
Correctly identifies the four types with basic examples of each category.
Explains all four types with specific examples and demonstrates understanding of when each type is used in database workflows.
How to structure your answer
- Define DDL and explain its role in database structure.
- Explain DML and its data manipulation purpose.
- Describe DCL and its security/access control function.
- Cover TCL and transaction management.
- Give specific SQL statement examples for each category.
Key points to hit
- DDL (Data Definition Language) creates and modifies database structure with commands like CREATE, ALTER, DROP.
- DML (Data Manipulation Language) works with data itself using SELECT, INSERT, UPDATE, DELETE.
- DCL (Data Control Language) manages permissions and access with GRANT and REVOKE.
- TCL (Transaction Control Language) handles transaction boundaries with COMMIT, ROLLBACK, SAVEPOINT.
Common mistakes
- Mixing up which commands belong to which category, especially SELECT in DML.
- Forgetting TCL entirely or not understanding transaction concepts.
Sample answer
SQL commands are organized into four main categories based on their function. DDL or Data Definition Language includes CREATE, ALTER, and DROP statements that define database structure like tables and indexes. DML or Data Manipulation Language covers SELECT, INSERT, UPDATE, and DELETE for working with actual data.
DCL or Data Control Language handles security with GRANT and REVOKE to manage user permissions. Finally, TCL or Transaction Control Language manages transactions using COMMIT to save changes, ROLLBACK to undo them, and SAVEPOINT for partial rollbacks.
How to level up
- Explain how these categories map to different database privileges and user roles.
- Mention that some operations like TRUNCATE can be DDL even though they affect data.
- Discuss how transaction commands interact with auto-commit settings.
Follow-up questions to expect
- Why is TRUNCATE considered DDL instead of DML?
- What happens if you don't explicitly use COMMIT in a transaction?
- How do database permissions typically align with these command categories?
What is the difference between WHERE and HAVING clauses?
What they're really asking
This tests understanding of SQL execution order and filtering logic. The interviewer wants to see if you know when each clause runs and can choose the right one for different filtering scenarios.
How you'll be scored
Can't explain when to use each clause or incorrectly states they're interchangeable.
Correctly states WHERE filters rows and HAVING filters groups with basic examples.
Explains execution order, performance implications, and demonstrates understanding with specific query scenarios.
How to structure your answer
- Explain WHERE clause timing and purpose in query execution.
- Describe HAVING clause and its relationship to GROUP BY.
- Compare performance implications of each approach.
- Show concrete examples of when to use each.
- Mention execution order and why it matters.
Key points to hit
- WHERE filters individual rows before grouping occurs, making it more efficient for row-level conditions.
- HAVING filters groups after GROUP BY executes and can use aggregate functions in conditions.
- Query execution order is FROM โ WHERE โ GROUP BY โ HAVING โ SELECT โ ORDER BY.
- Using WHERE instead of HAVING when possible reduces data processed during grouping.
Common mistakes
- Trying to use aggregate functions in WHERE clause.
- Using HAVING for simple row-level filtering instead of WHERE.
Sample answer
WHERE and HAVING both filter data, but they work at different stages of query execution. WHERE filters individual rows before any grouping happens, so it's more efficient because it reduces the dataset early. HAVING filters groups after GROUP BY executes, which means it can use aggregate functions like COUNT or SUM in its conditions.
For example, WHERE department = 'Sales' filters rows before grouping, while HAVING COUNT(*) > 5 filters groups after they're formed. Always use WHERE for row-level filtering because it's faster than processing all data and filtering groups later.
How to level up
- Explain how query optimizers can sometimes push down conditions from HAVING to WHERE.
- Discuss index usage differences between WHERE and HAVING conditions.
- Mention that WHERE conditions can often use indexes while HAVING typically cannot.
Follow-up questions to expect
- Can you write a query that needs both WHERE and HAVING?
- What happens if you try to use an aggregate function in a WHERE clause?
- How does the query optimizer handle these different filtering approaches?
What is a PRIMARY KEY? How does it differ from a UNIQUE KEY?
What they're really asking
This tests understanding of key constraints and data integrity concepts. The interviewer wants to see if you know how these constraints enforce data quality and their practical implications.
How you'll be scored
Gives basic definitions without explaining uniqueness, nullability, or practical differences.
Correctly explains both constraints and mentions key differences like null handling.
Explains constraints, discusses implementation details, indexing implications, and demonstrates understanding of when to use each.
How to structure your answer
- Define PRIMARY KEY and its core characteristics.
- Explain UNIQUE KEY and its properties.
- Compare null handling between the two constraint types.
- Discuss indexing and performance implications.
- Explain when to choose one over the other.
Key points to hit
- PRIMARY KEY uniquely identifies each row, automatically creates a clustered index, and cannot contain nulls.
- UNIQUE KEY enforces uniqueness but allows one null value per column (in most databases)
- A table can have only one PRIMARY KEY but multiple UNIQUE constraints.
- Both constraints automatically create indexes, but PRIMARY KEY typically creates the clustered index.
Common mistakes
- Thinking UNIQUE KEY cannot contain any nulls.
- Not understanding that PRIMARY KEY automatically implies NOT NULL.
Sample answer
A PRIMARY KEY is a constraint that uniquely identifies each row in a table and cannot contain null values. It automatically creates a clustered index and each table can have only one.
A UNIQUE KEY also enforces uniqueness but allows one null value per column in most database systems, and you can have multiple UNIQUE constraints per table. The main differences are that PRIMARY KEY implies NOT NULL automatically and typically determines the physical storage order through the clustered index, while UNIQUE keys create non-clustered indexes.
You'd use PRIMARY KEY for the main identifier like customer_id, and UNIQUE for alternate identifiers like email addresses.
How to level up
- Explain composite keys and how uniqueness works across multiple columns.
- Discuss clustered vs non-clustered index implications for query performance.
- Mention how foreign keys typically reference primary keys rather than unique keys.
Follow-up questions to expect
- Can you have a composite PRIMARY KEY? How does that work?
- What happens when you try to insert a duplicate value into a UNIQUE column?
- How do these constraints affect INSERT and UPDATE performance?
What is a FOREIGN KEY and how does it enforce referential integrity?
What they're really asking
This tests understanding of referential integrity and how databases maintain data consistency across related tables. The interviewer wants to see if you understand relationship enforcement and cascading behaviors.
How you'll be scored
Gives a basic definition without explaining referential integrity or practical enforcement.
Correctly explains foreign keys reference other tables and mentions basic integrity checks.
Explains referential integrity, discusses cascade options, and demonstrates understanding of relationship enforcement and performance implications.
How to structure your answer
- Define FOREIGN KEY and its relationship purpose.
- Explain referential integrity and what it prevents.
- Describe cascade options and their behaviors.
- Discuss performance implications of foreign key checks.
- Give concrete examples of foreign key relationships.
Key points to hit
- FOREIGN KEY creates a link between tables by referencing the PRIMARY KEY or UNIQUE KEY of another table.
- Referential integrity prevents orphaned records by ensuring referenced values actually exist.
- Cascade options control what happens when referenced records are updated or deleted.
- Foreign key constraints add overhead to INSERT, UPDATE, and DELETE operations due to integrity checks.
Common mistakes
- Not understanding that foreign keys must reference PRIMARY or UNIQUE keys.
- Forgetting that foreign key constraints can impact performance on data modifications.
Sample answer
A FOREIGN KEY is a constraint that creates a relationship between two tables by ensuring values in one table match existing values in another table's PRIMARY or UNIQUE key. It enforces referential integrity, which means you can't insert an order with a customer_id that doesn't exist in the customers table, preventing orphaned records.
Foreign keys support cascade options like CASCADE DELETE, which automatically removes related records when the parent is deleted, or CASCADE UPDATE, which updates foreign key values when the referenced primary key changes. This constraint adds some overhead to data modifications because the database must verify relationships, but it's essential for maintaining data consistency.
How to level up
- Explain the difference between CASCADE, SET NULL, and RESTRICT options for updates and deletes.
- Discuss how foreign key indexes can improve join performance.
- Mention scenarios where you might temporarily disable foreign key checks during data loading.
Follow-up questions to expect
- What's the difference between CASCADE DELETE and SET NULL?
- How do foreign keys affect the performance of INSERT and DELETE operations?
- Can a foreign key reference a column that's not a primary key?
What are the different types of JOINs in SQL (INNER, LEFT, RIGHT, FULL, CROSS)?
What they're really asking
The interviewer wants to confirm you understand relational data retrieval and can choose the right join type for real queries. They are checking whether you think about edge cases like missing or unmatched rows.
How you'll be scored
Gives a vague or incorrect definition, confuses which table retains rows, or cannot articulate when to use each.
Correctly defines both joins but sticks to textbook language without showing practical judgment on when to pick one over the other.
Explains both joins clearly with a concrete example, addresses NULL behavior in LEFT JOIN results, and demonstrates awareness of performance or data integrity implications.
How to structure your answer
- Define INNER JOIN in one sentence: returns only rows that match in both tables.
- Define LEFT JOIN in one sentence: returns all rows from the left table plus matched rows from the right, filling NULLs where there is no match.
- Give a concrete example using two tables (like orders and customers) to illustrate the difference.
- Explain when you would choose one over the other in a real scenario.
- Mention the NULL behavior that LEFT JOIN introduces and why it matters for downstream logic.
Key points to hit
- INNER JOIN excludes unmatched rows from both sides.
- LEFT JOIN preserves every row from the left table regardless of whether a match exists.
- Unmatched RIGHT side columns come back as NULL in a LEFT JOIN.
- Choosing the wrong join type can silently drop data or inflate result sets.
Common mistakes
- Forgetting to mention that LEFT JOIN produces NULLs for non-matching rows, which can break aggregations or filters if not handled.
- Describing joins without a concrete table example, which makes the explanation feel memorized rather than understood.
Sample answer
An INNER JOIN returns only the rows where both tables have a matching key. So if I join a customers table to an orders table on customer_id, customers with zero orders disappear from the results entirely. A LEFT JOIN keeps every customer and fills in NULLs for the order columns when there is no match.
I reach for LEFT JOIN when I need a complete picture, like generating a report of all customers including those who have never placed an order. The key thing to watch out for is those NULLs.
If you run a SUM on an order amount column after a LEFT JOIN without a COALESCE, you can get unexpected results.
How to level up
- Mention that LEFT JOIN combined with a WHERE clause filtering on the right table (e.g., WHERE right.id IS NULL) is a common pattern for finding orphan or missing records.
- Note that in large datasets, INNER JOIN can be faster because the optimizer discards non-matching rows early, while LEFT JOIN must preserve them.
- Bring up RIGHT JOIN and FULL OUTER JOIN briefly to show you understand the full spectrum, but keep focus on the two that were asked.
Follow-up questions to expect
- How would you find customers who have never placed an order using a join?
- What is the difference between a LEFT JOIN and a subquery with NOT EXISTS?
- How do joins affect query performance on large tables, and what indexing strategies help?
What is the difference between DELETE, TRUNCATE, and DROP?
What they're really asking
This tests basic SQL knowledge of data manipulation commands and their performance characteristics. The interviewer wants to see if you understand the permanent vs temporary nature of these operations and their rollback capabilities.
How you'll be scored
Only knows that all three remove data but can't explain the key differences in scope, rollback capability, or performance.
Correctly explains that DELETE removes rows, TRUNCATE removes all data, and DROP removes the entire table structure.
Explains all three operations plus discusses transaction log behavior, rollback capabilities, and performance implications of each approach.
How to structure your answer
- Define each command's primary purpose.
- Explain what each command affects (rows vs table structure)
- Compare rollback and transaction behavior.
- Mention performance characteristics.
- Give appropriate use cases for each.
Key points to hit
- DELETE removes specific rows and can be rolled back but generates full transaction logs.
- TRUNCATE removes all rows faster with minimal logging but limited rollback in some databases.
- DROP removes the entire table structure and all data permanently.
- Performance differs significantly with TRUNCATE being fastest for removing all data.
Common mistakes
- Saying TRUNCATE can't be rolled back in all database systems when some support it with specific transaction settings.
- Not mentioning that DROP affects table structure, not just data.
Sample answer
DELETE removes specific rows based on a WHERE clause and logs each deletion, so it can be rolled back but is slower for large datasets. TRUNCATE removes all rows from a table much faster because it deallocates data pages with minimal logging, though rollback support varies by database.
DROP completely removes the table structure and all data permanently. For removing a few specific records, I'd use DELETE. For clearing all data quickly, TRUNCATE is most efficient. DROP is only when I need to eliminate the table entirely.
How to level up
- Mention database-specific behaviors like SQL Server's ability to rollback TRUNCATE within explicit transactions.
- Discuss identity column reset behavior with TRUNCATE vs DELETE.
- Explain how foreign key constraints can prevent TRUNCATE but allow DELETE.
Follow-up questions to expect
- What happens to identity columns when you use TRUNCATE vs DELETE?
- Can you TRUNCATE a table that's referenced by a foreign key?
- How would you safely delete a large number of rows without locking the table?
Explain the SELECT statement and common clauses used with it.
What they're really asking
This tests fundamental query structure understanding and clause execution order. The interviewer wants to see if you know how clauses work together and their logical processing sequence.
How you'll be scored
Lists some clauses but doesn't understand their execution order or how they interact with each other.
Correctly explains SELECT retrieves data and names common clauses like WHERE, ORDER BY, and GROUP BY with basic usage.
Explains SELECT with multiple clauses and demonstrates understanding of logical processing order from FROM to ORDER BY with practical examples.
How to structure your answer
- Explain SELECT's core purpose of data retrieval.
- List the main clauses in logical execution order.
- Describe what each clause filters or modifies.
- Show how clauses work together.
- Give a complete example with multiple clauses.
Key points to hit
- SELECT specifies which columns to retrieve from tables.
- Execution order is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY regardless of how you write them.
- WHERE filters individual rows before grouping while HAVING filters groups after aggregation.
- Each clause operates on the results of the previous step in the logical sequence.
Common mistakes
- Writing clauses in the wrong order thinking SQL executes them as written.
- Using aggregate functions in WHERE clause instead of HAVING.
Sample answer
SELECT retrieves specified columns from database tables. The main clauses are FROM to specify tables, WHERE to filter individual rows, GROUP BY to create groups, HAVING to filter those groups, and ORDER BY to sort results.
Even though I write SELECT first, the database actually processes FROM first, then WHERE, then GROUP BY, then HAVING, then SELECT, and finally ORDER BY.
For example, 'SELECT department, COUNT(*) FROM employees WHERE salary > 50000 GROUP BY department HAVING COUNT(*) > 5 ORDER BY COUNT(*) DESC' would find departments with more than 5 high-paid employees.
How to level up
- Understand that SELECT clause aliasing affects later clauses like ORDER BY in most databases.
- Know that some databases allow ORDER BY on columns not in SELECT for non-DISTINCT queries.
- Remember that DISTINCT operates after SELECT but before ORDER BY in the logical sequence.
Follow-up questions to expect
- Why can't you use a column alias from SELECT in the WHERE clause?
- What's the difference between WHERE and HAVING?
- How would you select the top 5 records from a result set?
What are aggregate functions in SQL (COUNT, SUM, AVG, MIN, MAX)?
What they're really asking
This tests understanding of data aggregation and how aggregate functions process groups of rows. The interviewer wants to see if you know when and how to use these functions effectively.
How you'll be scored
Names some functions but doesn't understand they operate on groups of rows or how they handle NULL values.
Correctly explains what each function calculates and that they work on multiple rows to produce single values.
Explains all five functions with NULL handling behavior, shows understanding of their use with GROUP BY, and mentions performance considerations.
How to structure your answer
- Define what aggregate functions do conceptually.
- Explain each function's specific calculation.
- Describe how they handle NULL values.
- Show usage with and without GROUP BY.
- Mention common use cases and performance tips.
Key points to hit
- Aggregate functions process multiple rows to return single summary values.
- COUNT(*) counts all rows including NULLs, while COUNT(column) ignores NULL values.
- SUM, AVG, MIN, and MAX ignore NULL values in their calculations.
- Without GROUP BY, aggregates operate on the entire result set as one group.
Common mistakes
- Thinking COUNT(column) includes NULL values when it actually excludes them.
- Using aggregate functions in WHERE clause instead of HAVING clause.
Sample answer
Aggregate functions calculate summary values from multiple rows. COUNT returns the number of rows, SUM adds numeric values, AVG calculates the mean, MIN finds the smallest value, and MAX finds the largest. They ignore NULLs except COUNT(*) which counts all rows including those with NULLs.
Without GROUP BY, they summarize the entire table into one result. With GROUP BY, they calculate separate results for each group. For example, 'SELECT department, AVG(salary) FROM employees GROUP BY department' gives average salary per department.
How to level up
- Use COUNT(DISTINCT column) to count unique values, which is different from COUNT(column)
- Consider using window functions like SUM() OVER() when you need both detail rows and aggregates.
- Be aware that some databases optimize COUNT(*) better than COUNT(column) for row counting.
Follow-up questions to expect
- What's the difference between COUNT(*) and COUNT(column_name)?
- How would you find the second highest salary using aggregate functions?
- Can you use aggregate functions without GROUP BY?
What is the GROUP BY clause and how is it used?
What they're really asking
This tests understanding of data grouping and how GROUP BY creates subsets for aggregate calculations. The interviewer wants to see if you understand the relationship between grouping and aggregation rules.
How you'll be scored
Knows GROUP BY groups data but doesn't understand the rules about what columns can appear in SELECT or why grouping is needed.
Correctly explains that GROUP BY creates groups for aggregate functions and basic usage with simple examples.
Explains grouping with aggregate functions, understands column selection rules, and knows the difference between WHERE and HAVING with groups.
How to structure your answer
- Explain GROUP BY's purpose of creating subsets.
- Describe how it works with aggregate functions.
- Explain the rule about non-aggregated columns in SELECT.
- Show the difference between WHERE and HAVING.
- Provide practical examples with multiple grouping columns.
Key points to hit
- GROUP BY partitions rows into groups based on specified column values for separate aggregate calculations.
- All non-aggregated columns in SELECT must appear in GROUP BY clause.
- WHERE filters individual rows before grouping occurs, HAVING filters groups after aggregation.
- Multiple columns in GROUP BY create nested groupings with more granular results.
Common mistakes
- Including non-aggregated columns in SELECT that aren't in GROUP BY, which causes errors in most databases.
- Using WHERE instead of HAVING to filter aggregated results.
Sample answer
GROUP BY partitions rows into groups based on column values so aggregate functions calculate separate results for each group instead of the entire table. Every non-aggregated column in SELECT must be included in GROUP BY.
For example, 'SELECT department, job_title, AVG(salary) FROM employees GROUP BY department, job_title' calculates average salary for each department and job combination. I use WHERE to filter rows before grouping and HAVING to filter the grouped results after aggregation.
How to level up
- Understand that GROUP BY with multiple columns creates hierarchical groupings, not separate groupings.
- Know that some databases support GROUP BY column positions like 'GROUP BY 1, 2' referring to SELECT list order.
- Consider using GROUP BY with ROLLUP or CUBE for subtotal calculations in databases that support them.
Follow-up questions to expect
- What happens if you include a non-aggregated column in SELECT but not in GROUP BY?
- When would you use HAVING vs WHERE in a grouped query?
- How would you group by multiple columns and what does that create?
What is the ORDER BY clause? How do you sort ascending vs descending?
What they're really asking
This tests basic result set organization and understanding of sort operations. The interviewer wants to see if you know sorting affects query performance and execution timing.
How you'll be scored
Knows ORDER BY sorts results but doesn't understand ASC/DESC keywords or that sorting impacts performance.
Correctly explains ORDER BY sorts results, uses ASC for ascending and DESC for descending with basic examples.
Explains sorting with multiple columns, understands sort precedence, mentions performance implications, and knows ORDER BY executes last.
How to structure your answer
- Explain ORDER BY's purpose for result organization.
- Show ASC and DESC syntax with examples.
- Demonstrate multi-column sorting and precedence.
- Mention performance considerations.
- Explain ORDER BY's position in query execution order.
Key points to hit
- ORDER BY sorts the final result set and executes after all other clauses except LIMIT/TOP.
- ASC is ascending (default) from lowest to highest, DESC is descending from highest to lowest.
- Multiple columns sort by first column, then second for ties, creating hierarchical ordering.
- Sorting can be expensive for large result sets, especially without supporting indexes.
Common mistakes
- Forgetting that ORDER BY is the last logical operation, so it can reference SELECT aliases.
- Not understanding that multiple columns create nested sorting, not separate sorts.
Sample answer
ORDER BY sorts the final result set in ascending or descending order. ASC sorts from lowest to highest and is the default, while DESC sorts from highest to lowest.
For example, 'ORDER BY salary DESC, last_name ASC' first sorts by salary from highest to lowest, then by last name alphabetically for employees with the same salary. Since ORDER BY executes last, it can use column aliases from the SELECT clause. I'm mindful that sorting large result sets can impact performance, especially without proper indexes.
How to level up
- Remember that ORDER BY can reference columns not in the SELECT list for non-DISTINCT queries.
- Use indexes on ORDER BY columns to improve performance, especially for large tables.
- Know that ORDER BY with LIMIT/TOP can use more efficient execution plans than sorting the entire result set.
Follow-up questions to expect
- How does ORDER BY performance change with and without an index?
- Can you ORDER BY a column that's not in your SELECT list?
- What happens when you ORDER BY multiple columns with different sort directions?
What are NULL values in SQL? How do you handle them?
What they're really asking
This tests understanding of NULL semantics and safe data handling. The interviewer wants to see if you know that NULL comparisons behave differently than regular values and can cause unexpected query results.
How you'll be scored
Says NULL is empty string or zero, doesn't know IS NULL syntax.
Knows NULL represents missing data and uses IS NULL correctly.
Explains NULL comparison semantics, demonstrates COALESCE/ISNULL, discusses three-valued logic.
How to structure your answer
- Define what NULL represents conceptually.
- Explain why normal comparison operators don't work.
- Show IS NULL and IS NOT NULL syntax.
- Demonstrate NULL handling functions.
- Mention impact on JOINs and aggregations.
Key points to hit
- NULL represents unknown or missing data, not zero or empty string.
- Use IS NULL and IS NOT NULL for comparisons because NULL = NULL returns unknown, not true.
- Functions like COALESCE, ISNULL, and NULLIF help handle NULL values in calculations.
- NULLs are ignored by aggregate functions except COUNT(*)
Common mistakes
- Using = NULL or != NULL instead of IS NULL and IS NOT NULL.
- Forgetting that NULL in arithmetic operations makes the entire result NULL.
Sample answer
NULL represents missing or unknown data, not zero or an empty string. The key thing to remember is you can't use regular comparison operators with NULL because NULL = NULL actually returns unknown, not true. Instead, you use IS NULL or IS NOT NULL. For example, WHERE column_name IS NULL finds missing values.
I also use functions like COALESCE to provide default values, like COALESCE(salary, 0) to treat missing salaries as zero in calculations.
How to level up
- Understand three-valued logic where comparisons return true, false, or unknown.
- Know that different databases handle NULL concatenation differently.
- Consider using NOT EXISTS instead of NOT IN when dealing with potential NULLs.
Follow-up questions to expect
- How do NULLs affect JOINs between tables?
- What happens when you use GROUP BY on a column with NULLs?
- Write a query that handles NULL values in a salary calculation.
What is the difference between CHAR and VARCHAR data types?
What they're really asking
This tests basic data type knowledge and storage efficiency understanding. The interviewer wants to see if you know when to use fixed vs variable length strings for performance and storage optimization.
How you'll be scored
Confuses the two or thinks they're interchangeable without considering storage.
Knows CHAR is fixed length, VARCHAR is variable, mentions storage difference.
Explains performance trade-offs, discusses when to use each, mentions padding and truncation behavior.
How to structure your answer
- Define CHAR as fixed-length character storage.
- Define VARCHAR as variable-length with maximum limit.
- Compare storage and performance characteristics.
- Give examples of when to use each.
- Mention potential padding and truncation issues.
Key points to hit
- CHAR stores exactly the specified number of characters, padding with spaces if needed.
- VARCHAR stores only the actual characters plus length information, up to the specified maximum.
- CHAR can be faster for fixed-width data because of predictable storage size.
- VARCHAR saves space for variable-length data but adds slight overhead for length tracking.
Common mistakes
- Thinking VARCHAR is always better because it saves space.
- Not considering that CHAR padding can cause unexpected comparison results.
Sample answer
CHAR is fixed-length storage that always uses exactly the number of characters you specify, padding with spaces if the data is shorter. VARCHAR is variable-length that stores only the actual characters plus a small overhead to track length.
I use CHAR for things like state codes or zip codes where the length is always the same, because it's slightly faster due to predictable storage. VARCHAR is better for names, descriptions, or any text that varies in length because it saves storage space.
How to level up
- Consider that CHAR comparisons might include trailing spaces depending on the database.
- Know that very short VARCHAR fields might actually use more space than CHAR due to length overhead.
Follow-up questions to expect
- When might CHAR actually perform better than VARCHAR?
- How do trailing spaces affect comparisons in CHAR vs VARCHAR?
- What happens if you insert data longer than the specified length?
What are constraints in SQL? Name the different types.
What they're really asking
This tests data integrity knowledge and schema design understanding. The interviewer wants to see if you can prevent bad data from entering the database and understand the relationship between constraints and business rules.
How you'll be scored
Lists only PRIMARY KEY or can't explain what constraints actually do.
Names most constraint types and explains their basic purpose.
Explains all constraint types with examples, discusses constraint timing and cascading actions.
How to structure your answer
- Define constraints as rules that enforce data integrity.
- List the main constraint types.
- Explain each constraint with a practical example.
- Mention when constraints are checked.
- Discuss performance implications.
Key points to hit
- Constraints enforce business rules at the database level to prevent invalid data.
- PRIMARY KEY ensures unique identification of rows and prevents duplicates.
- FOREIGN KEY maintains referential integrity between related tables.
- CHECK constraints validate that data meets specific conditions, UNIQUE prevents duplicates on non-primary columns, NOT NULL requires values.
Common mistakes
- Forgetting that constraints can impact INSERT/UPDATE performance.
- Not understanding that FOREIGN KEY constraints can prevent deletions.
Sample answer
Constraints are rules that enforce data integrity automatically at the database level. The main types are PRIMARY KEY for unique row identification, FOREIGN KEY to maintain relationships between tables, NOT NULL to require values, UNIQUE to prevent duplicates on non-key columns, and CHECK to validate data against business rules.
For example, a CHECK constraint might ensure age is positive, or a FOREIGN KEY ensures every order references a valid customer. They're enforced whenever data is inserted or updated.
How to level up
- Understand CASCADE, RESTRICT, and SET NULL options for foreign key constraints.
- Know that constraints are checked at different times depending on the database and constraint type.
Follow-up questions to expect
- How would you handle constraint violations in application code?
- What's the difference between UNIQUE and PRIMARY KEY constraints?
- When might you temporarily disable a constraint?
What is a VIEW in SQL and how is it used?
What they're really asking
This tests understanding of database abstraction and security concepts. The interviewer wants to see if you know how views provide data access control and query simplification without duplicating data.
How you'll be scored
Thinks a view is a physical table or copies data.
Knows views are virtual tables based on queries, mentions basic uses.
Explains materialized vs standard views, discusses security benefits, mentions performance considerations.
How to structure your answer
- Define a view as a stored query that appears as a table.
- Explain that views don't store data themselves.
- List main use cases like security, simplification, and abstraction.
- Mention updatable vs read-only views.
- Discuss performance implications.
Key points to hit
- Views are virtual tables defined by a SELECT query that don't physically store data.
- They provide security by limiting column and row access without exposing underlying table structure.
- Views simplify complex queries by hiding joins and calculations behind a simple table interface.
- Most views are updatable if they meet certain conditions, but complex views with joins or aggregations are usually read-only.
Common mistakes
- Thinking views store data like tables do.
- Not considering that complex views can hurt performance if not properly indexed.
Sample answer
A VIEW is essentially a saved SELECT query that appears and behaves like a table, but doesn't actually store any data itself. When you query a view, it executes the underlying SELECT statement.
I use views mainly for security to hide sensitive columns from certain users, and for simplification to make complex joins look like simple tables. For example, I might create a view that joins customer and order tables so application developers don't need to write the join logic repeatedly.
How to level up
- Know the difference between standard views and materialized views that do store data.
- Understand that views can be indexed in some databases for better performance.
Follow-up questions to expect
- When would you use a materialized view instead of a regular view?
- Can you always INSERT or UPDATE through a view?
- How do views affect query performance?
What is an ALIAS in SQL and when would you use it?
What they're really asking
This tests code readability and query organization skills. The interviewer wants to see if you write maintainable SQL that others can understand and modify easily.
How you'll be scored
Only knows column aliases or gives vague examples without showing actual syntax.
Shows both column and table aliases with correct syntax and basic use cases.
Demonstrates aliases in complex queries, explains readability benefits, mentions correlation names in subqueries.
How to structure your answer
- Define aliases as alternative names for columns or tables.
- Show syntax for both column and table aliases.
- Explain readability benefits in complex queries.
- Demonstrate use in JOINs and subqueries.
- Mention when aliases are required vs optional.
Key points to hit
- Column aliases rename output columns for clarity, using AS keyword or just a space.
- Table aliases create short names for tables, essential in self-joins and helpful in multi-table queries.
- Aliases make complex queries more readable by shortening long table names and clarifying calculated columns.
- Some situations require aliases, like self-joins or when you need to reference a calculated column.
Common mistakes
- Using confusing single-letter table aliases that hurt readability.
- Forgetting that column aliases can't be used in WHERE clauses because they're applied after filtering.
Sample answer
An ALIAS gives an alternative name to a column or table to make queries more readable. For columns, I write SELECT salary * 12 AS annual_salary to give meaningful names to calculations. For tables, I use aliases like SELECT c.name, o.date FROM customers c JOIN orders o ON c.id = o.customer_id.
This makes the query much cleaner, especially with long table names or when I need to join a table to itself. Table aliases are actually required for self-joins since you need to distinguish between the same table used twice.
How to level up
- Use meaningful alias names that clarify the data, not just single letters.
- Remember that column aliases are useful in ORDER BY clauses and can reference the alias instead of repeating complex expressions.
Follow-up questions to expect
- Show me how you'd use aliases in a self-join query.
- Can you use a column alias in a WHERE clause? Why or why not?
- When are table aliases required versus just helpful?
How do you use the LIKE operator for pattern matching in SQL?
What they're really asking
The interviewer wants to confirm you understand wildcard pattern matching in SQL and can use LIKE with % and _ operators in real queries.
How you'll be scored
Cannot explain the difference between % and _ wildcards or writes incorrect LIKE syntax.
Knows the basic syntax but does not mention case sensitivity, performance implications, or escape characters.
Explains both wildcards clearly, demonstrates multiple patterns, discusses performance impact on large tables, and mentions alternatives like REGEXP.
How to structure your answer
- Define what LIKE does: filters rows where a column matches a specified pattern.
- Explain the two wildcards: % matches zero or more characters, _ matches exactly one character.
- Show practical examples: starts with, ends with, contains, specific position matching.
- Discuss performance: LIKE with a leading wildcard prevents index usage.
Key points to hit
- The % wildcard matches any sequence of characters including empty strings.
- The _ wildcard matches exactly one character, useful for fixed-length patterns.
- Leading wildcards like %term force full table scans because the index cannot help.
- Use ESCAPE to match literal % or _ characters in your data.
Common mistakes
- Forgetting that LIKE with a leading % wildcard is slow on large tables because it forces a full scan.
- Not knowing that LIKE is case-sensitive in some databases (PostgreSQL) but case-insensitive in others (MySQL default collation).
Sample answer
LIKE is used in the WHERE clause to filter rows based on a pattern. The % wildcard matches any number of characters, so WHERE name LIKE Jo% returns John, Joseph, and Jo. The _ wildcard matches exactly one character, so WHERE code LIKE A_B matches A1B and AXB but not AB or AXYZ.
One thing I always keep in mind is that patterns starting with % like %smith cannot use an index, so on a table with millions of rows I would consider a full-text index instead.
How to level up
- In PostgreSQL, use ILIKE for case-insensitive matching instead of converting both sides with LOWER().
- For complex pattern matching beyond LIKE, consider REGEXP or SIMILAR TO depending on your database engine.
Follow-up questions to expect
- How would you search for a literal percentage sign in a column using LIKE?
- What is the performance difference between LIKE abc% and LIKE %abc?
What is the DISTINCT keyword and how does it differ from GROUP BY?
What they're really asking
The interviewer wants to see if you understand the conceptual difference between removing duplicates (DISTINCT) and grouping for aggregation (GROUP BY), and when to use each.
How you'll be scored
Treats DISTINCT and GROUP BY as interchangeable without understanding the different use cases.
Knows DISTINCT removes duplicates and GROUP BY enables aggregation but cannot explain when one is preferable.
Clearly explains both, gives scenarios for each, discusses performance differences, and mentions that GROUP BY without aggregation can behave like DISTINCT.
How to structure your answer
- Define DISTINCT: removes duplicate rows from the result set.
- Define GROUP BY: groups rows by one or more columns, typically used with aggregate functions.
- Explain when each is appropriate.
- Discuss the overlap: GROUP BY without aggregation produces the same result as DISTINCT.
Key points to hit
- DISTINCT removes duplicate rows across all selected columns.
- GROUP BY is designed for aggregation (COUNT, SUM, AVG) but can also deduplicate.
- GROUP BY is required when you need aggregate calculations alongside grouping.
- Performance varies by database, but GROUP BY often uses sorting while DISTINCT may use hashing.
Common mistakes
- Using GROUP BY just to remove duplicates when DISTINCT is cleaner and communicates intent better.
- Forgetting that DISTINCT applies to the entire row, not just one column.
Sample answer
DISTINCT removes duplicate rows from a result set. If I run SELECT DISTINCT city FROM users, I get each city once. GROUP BY groups rows together, usually so I can run an aggregate function on each group.
SELECT city, COUNT(*) FROM users GROUP BY city gives me each city and how many users are in it. The interesting overlap is that GROUP BY without an aggregate function produces the same result as DISTINCT, but I prefer using DISTINCT when I just need unique values because it communicates the intent more clearly.
For aggregation, GROUP BY is the right choice.
How to level up
- Some databases like PostgreSQL support SELECT DISTINCT ON (column) which lets you pick one representative row per group, which is a useful hybrid of both concepts.
- When performance matters, test both approaches. In some databases GROUP BY is faster because the optimizer handles it differently.
Follow-up questions to expect
- Can you use DISTINCT with aggregate functions?
- How does DISTINCT interact with ORDER BY?
What is the difference between COUNT(*) and COUNT(column_name)?
What they're really asking
The interviewer is checking whether you understand how NULL values affect aggregate functions, which is a fundamental SQL concept that trips up many developers.
How you'll be scored
Thinks they are identical or cannot explain the NULL handling difference.
Knows COUNT(*) counts all rows and COUNT(column) skips NULLs but cannot explain when this matters practically.
Explains the NULL behavior clearly, gives a practical scenario where the difference matters, and mentions COUNT(DISTINCT column) as a related concept.
How to structure your answer
- Define COUNT(*): counts all rows in the result set regardless of NULL values.
- Define COUNT(column_name): counts only non-NULL values in that specific column.
- Give a practical example where they return different numbers.
- Mention COUNT(DISTINCT column) as a useful variant.
Key points to hit
- COUNT(*) counts all rows, including those with NULL values in any column.
- COUNT(column_name) ignores rows where that column is NULL.
- This difference is critical when working with optional fields like phone numbers or middle names.
- COUNT(1) behaves identically to COUNT(*) in all modern databases.
Common mistakes
- Assuming COUNT(*) and COUNT(column) always return the same number without considering NULLs.
- Not realizing that COUNT(DISTINCT column) also ignores NULLs.
Sample answer
COUNT(*) counts every row in the result set no matter what. COUNT(column_name) only counts rows where that specific column is not NULL. For example, if I have a users table with 1000 rows but only 800 have a phone number filled in, COUNT(*) returns 1000 and COUNT(phone) returns 800.
This distinction matters a lot when you are reporting on data completeness or when columns are optional. I also use COUNT(DISTINCT column) when I need the number of unique non-NULL values, like counting how many different cities my users come from.
How to level up
- Use the difference between COUNT(*) and COUNT(column) as a quick data quality check: if they differ significantly, you have a lot of NULLs in that column.
- COUNT(*) is often slightly faster than COUNT(column) because the database does not need to check for NULLs.
Follow-up questions to expect
- What does COUNT(DISTINCT column) do and when would you use it?
- How do NULLs affect other aggregate functions like SUM and AVG?
How do you retrieve the top N records in SQL (LIMIT/TOP)?
What they're really asking
The interviewer wants to know if you can limit result sets and whether you understand the syntax differences across database engines.
How you'll be scored
Only knows one database syntax or cannot combine LIMIT with ORDER BY.
Shows correct syntax but only for one database and does not discuss pagination.
Demonstrates syntax across multiple databases (MySQL LIMIT, SQL Server TOP, Oracle FETCH FIRST), combines with ORDER BY, and discusses OFFSET for pagination.
How to structure your answer
- Show the MySQL/PostgreSQL syntax: SELECT ... LIMIT N.
- Show the SQL Server syntax: SELECT TOP N ...
- Show the ANSI SQL standard: FETCH FIRST N ROWS ONLY.
- Explain that ORDER BY is essential to get deterministic results.
- Mention OFFSET for pagination.
Key points to hit
- Always use ORDER BY with LIMIT/TOP, otherwise the "top N" is arbitrary and non-deterministic.
- MySQL/PostgreSQL use LIMIT N, SQL Server uses TOP N, Oracle uses FETCH FIRST N ROWS ONLY.
- OFFSET combined with LIMIT enables pagination: LIMIT 10 OFFSET 20 skips 20 rows and returns the next 10.
- For large offsets, keyset pagination (WHERE id > last_seen_id) is much faster than OFFSET.
Common mistakes
- Using LIMIT without ORDER BY and expecting consistent results across query executions.
- Using large OFFSET values for pagination on big tables, which becomes very slow because the database still reads all skipped rows.
Sample answer
In MySQL and PostgreSQL, I use SELECT * FROM orders ORDER BY created_at DESC LIMIT 10 to get the 10 most recent orders. In SQL Server, the equivalent is SELECT TOP 10 * FROM orders ORDER BY created_at DESC. The ANSI standard syntax is FETCH FIRST 10 ROWS ONLY.
The key thing is always pairing it with ORDER BY, otherwise the database returns an arbitrary set of rows. For pagination, I use LIMIT with OFFSET, like LIMIT 10 OFFSET 20 for page 3.
But for large datasets, I prefer keyset pagination using WHERE id > last_seen_id LIMIT 10 because OFFSET gets progressively slower as you go deeper into the result set.
How to level up
- Keyset pagination (also called cursor-based pagination) is dramatically faster than OFFSET for deep pages because it uses an index scan instead of reading and discarding rows.
- Some databases support LIMIT with ties: FETCH FIRST 10 ROWS WITH TIES returns all rows that tie with the 10th row on the ORDER BY column.
Follow-up questions to expect
- Why does OFFSET-based pagination get slower as the page number increases?
- How would you implement efficient pagination for an API endpoint?
What is the IN operator and how do you use it?
What they're really asking
The interviewer is checking basic SQL syntax knowledge and whether you understand how IN compares to multiple OR conditions and subqueries.
How you'll be scored
Cannot write correct IN syntax or does not know it can be used with subqueries.
Shows correct syntax with a value list but does not discuss subquery usage or performance.
Demonstrates IN with both value lists and subqueries, discusses NULL behavior, and compares performance with EXISTS for large datasets.
How to structure your answer
- Define IN: tests whether a value matches any value in a list or subquery result.
- Show syntax with a value list: WHERE column IN (value1, value2, value3).
- Show syntax with a subquery: WHERE column IN (SELECT ...).
- Discuss when to use IN versus EXISTS for better performance.
Key points to hit
- IN is shorthand for multiple OR conditions: WHERE x IN (1,2,3) equals WHERE x=1 OR x=2 OR x=3.
- IN works with subqueries: WHERE id IN (SELECT user_id FROM orders) finds users who have orders.
- IN does not match NULL values. If NULL is in the list, it is ignored.
- For large subquery results, EXISTS often performs better than IN because it short-circuits.
Common mistakes
- Using IN with a very large value list (thousands of items) which can hit query length limits and perform poorly.
- Not knowing that NOT IN with NULLs in the subquery returns no rows, which is a common and confusing gotcha.
Sample answer
IN tests whether a value matches any item in a list. I can use it with literal values like WHERE status IN (active, pending, review) which is cleaner than writing three OR conditions. I also use it with subqueries, like WHERE user_id IN (SELECT user_id FROM premium_users) to filter by users in another table.
One important gotcha is NULL handling: if the subquery returns any NULL values and you use NOT IN, you get zero results because NULL comparisons are unknown. In that case I switch to NOT EXISTS which handles NULLs correctly.
For very large lists, EXISTS also tends to perform better because it stops scanning as soon as it finds a match.
How to level up
- The NOT IN with NULL trap is one of the most common SQL bugs. Always use NOT EXISTS or add WHERE column IS NOT NULL to the subquery.
- When the IN list is generated dynamically in application code, consider using a temporary table or CTE instead of building a massive IN clause.
Follow-up questions to expect
- What happens with NOT IN when the subquery contains NULL values?
- When would you choose EXISTS over IN?
What is the BETWEEN operator?
What they're really asking
This tests basic SQL operator knowledge and syntax understanding. The interviewer wants to see if you know how BETWEEN works with inclusive boundaries and can identify when to use it versus other comparison operators.
How you'll be scored
Gives a vague definition without mentioning that BETWEEN is inclusive on both ends or shows incorrect syntax.
Correctly explains BETWEEN as inclusive range checking with proper syntax example.
Explains BETWEEN with correct syntax, mentions inclusive boundaries, discusses performance compared to >= AND <=, and notes potential gotchas with different data types.
How to structure your answer
- Define what BETWEEN does.
- Show the basic syntax.
- Explain that it's inclusive on both ends.
- Give a concrete example.
- Mention when you'd use it versus other operators.
Key points to hit
- BETWEEN is inclusive of both boundary values, unlike some other programming languages.
- Syntax is 'column BETWEEN value1 AND value2' where value1 should be less than value2.
- BETWEEN works with numbers, dates, and strings using lexicographic ordering.
- Performance-wise, BETWEEN is equivalent to using >= AND <= but more readable.
Common mistakes
- Thinking BETWEEN excludes the boundary values.
- Not knowing that the first value should be smaller than the second value for expected results.
Sample answer
The BETWEEN operator checks if a value falls within a specified range, and it's inclusive on both ends. The syntax is 'WHERE column BETWEEN value1 AND value2'. For example, 'WHERE age BETWEEN 25 AND 35' returns rows where age is 25, 35, or anything in between. It works with numbers, dates, and even strings. I'd use BETWEEN when I need range filtering because it's more readable than writing 'WHERE age >= 25 AND age <= 35', though they perform identically.
How to level up
- Remember that with strings, BETWEEN uses lexicographic ordering, so 'BETWEEN 'A' AND 'C'' includes 'Apple' but not 'Cat'
- For date ranges, be careful about time components - you might need to use DATE functions or adjust your end date.
Follow-up questions to expect
- How would you handle a case where the first value might be larger than the second value?
- What happens when you use BETWEEN with NULL values?
- Can you rewrite this BETWEEN query using other operators?
How do you insert, update, and delete data in a table?
What they're really asking
This tests fundamental data manipulation language (DML) knowledge and proper syntax for the three core operations that modify data. The interviewer wants to see if you understand transaction implications and can write syntactically correct statements.
How you'll be scored
Shows incorrect syntax or confuses the three operations, missing key components like WHERE clauses for UPDATE/DELETE.
Demonstrates correct basic syntax for INSERT, UPDATE, and DELETE with simple examples.
Shows correct syntax, explains the importance of WHERE clauses for UPDATE/DELETE, discusses transaction safety, and mentions bulk operations or performance considerations.
How to structure your answer
- Show INSERT syntax with both single and multiple row examples.
- Demonstrate UPDATE with proper WHERE clause.
- Show DELETE with WHERE clause and safety considerations.
- Mention transaction context.
- Discuss common safety practices.
Key points to hit
- INSERT can add single rows with VALUES or multiple rows from SELECT queries.
- UPDATE and DELETE should almost always include WHERE clauses to avoid modifying entire tables.
- All three operations are transactional and can be rolled back if wrapped in a transaction.
- DELETE removes rows but keeps table structure, unlike DROP or TRUNCATE.
Common mistakes
- Forgetting WHERE clauses in UPDATE or DELETE, which would modify every row in the table.
- Not understanding that DELETE without WHERE removes all data from the table.
Sample answer
For INSERT, I use 'INSERT INTO table (col1, col2) VALUES (val1, val2)' for single rows or 'INSERT INTO table SELECT...' for multiple rows. UPDATE uses 'UPDATE table SET col1 = value WHERE condition' - the WHERE clause is critical to avoid updating every row.
DELETE uses 'DELETE FROM table WHERE condition' - again, WHERE is essential for safety. I always test these with SELECT first using the same WHERE clause to see what rows would be affected, and I prefer running them in transactions so I can rollback if something goes wrong.
How to level up
- Use INSERT... ON DUPLICATE KEY UPDATE for MySQL or INSERT... ON CONFLICT for PostgreSQL to handle potential duplicates gracefully.
- Consider using LIMIT with UPDATE/DELETE in MySQL to prevent accidentally modifying too many rows.
Follow-up questions to expect
- How would you safely update a large table without locking it for too long?
- What's the difference between DELETE, DROP, and TRUNCATE?
- How would you insert data from one table into another with some transformation?
How do you create a table and add/remove columns?
What they're really asking
This tests Data Definition Language (DDL) knowledge and schema management skills. The interviewer wants to see if you understand table creation syntax, column specifications, and safe schema modification practices.
How you'll be scored
Shows basic CREATE TABLE syntax but misses important details like data types, constraints, or doesn't know ALTER TABLE syntax.
Demonstrates correct CREATE TABLE and ALTER TABLE syntax with proper data types and basic constraints.
Shows comprehensive DDL knowledge including data types, constraints, indexes, discusses safe schema changes in production, and mentions migration strategies.
How to structure your answer
- Show CREATE TABLE syntax with data types and constraints.
- Demonstrate ALTER TABLE for adding columns.
- Show how to drop columns safely.
- Discuss considerations for production environments.
- Mention indexing as part of table design.
Key points to hit
- CREATE TABLE requires specifying appropriate data types and constraints like NOT NULL, PRIMARY KEY, FOREIGN KEY.
- ALTER TABLE ADD COLUMN is generally safe, but dropping columns can break applications.
- Adding columns with NOT NULL requires either a DEFAULT value or careful planning.
- Schema changes in production require coordination with application deployments.
Common mistakes
- Not specifying appropriate data types or constraints when creating tables.
- Dropping columns in production without ensuring no application code depends on them.
Sample answer
To create a table, I use CREATE TABLE with column definitions: 'CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100) NOT NULL, email VARCHAR(255) UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)'. For adding columns, I use 'ALTER TABLE users ADD COLUMN phone VARCHAR(20)'. To remove columns, 'ALTER TABLE users DROP COLUMN phone'.
In production, I'm very careful about schema changes - I always check that no application code references columns I'm dropping, and I prefer adding nullable columns first, then populating them and adding constraints later.
How to level up
- Consider adding new columns as nullable first, then populate them and add NOT NULL constraints in a separate migration to avoid locking issues.
- When dropping columns, consider a multi-step process: stop using the column in code, deploy, then drop the column.
Follow-up questions to expect
- How would you add a NOT NULL column to a table that already has millions of rows?
- What's the difference between DROP COLUMN and setting a column to NULL?
- How do you handle foreign key constraints when dropping columns?
What is the difference between SQL and NoSQL databases?
What they're really asking
This tests understanding of different database paradigms and when to choose relational versus non-relational approaches. The interviewer wants to see if you can articulate the trade-offs and use cases for each type.
How you'll be scored
Gives vague differences like 'SQL has tables, NoSQL doesn't' without understanding the deeper architectural and use case differences.
Correctly identifies key differences like ACID properties, schema flexibility, and scaling approaches with basic examples.
Demonstrates deep understanding of trade-offs, discusses CAP theorem implications, provides specific use cases for each, and understands when to choose one over the other based on business requirements.
How to structure your answer
- Define SQL databases with key characteristics.
- Define NoSQL databases and main types.
- Compare ACID properties and consistency models.
- Discuss scaling approaches.
- Provide specific use cases for each.
Key points to hit
- SQL databases enforce ACID properties and have rigid schemas, while NoSQL databases often trade some consistency for flexibility and scalability.
- SQL databases typically scale vertically, while NoSQL databases are designed for horizontal scaling.
- NoSQL includes document stores (MongoDB), key-value stores (Redis), column-family (Cassandra), and graph databases (Neo4j)
- Choice depends on data structure, consistency requirements, scale, and query patterns.
Common mistakes
- Thinking NoSQL is always better for large scale or that SQL databases can't handle big data.
- Not understanding that different NoSQL types serve different use cases.
Sample answer
SQL databases like PostgreSQL use structured tables with enforced schemas and ACID transactions, making them great for applications needing strong consistency like financial systems. NoSQL databases sacrifice some of these guarantees for flexibility and horizontal scaling. For example, MongoDB stores documents without fixed schemas, perfect for content management where data structure varies.
Redis is a key-value store excellent for caching. The choice depends on your needs - if you need complex queries and transactions, choose SQL. If you need to scale horizontally with flexible data structures, consider NoSQL. Many modern applications actually use both.
How to level up
- Understand the CAP theorem - you can't have consistency, availability, and partition tolerance all at once, which explains many NoSQL design decisions.
- NewSQL databases like CockroachDB try to combine SQL's ACID properties with NoSQL's scalability.
Follow-up questions to expect
- When would you choose a document database over a relational database for a new project?
- How do you handle transactions in a NoSQL environment?
- What are the challenges of migrating from SQL to NoSQL?
Intermediate SQL Questions (25)
What is a subquery? What are correlated vs non-correlated subqueries?
What they're really asking
This tests understanding of query nesting, execution context, and the performance implications of different subquery types. The interviewer wants to see if you can identify when subqueries are correlated and understand their performance characteristics.
How you'll be scored
Defines subquery as 'query inside another query' but can't distinguish between correlated and non-correlated types or understand performance implications.
Correctly explains both types with basic examples and understands that correlated subqueries execute once per outer row.
Provides clear examples of both types, explains execution differences, discusses performance implications, and knows when to use subqueries versus JOINs or window functions.
How to structure your answer
- Define what a subquery is.
- Explain non-correlated subqueries with example.
- Explain correlated subqueries with example.
- Compare performance characteristics.
- Discuss alternatives like JOINs or EXISTS.
Key points to hit
- Non-correlated subqueries execute once and return results used by the outer query.
- Correlated subqueries reference columns from the outer query and execute once for each outer row.
- Correlated subqueries are generally slower because they can't be optimized as easily.
- EXISTS is often more efficient than IN with subqueries, especially when checking for presence rather than specific values.
Common mistakes
- Not understanding that correlated subqueries execute multiple times, leading to performance problems.
- Using IN with subqueries when EXISTS would be more appropriate and efficient.
Sample answer
A subquery is a query nested inside another query. Non-correlated subqueries are independent - like 'SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments WHERE budget > 100000)'. The inner query runs once.
Correlated subqueries reference the outer query - like 'SELECT * FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department = e.department)'. This inner query runs once per outer row, making it potentially slow.
I prefer EXISTS over IN for correlated subqueries when checking existence, and I consider JOINs or window functions as alternatives for better performance.
How to level up
- Use EXISTS instead of IN when you only care about existence, not the actual values returned.
- Modern query optimizers can sometimes transform correlated subqueries into JOINs automatically, but it's better to write efficient queries from the start.
Follow-up questions to expect
- When would you use a subquery instead of a JOIN?
- How would you optimize a slow correlated subquery?
- What's the difference between EXISTS and IN with subqueries?
What is the difference between UNION and UNION ALL?
What they're really asking
This tests your understanding of set operations and query performance optimization. The interviewer wants to see if you know when duplicate elimination matters and can predict query performance implications.
How you'll be scored
Only mentions that UNION removes duplicates without understanding performance impact or when to use each.
Correctly explains duplicate handling and mentions performance difference between the two operations.
Explains duplicate handling, performance trade-offs, discusses when each is appropriate, and mentions internal sorting behavior.
How to structure your answer
- Define what each operation does with duplicates.
- Explain the performance difference and why it occurs.
- Give concrete examples of when to use each.
- Mention any sorting behavior implications.
Key points to hit
- UNION removes duplicate rows by performing an implicit DISTINCT operation, while UNION ALL preserves all rows including duplicates.
- UNION ALL is faster because it doesn't need to sort and compare rows to eliminate duplicates.
- Use UNION when data integrity requires no duplicates, UNION ALL when you know duplicates don't exist or need them preserved.
- UNION typically sorts results as part of duplicate elimination, while UNION ALL preserves original order.
Common mistakes
- Forgetting that UNION has performance overhead due to duplicate checking and sorting operations.
- Not mentioning when you'd actually choose one over the other in real scenarios.
Sample answer
UNION removes duplicate rows from the combined result set, essentially performing a DISTINCT operation, while UNION ALL keeps all rows including duplicates. The key difference is performance - UNION ALL is significantly faster because it just appends the results without sorting or comparing rows.
I'd use UNION when combining data where duplicates would cause business logic issues, like merging customer lists from different systems. But if I know the data sets don't overlap or I actually want duplicates preserved, UNION ALL is the better choice since it avoids the expensive deduplication step.
How to level up
- Mention that UNION can be replaced with UNION ALL plus DISTINCT for more control over the deduplication process.
- Discuss how query planners handle these operations differently and impact on memory usage.
- Note that column names and data types must match between the SELECT statements being unioned.
Follow-up questions to expect
- How would you optimize a query that uses multiple UNION operations?
- What happens if the column types don't match exactly in a UNION?
- Can you write a query that demonstrates both UNION and UNION ALL with sample data?
What is a CTE (Common Table Expression) and when would you use it?
What they're really asking
This tests your knowledge of advanced SQL query structure and code organization. The interviewer wants to see if you understand query readability, recursive operations, and when CTEs improve maintainability over subqueries.
How you'll be scored
Gives a vague definition without concrete use cases or understanding of when CTEs are better than alternatives.
Correctly defines CTE syntax and mentions improved readability compared to nested subqueries.
Explains CTE syntax, discusses recursive CTEs, compares performance with subqueries, and gives specific use cases like hierarchical data.
How to structure your answer
- Define what a CTE is and its basic syntax.
- Explain the main benefits over subqueries or temporary tables.
- Give examples of common use cases.
- Mention recursive CTEs if applicable.
Key points to hit
- A CTE is a named temporary result set defined using WITH clause that exists only for the duration of a single query.
- CTEs improve query readability by breaking complex logic into named, reusable components rather than nested subqueries.
- Recursive CTEs can reference themselves, making them ideal for hierarchical data like organizational charts or category trees.
- CTEs are evaluated once and can be referenced multiple times in the main query, though they're not cached like temp tables.
Common mistakes
- Confusing CTEs with temporary tables or thinking they persist beyond the query execution.
- Not mentioning recursive CTEs when discussing advanced use cases.
Sample answer
A CTE or Common Table Expression is a named temporary result set that you define using the WITH clause before your main query. It's like creating a virtual table that only exists for that query execution.
I use CTEs primarily to make complex queries more readable - instead of having deeply nested subqueries that are hard to debug, I can break the logic into named steps.
For example, if I need to calculate running totals and then filter on them, I'd create a CTE for the running totals calculation and then reference it in my main SELECT. CTEs are also essential for recursive operations, like traversing hierarchical data structures or organizational reporting chains.
How to level up
- Discuss the difference between CTEs and derived tables in terms of readability and reusability within the same query.
- Mention that CTEs can sometimes be less performant than well-written subqueries due to optimization differences.
- Explain how recursive CTEs work with UNION ALL to build hierarchical result sets.
Follow-up questions to expect
- Can you write a recursive CTE to find all employees under a specific manager?
- When would you choose a CTE over a temporary table or subquery?
- How do CTEs perform compared to subqueries in terms of execution plans?
Explain the difference between RANK(), DENSE_RANK(), and ROW_NUMBER().
What they're really asking
This tests your understanding of window function ranking behavior and how ties are handled. The interviewer wants to see if you can predict result sets accurately and choose the right ranking function for business requirements.
How you'll be scored
Provides incorrect or confused explanations of how these functions handle ties and numbering.
Correctly explains the basic difference in how each function assigns numbers to tied values.
Accurately describes tie handling, gives examples with sample data, and discusses when to use each function based on business needs.
How to structure your answer
- Define how each function handles tied values.
- Show concrete examples with sample data.
- Explain when you'd choose each function.
- Mention the sequential numbering behavior.
Key points to hit
- ROW_NUMBER() assigns unique sequential numbers even for tied values, essentially breaking ties arbitrarily.
- RANK() gives tied values the same rank but skips subsequent numbers (1,2,2,4,5 for a tie at position 2)
- DENSE_RANK() gives tied values the same rank without skipping numbers (1,2,2,3,4 for a tie at position 2)
- Choose based on business needs: ROW_NUMBER() for unique identifiers, RANK() for competition-style ranking, DENSE_RANK() for grade-level ranking.
Common mistakes
- Confusing which functions skip numbers after ties and which don't.
- Not understanding that ROW_NUMBER() breaks ties arbitrarily and isn't deterministic without ORDER BY.
Sample answer
The key difference is how they handle tied values. ROW_NUMBER() always assigns unique sequential numbers, so even if two rows have the same value, they get different numbers like 1,2,3,4.
RANK() gives tied values the same number but then skips ahead - so if two people tie for second place, they both get rank 2, but the next person gets rank 4.
DENSE_RANK() also gives ties the same number but doesn't skip - those same two people would get rank 2, and the next person gets rank 3. I'd use ROW_NUMBER() when I need unique identifiers, RANK() for sports-style competitions where ties matter, and DENSE_RANK() when I want consecutive ranking levels like grade classifications.
How to level up
- Mention that ROW_NUMBER() results can be non-deterministic with ties unless you include tie-breaking columns in ORDER BY.
- Discuss how these functions interact with PARTITION BY to reset rankings within groups.
- Note the performance implications - all three functions require sorting the data.
Follow-up questions to expect
- Write a query showing all three functions on the same dataset with ties.
- How would you find just the top 3 unique salary levels using these functions?
- What happens if you don't include an ORDER BY clause with these ranking functions?
What are window functions in SQL? Give examples.
What they're really asking
This tests your knowledge of advanced SQL analytics and whether you understand the difference between aggregate functions and window functions. The interviewer wants to see if you can write queries that perform row-level calculations while maintaining detail.
How you'll be scored
Confuses window functions with aggregate functions or can't explain when you'd use them instead of GROUP BY.
Correctly defines window functions and gives basic examples like SUM() OVER() or ROW_NUMBER().
Explains the OVER() clause, discusses partitioning and framing, gives multiple practical examples, and contrasts with aggregate functions.
How to structure your answer
- Define what window functions do and the OVER() clause.
- Explain how they differ from regular aggregate functions.
- Give concrete examples with different window function types.
- Mention partitioning and ordering concepts.
Key points to hit
- Window functions perform calculations across related rows while returning results for each individual row, unlike aggregate functions that collapse rows.
- The OVER() clause defines the window of rows for the calculation, including optional PARTITION BY and ORDER BY.
- Common types include ranking functions (ROW_NUMBER, RANK), aggregate functions (SUM, AVG OVER), and offset functions (LAG, LEAD)
- Window functions allow you to calculate running totals, moving averages, and row comparisons without self-joins or subqueries.
Common mistakes
- Confusing window functions with GROUP BY aggregations - window functions don't collapse rows into groups.
- Forgetting that window functions execute after WHERE but before ORDER BY in query processing order.
Sample answer
Window functions perform calculations across a set of related rows but return a result for each individual row, unlike regular aggregates that group rows together. They use the OVER() clause to define their 'window' of calculation.
For example, SUM(salary) OVER() gives you the total of all salaries on each row, while SUM(salary) OVER(PARTITION BY department) gives you the department total on each row. I use them frequently for running totals like SUM(amount) OVER(ORDER BY date), comparing rows with LAG() and LEAD(), or calculating percentiles with NTILE().
They're incredibly powerful because you can do complex analytics while keeping all your detail rows intact.
How to level up
- Discuss window framing with ROWS BETWEEN and RANGE BETWEEN for precise control over which rows are included.
- Mention that window functions can be expensive and might benefit from appropriate indexing on PARTITION BY and ORDER BY columns.
- Explain how multiple window functions in the same query can share window definitions using the WINDOW clause.
Follow-up questions to expect
- Write a query to calculate each employee's salary as a percentage of their department total using window functions.
- How would you calculate a 3-month moving average of sales using window functions?
- What's the difference between using ROWS and RANGE in window frame specifications?
How do you find the second (or Nth) highest salary in a table?
What they're really asking
This tests your ability to write complex analytical queries and understand ranking logic. The interviewer wants to see if you can handle common business problems and choose between different approaches based on how duplicates should be handled.
How you'll be scored
Provides incorrect logic or overly complex solutions that don't handle edge cases like ties properly.
Shows a working solution using ranking functions or subqueries but doesn't discuss different approaches for handling ties.
Demonstrates multiple approaches, explains when to use each based on business requirements, and handles edge cases like ties and insufficient data.
How to structure your answer
- Present the main approach using window functions.
- Show alternative methods and when to use them.
- Discuss how to handle ties and edge cases.
- Mention performance considerations.
Key points to hit
- Use DENSE_RANK() when you want the actual Nth distinct salary value, or RANK() when ties should count as multiple positions.
- The OFFSET/LIMIT approach with ORDER BY and subqueries works but is less flexible than window functions.
- Always consider edge cases like fewer than N employees, ties at the Nth position, or NULL salary values.
- Window functions are generally more readable and flexible than correlated subqueries for this type of problem.
Common mistakes
- Using ROW_NUMBER() without considering that ties might exist and should be handled appropriately.
- Not accounting for edge cases like when there are fewer than N distinct salary values in the table.
Sample answer
I'd use window functions for this because they handle ties cleanly and are very readable. For the second highest salary, I'd write: SELECT DISTINCT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM employees) ranked WHERE rank = 2.
I use DENSE_RANK() because I want the second distinct salary value - if multiple people have the highest salary, I still want the next unique amount. For a more general solution, I'd parameterize the rank value. An alternative approach is using OFFSET with ORDER BY, but that gets tricky with ties.
The key decision is whether ties should count as multiple positions or not, which depends on the business requirement.
How to level up
- Discuss the difference between using DENSE_RANK() vs RANK() based on whether ties should affect subsequent rankings.
- Mention handling NULL salaries with appropriate WHERE clauses or NULL handling in the ranking.
- Show how to make the solution generic for any Nth value rather than hardcoding the second highest.
Follow-up questions to expect
- How would you modify this to find the second highest salary within each department?
- What if there are NULL salary values - how does that affect your query?
- Can you write this same query using only subqueries without window functions?
How do you find and remove duplicate rows from a table?
What they're really asking
This tests your ability to identify duplicates using grouping or window functions and safely delete them without losing data. The interviewer wants to see if you understand the difference between finding duplicates and removing them while preserving one copy.
How you'll be scored
Suggests DELETE without a clear strategy for keeping one row, or cannot explain how to identify duplicates in the first place.
Uses GROUP BY with HAVING COUNT(*) > 1 to find duplicates and can describe a deletion approach.
Demonstrates multiple approaches including CTE with ROW_NUMBER for precise deletion, explains why ROW_NUMBER is safer than MIN/MAX for composite duplicates, and discusses prevention strategies.
How to structure your answer
- Explain how to identify duplicates using GROUP BY and HAVING.
- Show the ROW_NUMBER approach with a CTE for safe deletion.
- Discuss which row to keep and how to decide.
- Mention prevention with UNIQUE constraints.
Key points to hit
- GROUP BY with HAVING COUNT(*) > 1 finds which values are duplicated but does not help delete specific rows.
- ROW_NUMBER() OVER (PARTITION BY duplicate_columns ORDER BY id) assigns a number to each copy so you can delete rows where row_num > 1.
- Always test with SELECT before running DELETE to confirm which rows will be removed.
- Adding UNIQUE constraints after cleanup prevents future duplicates.
Common mistakes
- Running DELETE without first verifying which rows will be affected using a SELECT statement.
- Using DELETE with a subquery that accidentally removes all copies instead of keeping one.
Sample answer
I would use a CTE with ROW_NUMBER to handle this safely. First, I assign a row number to each duplicate group: WITH duplicates AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn FROM users) SELECT * FROM duplicates WHERE rn > 1.
Once I verify the results look correct, I change the SELECT to DELETE FROM duplicates WHERE rn > 1. This keeps the row with the lowest id for each email. After cleanup, I would add a UNIQUE constraint on the email column with ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE(email) to prevent future duplicates.
How to level up
- In PostgreSQL you can use DELETE FROM ... USING with a self-join as an alternative to the CTE approach.
- For very large tables, consider batching deletes to avoid long-running transactions and lock contention.
- Use DISTINCT ON in PostgreSQL as a quick way to select one row per duplicate group without a CTE.
Follow-up questions to expect
- How would you handle duplicates across multiple columns instead of just one?
- What if you need to keep the most recent duplicate instead of the oldest?
- How would you deduplicate a table with hundreds of millions of rows efficiently?
What is a self-join and when would you use it?
What they're really asking
This tests whether you understand that a table can be joined to itself and when this pattern solves real problems. The interviewer wants to see if you can model hierarchical or comparative relationships within a single table.
How you'll be scored
Cannot explain when or why you would join a table to itself, or confuses self-join with a regular join.
Correctly explains the concept with a basic example like an employee-manager relationship.
Provides multiple use cases, uses proper table aliasing, and explains how self-joins handle hierarchical data and row comparisons within the same table.
How to structure your answer
- Define what a self-join is and why it requires aliases.
- Explain the employee-manager hierarchy use case.
- Describe comparing rows within the same table.
- Show proper syntax with table aliases.
Key points to hit
- A self-join joins a table to itself using two different aliases so the database treats them as separate tables.
- The most common use case is hierarchical data where a foreign key references the same table, like employee.manager_id referencing employee.id.
- Self-joins are also useful for comparing rows within the same table, such as finding consecutive records or matching pairs.
- You must use aliases because the same table appears twice in the FROM clause.
Common mistakes
- Forgetting to alias the table, which causes ambiguous column reference errors.
- Not handling NULL values in the join column, which would exclude root-level records like top-level managers.
Sample answer
A self-join is when you join a table to itself by giving it two different aliases. The classic example is an employee table where each employee has a manager_id that points back to another employee. The query looks like SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id. I use LEFT JOIN here so employees without a manager, like the CEO, still appear in the results. Another use case is finding pairs within a table, like SELECT a.name, b.name FROM users a JOIN users b ON a.city = b.city AND a.id < b.id to find all pairs of users in the same city without duplicating pairs.
How to level up
- Use LEFT JOIN instead of INNER JOIN when you need to include rows that have no matching partner, such as top-level nodes in a hierarchy.
- For deep hierarchies, recursive CTEs are often cleaner than multiple self-joins.
- Self-joins can be expensive on large tables, so make sure the join columns are indexed.
Follow-up questions to expect
- How would you find all employees who earn more than their manager using a self-join?
- When would a recursive CTE be a better choice than a self-join?
- How would you write a self-join to find consecutive orders from the same customer?
How does the CASE statement work in SQL?
What they're really asking
This tests your ability to implement conditional logic directly in SQL queries. The interviewer wants to see if you understand both simple and searched CASE syntax and can apply them in SELECT, WHERE, and ORDER BY clauses.
How you'll be scored
Can only describe CASE in vague terms without showing correct syntax or practical examples.
Shows correct CASE WHEN syntax with a basic example in a SELECT clause.
Demonstrates both simple and searched CASE forms, uses CASE in multiple clause positions, and explains how it handles NULL and the ELSE fallback.
How to structure your answer
- Explain the two forms of CASE: simple and searched.
- Show CASE usage in a SELECT for value transformation.
- Demonstrate CASE in ORDER BY for custom sorting.
- Explain ELSE and NULL behavior.
Key points to hit
- Simple CASE compares one expression to multiple values: CASE status WHEN 'A' THEN 'Active' WHEN 'I' THEN 'Inactive' END.
- Searched CASE evaluates independent boolean conditions: CASE WHEN salary > 100000 THEN 'High' WHEN salary > 50000 THEN 'Mid' ELSE 'Low' END.
- CASE evaluates conditions in order and returns the first match, so ordering matters for overlapping conditions.
- If no condition matches and there is no ELSE clause, CASE returns NULL.
Common mistakes
- Putting overlapping conditions in the wrong order so the more specific condition never matches.
- Forgetting the END keyword which is required to close every CASE expression.
Sample answer
CASE works like an if-else chain inside your SQL query. There are two forms. The simple form compares one value: CASE status WHEN 'A' THEN 'Active' WHEN 'I' THEN 'Inactive' ELSE 'Unknown' END.
The searched form lets you write any boolean condition: CASE WHEN revenue > 1000000 THEN 'Enterprise' WHEN revenue > 100000 THEN 'Mid-Market' ELSE 'SMB' END AS tier.
You can use CASE in SELECT for computed columns, in ORDER BY for custom sorting like ORDER BY CASE WHEN priority = 'urgent' THEN 1 ELSE 2 END, and even in WHERE clauses. The conditions are evaluated top to bottom and it returns the first match, so put your most specific conditions first.
How to level up
- Use CASE inside aggregate functions for conditional counting: SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) to pivot data without PIVOT.
- In PostgreSQL, COALESCE and NULLIF are shorthand alternatives for simple CASE patterns involving NULLs.
- CASE expressions can be nested, but deeply nested CASE often signals that logic should move to application code or a lookup table.
Follow-up questions to expect
- How would you use CASE inside an aggregate function to create a pivot-style result?
- What is the difference between CASE and COALESCE?
- How would you handle NULL comparisons inside a CASE expression?
What is the difference between EXISTS/NOT EXISTS and IN/NOT IN?
What they're really asking
This tests your understanding of subquery evaluation strategies and NULL handling differences between these operators. The interviewer wants to see if you know when each approach is more appropriate and the critical NULL trap with NOT IN.
How you'll be scored
Says they are interchangeable or cannot explain the difference in how they evaluate subqueries.
Correctly explains that IN checks a list of values while EXISTS checks for row existence, with basic examples.
Highlights the NULL handling difference with NOT IN, discusses performance implications of correlated vs uncorrelated subqueries, and explains when to prefer each approach.
How to structure your answer
- Explain how IN works with a subquery or value list.
- Explain how EXISTS works with a correlated subquery.
- Highlight the critical NOT IN vs NOT EXISTS difference with NULLs.
- Discuss performance considerations.
Key points to hit
- IN compares a value against a list and returns true if any match is found. It works with both value lists and subqueries.
- EXISTS returns true if the correlated subquery returns at least one row, regardless of what columns it returns.
- NOT IN returns no results if any value in the subquery is NULL because NULL comparisons yield UNKNOWN, which breaks the entire condition.
- EXISTS often performs better with large subqueries because it can short-circuit after finding the first matching row.
Common mistakes
- Using NOT IN with a subquery that could return NULL values, which silently returns zero results instead of the expected filtered set.
- Assuming IN and EXISTS always produce the same execution plan without considering data size and indexing.
Sample answer
The biggest practical difference is how they handle NULLs. IN compares your value against a list: SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE active = 1).
EXISTS uses a correlated subquery and just checks if any row comes back: SELECT * FROM orders o WHERE EXISTS (SELECT 1 FROM customers c WHERE c.id = o.customer_id AND c.active = 1). The critical trap is NOT IN.
If even one value in the subquery result is NULL, NOT IN returns zero rows because any comparison with NULL is UNKNOWN. NOT EXISTS does not have this problem. For performance, EXISTS can short-circuit after finding the first match, which helps with large datasets.
I default to EXISTS for correlated checks and IN for small static value lists.
How to level up
- Modern query optimizers in PostgreSQL and SQL Server often rewrite IN as a semi-join, making it equivalent to EXISTS in many cases.
- Always add a NOT NULL filter inside NOT IN subqueries if you cannot guarantee the column has no NULLs.
- For large value lists, consider using a temporary table with a join instead of IN with thousands of literal values.
Follow-up questions to expect
- Can you demonstrate the NULL trap with NOT IN using a concrete example?
- How does the query optimizer typically handle IN versus EXISTS internally?
- When would you use a LEFT JOIN with IS NULL instead of NOT EXISTS?
What is normalization? Explain the different normal forms (1NF, 2NF, 3NF, BCNF).
What they're really asking
This tests your understanding of database design theory and whether you can reduce data redundancy systematically. The interviewer wants to see if you know each normal form's specific rule and can apply them to real table designs.
How you'll be scored
Vaguely says normalization reduces redundancy but cannot explain any specific normal form or its requirements.
Correctly describes 1NF through 3NF with basic examples of each.
Explains all four forms with concrete table examples, identifies violations in sample schemas, and discusses when to stop normalizing based on practical trade-offs.
How to structure your answer
- Define normalization and its goal of reducing redundancy and anomalies.
- Explain 1NF: atomic values and no repeating groups.
- Explain 2NF: no partial dependencies on composite keys.
- Explain 3NF: no transitive dependencies.
- Explain BCNF: every determinant must be a candidate key.
Key points to hit
- 1NF requires every column to hold atomic (indivisible) values and every row to be unique, so no multi-value fields like comma-separated lists.
- 2NF builds on 1NF and eliminates partial dependencies where a non-key column depends on only part of a composite primary key.
- 3NF builds on 2NF and removes transitive dependencies where a non-key column depends on another non-key column instead of the primary key directly.
- BCNF is a stricter version of 3NF where every functional dependency must have a superkey on the left side.
Common mistakes
- Confusing 2NF and 3NF by not distinguishing between partial dependencies (2NF) and transitive dependencies (3NF)
- Saying normalization always improves performance, when over-normalization can actually hurt read-heavy workloads due to excessive joins.
Sample answer
Normalization is a systematic process of organizing tables to minimize redundancy and prevent update anomalies. In 1NF, every cell must hold a single atomic value, so a column like phone_numbers with "555-1234, 555-5678" would need to be split into separate rows or a related table. 2NF applies when you have a composite primary key.
If an orders table has a key of (order_id, product_id) but customer_name depends only on order_id, that is a partial dependency and you would move customer_name to an orders table. 3NF removes transitive dependencies. If an employees table stores department_id and department_name, the name depends on department_id, not on employee_id.
You would move department_name to a departments table. BCNF goes further and requires that for every functional dependency X determines Y, X must be a candidate key. Most production databases target 3NF as a practical balance.
How to level up
- In practice, most teams normalize to 3NF and then selectively denormalize for read performance, documenting the trade-offs.
- BCNF violations are rare in practice but can appear in tables with overlapping candidate keys.
- Understanding normalization helps you spot data modeling mistakes during code reviews even if you never formally normalize a schema step by step.
Follow-up questions to expect
- Can you give an example of a table that is in 3NF but not in BCNF?
- When would you intentionally keep a table in 2NF instead of normalizing further?
- How does normalization relate to insert, update, and delete anomalies?
What is denormalization and when is it used?
What they're really asking
This tests your understanding of database design principles and when to break normalization rules for performance. The interviewer wants to see if you can balance data integrity against query performance and understand the trade-offs in real-world applications.
How you'll be scored
Only mentions that denormalization means adding redundant data without explaining when or why you'd do it.
Correctly defines denormalization and gives basic examples like avoiding joins for performance.
Explains denormalization with specific use cases, discusses the trade-offs between storage cost and query speed, and mentions maintenance complexity.
How to structure your answer
- Define denormalization as intentionally introducing redundancy.
- Explain the primary motivation (query performance)
- Give specific scenarios where it's beneficial.
- Discuss the trade-offs and risks.
- Mention maintenance strategies.
Key points to hit
- Denormalization trades storage space and update complexity for faster read performance by reducing joins.
- Common patterns include storing calculated totals, flattening hierarchies, and duplicating frequently-accessed foreign key data.
- The decision depends on read-to-write ratios and whether the application can handle eventual consistency.
- Requires careful planning for data synchronization and handling update anomalies.
Common mistakes
- Thinking denormalization is always bad or always good without considering the specific use case.
- Not mentioning the maintenance overhead and potential for data inconsistency.
Sample answer
Denormalization is intentionally introducing redundant data into a normalized schema to improve query performance. For example, in an e-commerce system, instead of joining Orders, OrderItems, and Products tables every time we need order totals, we might store the calculated total directly in the Orders table.
This is particularly useful for reporting dashboards where we're doing many more reads than writes. The trade-off is that we now need to maintain that total whenever order items change, and we risk data inconsistency if our update logic has bugs.
I'd use denormalization when the read-to-write ratio is high and the performance gain justifies the added complexity.
How to level up
- Consider materialized views as a middle ground that provides denormalization benefits with automatic maintenance.
- Implement denormalization gradually and measure the actual performance impact before and after.
- Use database triggers or application-level transaction patterns to maintain consistency across denormalized data.
Follow-up questions to expect
- How would you handle keeping denormalized data consistent when updates happen?
- Can you give an example of when you would NOT denormalize despite performance concerns?
- What's the difference between denormalization and using materialized views?
How do you calculate a running total or moving average in SQL?
What they're really asking
This tests your knowledge of window functions and analytical SQL capabilities. The interviewer wants to see if you understand how to perform cumulative calculations that are common in financial reporting and time-series analysis.
How you'll be scored
Attempts to use self-joins or cursors instead of window functions, showing lack of modern SQL knowledge.
Uses SUM() OVER() correctly for running totals but may not explain the window frame or handle moving averages properly.
Demonstrates both running totals and moving averages with proper window frame syntax, explains performance benefits over alternative approaches.
How to structure your answer
- Explain the concept of window functions.
- Show running total syntax with SUM() OVER()
- Demonstrate moving average with frame specification.
- Explain the window frame concept.
- Discuss performance considerations.
Key points to hit
- Running totals use SUM() OVER (ORDER BY date_column ROWS UNBOUNDED PRECEDING) to accumulate values chronologically.
- Moving averages require specifying a window frame like ROWS BETWEEN 2 PRECEDING AND CURRENT ROW for a 3-period average.
- Window functions are more efficient than self-joins because they process data in a single pass.
- The ORDER BY clause in the window function determines the sequence for calculations, not the final result order.
Common mistakes
- Forgetting the ORDER BY clause in the window function, which makes the running total unpredictable.
- Confusing RANGE and ROWS window frames, where RANGE uses value-based windows instead of physical row counts.
Sample answer
For a running total, I'd use SUM(amount) OVER (ORDER BY date_column ROWS UNBOUNDED PRECEDING). This accumulates all previous rows plus the current row. For a 3-month moving average, I'd write AVG(amount) OVER (ORDER BY date_column ROWS BETWEEN 2 PRECEDING AND CURRENT ROW).
The key is understanding window frames - UNBOUNDED PRECEDING means from the start of the partition, while '2 PRECEDING' creates a sliding window. These window functions are much more efficient than self-joins because the database can calculate all values in one pass through the data.
How to level up
- Use PARTITION BY to calculate separate running totals for different groups in the same query.
- Consider using RANGE instead of ROWS when you need value-based windows rather than physical row counts.
- Add proper indexing on the ORDER BY columns to optimize window function performance.
Follow-up questions to expect
- How would you handle missing dates in a time series when calculating moving averages?
- What's the difference between ROWS and RANGE in window frame specifications?
- How would you optimize a query with multiple window functions?
Explain the purpose of LAG() and LEAD() window functions.
What they're really asking
This tests your understanding of window functions for accessing data from adjacent rows. The interviewer wants to see if you can work with row-relative data access patterns common in time-series analysis and comparative reporting.
How you'll be scored
Confuses LAG and LEAD or tries to use self-joins instead of understanding these are window functions.
Correctly explains that LAG gets previous rows and LEAD gets next rows with basic syntax.
Demonstrates both functions with realistic examples, explains default value handling, and discusses use cases like period-over-period comparisons.
How to structure your answer
- Define LAG as accessing previous rows and LEAD as accessing next rows.
- Show basic syntax with offset and default parameters.
- Provide concrete business use cases.
- Explain how they work with partitions.
- Discuss practical applications in analytics.
Key points to hit
- LAG(column, offset, default) accesses data from previous rows, while LEAD accesses future rows in the ordered result set.
- The offset parameter defaults to 1, and the default value prevents nulls when no previous or next row exists.
- These functions are essential for period-over-period comparisons like month-over-month growth calculations.
- Combined with PARTITION BY, they work within groups to compare values within categories.
Common mistakes
- Not specifying a default value and ending up with unexpected nulls at partition boundaries.
- Forgetting that the ORDER BY clause determines which row is 'previous' or 'next'
Sample answer
LAG and LEAD are window functions that access data from previous or next rows relative to the current row. For example, LAG(sales, 1, 0) gets the sales value from the previous row, with 0 as default if there's no previous row. LEAD(sales, 1, 0) gets the next row's value.
I commonly use these for calculating month-over-month changes like SELECT month, sales, sales - LAG(sales, 1, 0) OVER (ORDER BY month) AS growth. With PARTITION BY, I can compare values within groups, like comparing each employee's performance to their previous month within their department.
How to level up
- Use LAG and LEAD together to calculate centered moving averages or identify local peaks and valleys in data.
- Combine with CASE statements to handle business logic like 'first month of employment' where LAG returns null.
- Consider using larger offset values to compare year-over-year instead of sequential periods.
Follow-up questions to expect
- How would you calculate the percentage change between current and previous periods using LAG?
- What happens when you use LAG or LEAD at partition boundaries?
- Can you show how to use these functions to identify consecutive sequences in data?
What is the COALESCE function and how is it used?
What they're really asking
This tests your knowledge of null handling and data cleanup functions. The interviewer wants to see if you understand how to work with incomplete data and can choose the right approach for different null-handling scenarios.
How you'll be scored
Only knows COALESCE returns the first non-null value without understanding when to use it over alternatives.
Correctly explains COALESCE syntax and gives basic examples of null replacement.
Demonstrates COALESCE with realistic scenarios, compares it to ISNULL or CASE alternatives, and discusses performance implications.
How to structure your answer
- Define COALESCE as returning first non-null value from a list.
- Show syntax with multiple parameters.
- Give practical examples of null handling.
- Compare to database-specific alternatives.
- Discuss performance and use case considerations.
Key points to hit
- COALESCE(value1, value2, value3) returns the first non-null value from left to right, or null if all are null.
- It's SQL standard unlike database-specific functions like ISNULL (SQL Server) or NVL (Oracle)
- Common use cases include providing default values for missing data and creating fallback hierarchies.
- COALESCE can accept any number of parameters and works with any data type as long as they're compatible.
Common mistakes
- Using COALESCE when you need to distinguish between null and empty string, since it only handles nulls.
- Not considering data type compatibility when mixing different types in the parameter list.
Sample answer
COALESCE returns the first non-null value from a list of expressions. For example, COALESCE(preferred_email, work_email, personal_email, 'no-email@company.com') would check each email field and return the first one that's not null, with a default if all are null. I use this frequently for data cleanup, like COALESCE(nickname, first_name) to display a person's preferred name.
It's more portable than database-specific functions like ISNULL because it's part of the SQL standard. The function evaluates left to right and stops at the first non-null value, so you can put expensive calculations or subqueries toward the right side.
How to level up
- Use COALESCE in ORDER BY clauses to handle null sorting behavior consistently across different databases.
- Combine with NULLIF to create more sophisticated null handling logic like COALESCE(NULLIF(column, ''), 'default')
- Consider using COALESCE in aggregate functions to provide meaningful defaults for empty groups.
Follow-up questions to expect
- What's the difference between COALESCE and using CASE statements for null handling?
- How would you handle both null and empty string values in a single expression?
- When might you choose database-specific functions like ISNULL over COALESCE?
What is the MERGE (UPSERT) statement and when should it be used?
What they're really asking
This tests your understanding of advanced DML operations and data synchronization patterns. The interviewer wants to see if you can handle complex data integration scenarios where you need to insert new records and update existing ones atomically.
How you'll be scored
Only knows basic INSERT/UPDATE syntax and suggests separate statements without understanding atomicity issues.
Understands MERGE combines INSERT/UPDATE operations but may not explain the matching logic clearly.
Demonstrates proper MERGE syntax with realistic examples, explains performance benefits over separate operations, and discusses transaction safety.
How to structure your answer
- Define MERGE as combining INSERT, UPDATE, and DELETE in one statement.
- Explain the concept of source and target tables with matching conditions.
- Show the WHEN MATCHED/NOT MATCHED syntax.
- Discuss use cases like ETL and data synchronization.
- Mention atomicity and performance benefits.
Key points to hit
- MERGE uses a source table to conditionally INSERT, UPDATE, or DELETE rows in a target table based on matching criteria.
- The statement structure includes WHEN MATCHED, WHEN NOT MATCHED BY TARGET, and optionally WHEN NOT MATCHED BY SOURCE clauses.
- Primary use cases include ETL processes, data warehouse loading, and synchronizing tables across systems.
- MERGE is atomic and more efficient than separate INSERT/UPDATE operations because it scans the target table once.
Common mistakes
- Not handling all possible scenarios (matched, not matched by target, not matched by source) which can lead to incomplete synchronization.
- Using MERGE for simple operations where plain INSERT or UPDATE would be clearer and faster.
Sample answer
MERGE is an UPSERT operation that combines INSERT, UPDATE, and DELETE in a single atomic statement. For example, when loading daily sales data, I'd use MERGE sales_summary AS target USING daily_sales AS source ON target.date = source.date WHEN MATCHED THEN UPDATE SET target.total = source.total WHEN NOT MATCHED THEN INSERT VALUES (source.date, source.total).
This handles both new dates and updates to existing dates in one operation. It's particularly useful for ETL processes where you're synchronizing data between systems. The key advantage is atomicity and performance since it scans the target table only once instead of separate scans for INSERT and UPDATE operations.
How to level up
- Use additional conditions in WHEN clauses like 'WHEN MATCHED AND source.updated_date > target.updated_date' to avoid unnecessary updates.
- Consider using WHEN NOT MATCHED BY SOURCE to delete records that no longer exist in the source system.
- Add proper indexing on the merge join conditions to optimize performance for large datasets.
Follow-up questions to expect
- How would you handle conflicts when multiple source rows match the same target row?
- What are the transaction isolation considerations when using MERGE with concurrent operations?
- When would you choose separate INSERT/UPDATE statements over MERGE?
How do you use COMMIT, ROLLBACK, and SAVEPOINT in transactions?
What they're really asking
This tests your understanding of transaction control and whether you can manage multi-step database operations safely. The interviewer wants to see if you know how to group changes, undo partial work, and ensure data consistency.
How you'll be scored
Knows COMMIT saves changes but cannot explain ROLLBACK or SAVEPOINT or when transactions are necessary.
Correctly explains all three commands with a basic example of wrapping statements in a transaction.
Demonstrates a realistic multi-step transaction with error handling, shows partial rollback to a SAVEPOINT, and discusses auto-commit behavior differences across databases.
How to structure your answer
- Explain what a transaction is and why it matters.
- Define COMMIT and when changes become permanent.
- Define ROLLBACK and full undo behavior.
- Define SAVEPOINT for partial rollback.
- Show a practical example combining all three.
Key points to hit
- BEGIN TRANSACTION starts a new transaction block where all subsequent changes are provisional until COMMIT.
- COMMIT makes all changes in the current transaction permanent and visible to other sessions.
- ROLLBACK undoes all changes since the last BEGIN or SAVEPOINT, restoring the database to its previous state.
- SAVEPOINT creates a named checkpoint within a transaction so you can ROLLBACK TO that point without losing all work.
Common mistakes
- Forgetting that some databases like MySQL auto-commit each statement by default unless you explicitly start a transaction.
- Not understanding that DDL statements like CREATE TABLE cause an implicit commit in MySQL, breaking your transaction boundary.
Sample answer
These three commands control transaction boundaries. You start with BEGIN TRANSACTION, then run your SQL statements. COMMIT makes everything permanent. ROLLBACK undoes everything. SAVEPOINT lets you set checkpoints for partial rollback.
Here is a practical example: BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 500 WHERE id = 1; SAVEPOINT after_debit; UPDATE accounts SET balance = balance + 500 WHERE id = 2; if the second update fails, I can ROLLBACK TO after_debit to undo just the credit while keeping the debit, then handle the error.
If everything succeeds, COMMIT finalizes both changes. In production code, I wrap this in a try-catch block so any exception triggers a full ROLLBACK.
How to level up
- In PostgreSQL, a failed statement inside a transaction marks the entire transaction as aborted, and you must ROLLBACK TO a savepoint or ROLLBACK entirely before issuing any new commands.
- Nested savepoints are supported in most databases and act like a stack where RELEASE SAVEPOINT removes the checkpoint.
- Keep transactions as short as possible to reduce lock contention, especially in high-concurrency applications.
Follow-up questions to expect
- What happens if your application crashes between the UPDATE and the COMMIT?
- How does auto-commit mode differ between PostgreSQL and MySQL?
- Can you nest transactions, and if so, how does that work?
What are the ACID properties of a transaction?
What they're really asking
This tests whether you understand the guarantees that database transactions provide and why they matter. The interviewer wants to see if you can explain each property with practical implications, not just recite definitions.
How you'll be scored
Can name some ACID letters but cannot explain what each property guarantees or why it matters.
Correctly defines all four properties with textbook definitions.
Explains each property with real-world failure scenarios showing what goes wrong without it, and discusses how databases implement these guarantees.
How to structure your answer
- Define Atomicity and the all-or-nothing guarantee.
- Define Consistency and constraint enforcement.
- Define Isolation and concurrent access behavior.
- Define Durability and crash recovery.
- Give a real-world example tying all four together.
Key points to hit
- Atomicity means a transaction is all-or-nothing. If any part fails, the entire transaction rolls back so the database never has partial results.
- Consistency ensures every transaction moves the database from one valid state to another, enforcing constraints like foreign keys and check rules.
- Isolation controls how concurrent transactions see each other's uncommitted changes, preventing issues like dirty reads and phantom reads.
- Durability guarantees that once a transaction is committed, the data survives even a power failure or system crash, typically through write-ahead logging.
Common mistakes
- Explaining ACID in purely theoretical terms without concrete examples of what breaks when a property is violated.
- Confusing Consistency in ACID with Consistency in the CAP theorem, which means something different.
Sample answer
ACID describes the four guarantees every database transaction must provide. Atomicity means all-or-nothing. If I transfer money with UPDATE accounts SET balance = balance - 100 WHERE id = 1 and UPDATE accounts SET balance = balance + 100 WHERE id = 2, either both updates succeed or neither does.
Consistency means the database enforces all constraints before and after the transaction, so you cannot end up with a negative balance if you have a CHECK constraint. Isolation means two people transferring money at the same time do not see each other's intermediate states, preventing double-spending scenarios.
Durability means once COMMIT returns successfully, the data is persisted to disk even if the server crashes one second later, which databases achieve using write-ahead logs.
How to level up
- Discuss how isolation levels let you trade some isolation for better performance, since full serializable isolation is expensive.
- Mention that NoSQL databases often relax one or more ACID properties in exchange for horizontal scalability.
- Explain how write-ahead logging (WAL) implements durability by writing to a log before modifying actual data pages.
Follow-up questions to expect
- How does ACID relate to the CAP theorem in distributed systems?
- Which isolation level provides full ACID compliance and why is it not always used?
- How do databases recover from crashes using write-ahead logs?
How do you implement pagination in SQL?
What they're really asking
This tests whether you understand how to return subsets of results efficiently and know the trade-offs between different pagination strategies. The interviewer wants to see if you can go beyond basic OFFSET/LIMIT to discuss performance at scale.
How you'll be scored
Only mentions LIMIT without OFFSET or cannot construct a working pagination query.
Shows correct OFFSET/LIMIT syntax and can calculate page boundaries.
Explains both offset-based and keyset (cursor) pagination, discusses why OFFSET degrades on large datasets, and recommends keyset pagination for production APIs.
How to structure your answer
- Show basic OFFSET/LIMIT pagination syntax.
- Explain how to calculate offset from page number and page size.
- Discuss the performance problem with large offsets.
- Introduce keyset pagination as the scalable alternative.
Key points to hit
- OFFSET/LIMIT is the simplest approach: SELECT * FROM products ORDER BY id LIMIT 20 OFFSET 40 gets page 3 with 20 items per page.
- OFFSET forces the database to scan and discard all skipped rows, so page 10000 is much slower than page 1.
- Keyset pagination uses a WHERE clause on the last seen value: WHERE id > 1000 ORDER BY id LIMIT 20, which uses the index directly.
- Always include an ORDER BY with pagination, otherwise the result order is not guaranteed between pages.
Common mistakes
- Using OFFSET/LIMIT on large tables without realizing performance degrades linearly as the offset increases.
- Paginating without ORDER BY, which can cause rows to appear on multiple pages or be skipped entirely.
Sample answer
The simplest approach is OFFSET and LIMIT. For page 3 with 20 rows per page, I would write SELECT * FROM products ORDER BY created_at DESC LIMIT 20 OFFSET 40. The problem is that OFFSET 100000 means the database has to read and throw away 100,000 rows before returning your 20. For production APIs with large datasets, I use keyset pagination instead. The client sends the last value they saw, and I query WHERE created_at < '2026-01-15' ORDER BY created_at DESC LIMIT 20. This uses the index on created_at directly and performs consistently regardless of how deep into the results you are. The trade-off is that keyset pagination does not support jumping to arbitrary page numbers.
How to level up
- SQL Server uses OFFSET FETCH syntax instead of LIMIT: OFFSET 40 ROWS FETCH NEXT 20 ROWS ONLY.
- For keyset pagination on non-unique columns, use a composite cursor like WHERE (created_at, id) < (last_date, last_id) to handle ties.
- Consider including a total count query only when necessary since COUNT(*) on large tables can be expensive by itself.
Follow-up questions to expect
- How would you implement keyset pagination when sorting by a non-unique column like created_at?
- What are the trade-offs between keyset and offset pagination for a user-facing application?
- How would you return the total number of pages efficiently alongside paginated results?
What is the purpose of the SQL PIVOT operator?
What they're really asking
This tests whether you can transform row-based data into columnar format for reporting. The interviewer wants to see if you understand when pivoting is useful and can implement it even in databases that lack a native PIVOT operator.
How you'll be scored
Cannot explain what pivoting means or confuses it with a simple GROUP BY.
Explains that PIVOT turns rows into columns with a basic syntax example.
Shows both native PIVOT syntax and the manual CASE/GROUP BY alternative, explains when each is appropriate, and discusses dynamic pivoting challenges.
How to structure your answer
- Define what pivoting does: transform rows into columns.
- Show SQL Server PIVOT syntax as the native approach.
- Show the portable CASE with GROUP BY alternative.
- Discuss when pivoting is useful in reporting.
Key points to hit
- PIVOT rotates rows into columns, turning unique values from one column into separate column headers in the result.
- SQL Server has native PIVOT syntax, but PostgreSQL and MySQL require the CASE/GROUP BY approach.
- The manual approach uses SUM(CASE WHEN category = 'X' THEN amount ELSE 0 END) AS X for each target column.
- Dynamic pivoting where column names are not known in advance requires dynamic SQL or application-level transformation.
Common mistakes
- Assuming PIVOT is standard SQL available in all databases when it is actually a SQL Server and Oracle specific extension.
- Forgetting to include an aggregate function in PIVOT, since it requires aggregation to combine values into the new columns.
Sample answer
PIVOT transforms row values into column headers, which is essential for cross-tab reports. In SQL Server, the syntax is SELECT * FROM (SELECT product, quarter, revenue FROM sales) src PIVOT (SUM(revenue) FOR quarter IN ([Q1], [Q2], [Q3], [Q4])) pvt. This turns four rows per product into one row with Q1 through Q4 as columns.
Since PostgreSQL and MySQL do not have native PIVOT, I use the portable approach: SELECT product, SUM(CASE WHEN quarter = 'Q1' THEN revenue ELSE 0 END) AS Q1, SUM(CASE WHEN quarter = 'Q2' THEN revenue ELSE 0 END) AS Q2 FROM sales GROUP BY product.
The CASE approach works everywhere and is often clearer about what aggregation is happening.
How to level up
- For dynamic pivot columns where you do not know the values in advance, use dynamic SQL to build the CASE expressions from a SELECT DISTINCT on the pivot column.
- UNPIVOT does the reverse, turning columns back into rows, which is useful for normalizing denormalized reporting tables.
- In PostgreSQL, the crosstab function from the tablefunc extension provides native pivot functionality.
Follow-up questions to expect
- How would you handle a pivot where the column values are not known in advance?
- What is UNPIVOT and when would you use it?
- How would you implement this same transformation in application code instead of SQL?
How do you update one table based on values from another table?
What they're really asking
This tests whether you can write UPDATE statements that reference other tables, which is a common requirement for data synchronization and bulk corrections. The interviewer wants to see if you know the syntax variations across databases.
How you'll be scored
Cannot write an UPDATE with a JOIN or subquery, or writes syntax that would not compile.
Shows one correct approach using either a subquery or UPDATE with JOIN.
Demonstrates both UPDATE FROM and correlated subquery approaches, notes syntax differences across databases, and discusses safety practices like previewing with SELECT first.
How to structure your answer
- Show the UPDATE with JOIN approach used in SQL Server and PostgreSQL.
- Show the correlated subquery approach for standard SQL.
- Explain safety practices for multi-table updates.
- Mention MERGE as an alternative for upsert scenarios.
Key points to hit
- SQL Server uses UPDATE t1 SET t1.col = t2.val FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id.
- PostgreSQL uses UPDATE table1 SET col = t2.val FROM table2 t2 WHERE table1.id = t2.id.
- The standard SQL approach uses a correlated subquery: UPDATE table1 SET col = (SELECT val FROM table2 WHERE table2.id = table1.id)
- MySQL uses UPDATE table1 t1 JOIN table2 t2 ON t1.id = t2.id SET t1.col = t2.val.
Common mistakes
- Not previewing the update with a SELECT first, which risks updating wrong rows in production.
- Using a correlated subquery that returns multiple rows for a single match, causing an error or unpredictable results.
Sample answer
The approach depends on your database. In PostgreSQL, I would write UPDATE orders SET status = c.default_status FROM customers c WHERE orders.customer_id = c.id AND c.tier = 'premium'. In SQL Server, the syntax is UPDATE o SET o.status = c.default_status FROM orders o JOIN customers c ON o.customer_id = c.id WHERE c.tier = 'premium'.
For standard SQL compatibility, I can use a correlated subquery: UPDATE orders SET status = (SELECT default_status FROM customers WHERE customers.id = orders.customer_id) WHERE customer_id IN (SELECT id FROM customers WHERE tier = 'premium').
Before running any of these, I always convert the UPDATE to a SELECT first to verify which rows will be affected and what the new values will be.
How to level up
- For large tables, batch the update with a LIMIT or WHERE id BETWEEN range to avoid long-running transactions and excessive lock holding.
- MERGE or INSERT ON CONFLICT can handle the case where you need to insert new rows and update existing ones in a single statement.
- In PostgreSQL, you can use UPDATE RETURNING to see which rows were actually modified without a separate query.
Follow-up questions to expect
- What would happen if the subquery in a correlated UPDATE returns more than one row?
- How would you update a table based on an aggregation from another table?
- When would you choose MERGE over a simple UPDATE with JOIN?
What is a cross join and how does it differ from an inner join?
What they're really asking
This tests your understanding of join cardinality and result set size. The interviewer wants to see if you recognize that cross joins create Cartesian products and understand when this massive data expansion is intentional versus accidental.
How you'll be scored
Confuses cross join with inner join or cannot explain the Cartesian product concept.
Correctly explains that cross join returns all combinations but doesn't discuss practical implications.
Explains Cartesian products, discusses performance implications, and identifies legitimate use cases like generating test data or date ranges.
How to structure your answer
- Define cross join as Cartesian product.
- Show syntax difference from inner join.
- Explain result set size calculation.
- Discuss performance implications.
- Give practical use cases.
Key points to hit
- Cross join produces every combination of rows from both tables without any join condition.
- Result set size equals table1_rows ร table2_rows, which can become enormous quickly.
- Inner join requires a matching condition and typically produces smaller result sets.
- Cross joins are rarely needed but useful for generating combinations like all dates with all products.
Common mistakes
- Writing a cross join accidentally by forgetting the WHERE clause in older SQL syntax.
- Not recognizing the performance danger when cross joining large tables.
Sample answer
A cross join creates a Cartesian product, returning every possible combination of rows from two tables. So if I have 100 customers and 50 products, a cross join gives me 5,000 rows. The syntax is either CROSS JOIN or just comma-separated tables without a WHERE clause.
An inner join requires a matching condition like customer_id = order.customer_id and only returns rows where that condition is true. I've used cross joins to generate test data combinations or to create a complete date range paired with all product categories for reporting templates.
How to level up
- Recognize when accidental cross joins happen in complex queries with multiple tables.
- Use cross joins strategically for generating reference data like calendar tables paired with dimensions.
Follow-up questions to expect
- How would you identify if a query accidentally contains a cross join?
- What happens to query performance when you cross join two large tables?
Explain anti-joins and how to find records in one table that are not in another.
What they're really asking
This tests your knowledge of exclusion patterns and NULL handling in joins. The interviewer wants to see if you understand how to correctly filter out matching records and avoid the common pitfall of using NOT IN with nullable columns.
How you'll be scored
Uses NOT IN without considering NULL values or cannot write a working anti-join query.
Writes a correct LEFT JOIN with IS NULL pattern but doesn't explain the NULL handling issue.
Demonstrates multiple anti-join techniques, explains NULL behavior with NOT IN, and discusses performance considerations of different approaches.
How to structure your answer
- Define anti-join concept.
- Show LEFT JOIN with IS NULL approach.
- Demonstrate NOT EXISTS alternative.
- Explain NOT IN pitfall with NULLs.
- Compare performance characteristics.
Key points to hit
- Anti-join finds records in table A that have no matching records in table B.
- LEFT JOIN with IS NULL is the most common pattern: LEFT JOIN table2 ON condition WHERE table2.key IS NULL.
- NOT IN fails when the right side contains NULLs because NULL comparisons return unknown, not false.
- NOT EXISTS is often more readable and handles NULLs correctly.
Common mistakes
- Using NOT IN with columns that might contain NULL values.
- Forgetting the IS NULL condition after LEFT JOIN, which turns it into a regular join.
Sample answer
An anti-join finds records in one table that don't exist in another. The safest approach is LEFT JOIN with IS NULL: SELECT customers.* FROM customers LEFT JOIN orders ON customers.id = orders.customer_id WHERE orders.customer_id IS NULL. This finds customers with no orders.
I avoid NOT IN because if the orders table has any NULL customer_id values, the NOT IN returns no results at all due to how SQL handles NULL comparisons. NOT EXISTS is another clean option that handles NULLs properly.
How to level up
- Consider using NOT EXISTS for better readability when the anti-join logic is complex.
- Check execution plans since NOT EXISTS sometimes performs better than LEFT JOIN with large datasets.
Follow-up questions to expect
- Why does NOT IN fail when NULLs are present in the subquery?
- How would you find customers who have never ordered a specific product category?
What is referential integrity? How is it enforced?
What they're really asking
This tests your understanding of data consistency and constraint mechanisms. The interviewer wants to see if you know how databases prevent orphaned records and maintain logical relationships between tables.
How you'll be scored
Gives vague definition without explaining foreign key constraints or enforcement mechanisms.
Correctly explains foreign keys and basic constraint enforcement but misses cascade options or business implications.
Explains foreign keys, discusses cascade options (DELETE/UPDATE), mentions constraint checking timing, and connects to data quality benefits.
How to structure your answer
- Define referential integrity concept.
- Explain foreign key constraints.
- Describe enforcement mechanisms.
- Cover cascade options.
- Discuss business benefits.
Key points to hit
- Referential integrity ensures that foreign key values always reference valid primary key values in the parent table.
- Enforced through foreign key constraints that prevent inserting invalid references or deleting referenced records.
- CASCADE options handle dependent records automatically: DELETE CASCADE removes child records, UPDATE CASCADE updates foreign keys.
- Constraint checking can be immediate or deferred depending on database settings.
Common mistakes
- Thinking referential integrity only prevents deletes, when it also validates inserts and updates.
- Not understanding that cascade operations can have unintended consequences on large datasets.
Sample answer
Referential integrity ensures that relationships between tables remain valid. If an orders table has a customer_id foreign key, that ID must exist in the customers table. The database enforces this through foreign key constraints that reject any insert or update creating invalid references.
When I try to delete a customer with existing orders, it fails unless I use CASCADE DELETE to remove the orders too, or SET NULL to clear the foreign key. This prevents orphaned data and maintains logical consistency in the application.
How to level up
- Consider using RESTRICT vs CASCADE carefully since CASCADE can delete more data than intended.
- Use deferred constraint checking in transactions when you need to temporarily violate constraints during complex updates.
Follow-up questions to expect
- What happens when you try to insert a record with an invalid foreign key?
- How do you handle referential integrity when loading data from external sources?
What are temporary tables? When should you use them?
What they're really asking
This tests your understanding of temporary storage options and session management. The interviewer wants to see if you know when to use temporary tables versus alternatives and understand their lifecycle and performance characteristics.
How you'll be scored
Confuses temporary tables with regular tables or cannot explain when to use them.
Correctly explains that temp tables are session-specific but doesn't discuss performance benefits or alternatives.
Explains temp table types (session vs global), discusses indexing capabilities, compares with CTEs and table variables, and identifies optimal use cases.
How to structure your answer
- Define temporary table characteristics.
- Explain session vs global temp tables.
- Compare with alternatives (CTEs, table variables)
- Identify optimal use cases.
- Discuss performance considerations.
Key points to hit
- Temporary tables exist only for the duration of a session and are automatically dropped when the session ends.
- They support indexing and statistics, making them faster than table variables for large datasets.
- Local temp tables (#temp) are session-specific while global temp tables (##temp) are visible across sessions.
- Use temp tables for complex multi-step processing where you need to store intermediate results with good performance.
Common mistakes
- Using temp tables when a simple CTE would suffice.
- Forgetting that temp tables consume tempdb space and can cause contention in high-concurrency environments.
Sample answer
Temporary tables are session-specific tables that exist only during your connection, created with CREATE TABLE #tablename. They're stored in tempdb and automatically dropped when the session ends. I use them when I need to store intermediate results for complex processing, especially when the dataset is large enough to benefit from indexes.
Unlike CTEs which are just query expressions, temp tables can be indexed and have statistics, making them much faster for repeated access. They're perfect for breaking down complex reports into manageable steps.
How to level up
- Create indexes on temp tables when you'll be joining or filtering on them multiple times.
- Monitor tempdb usage in production since heavy temp table use can create bottlenecks.
Follow-up questions to expect
- When would you choose a CTE over a temporary table?
- How do temporary tables affect transaction log usage?
Ready to put this into practice?
Try these questions in a mock interview →Still applying for jobs? Let Auto Apply do it
Advanced SQL Questions (25)
How do you optimize a slow-running query?
What they're really asking
This tests your systematic approach to performance diagnosis and optimization. The interviewer wants to see if you follow a methodical process from identifying bottlenecks to implementing solutions, not just guessing at fixes.
How you'll be scored
Suggests random optimizations like adding indexes without diagnosing the actual problem first.
Mentions execution plans and basic optimizations but lacks a systematic troubleshooting approach.
Demonstrates systematic diagnosis using execution plans, identifies specific bottlenecks, prioritizes solutions by impact, and discusses measurement and validation.
How to structure your answer
- Analyze execution plan first.
- Identify specific bottlenecks.
- Prioritize optimizations by impact.
- Implement and measure results.
- Consider query rewrite vs schema changes.
Key points to hit
- Start with the execution plan to identify table scans, expensive operations, and missing index recommendations.
- Look for high-cost operations like sorts, hash joins on large datasets, or key lookups.
- Consider both query-level fixes (better WHERE clauses, index hints) and schema-level fixes (new indexes, partitioning)
- Measure before and after performance to validate improvements and avoid making things worse.
Common mistakes
- Adding indexes without understanding the query pattern, which can slow down writes.
- Optimizing the wrong part of the query instead of focusing on the highest-cost operations.
Sample answer
I start by examining the execution plan to find the most expensive operations. Usually it's table scans on large tables or expensive sorts. If I see a table scan, I check if there's a useful index or if the WHERE clause can be improved to be more selective.
For joins, I look at join types and cardinality estimates. Sometimes the fix is rewriting the query logic, like using EXISTS instead of IN for subqueries. I also check if statistics are current since stale stats lead to bad execution plans.
After making changes, I re-run the query and compare the new execution plan to verify the improvement.
How to level up
- Use query store or profiling tools to identify the most frequently run expensive queries rather than optimizing one-offs.
- Consider parameter sniffing issues where the same query performs differently with different parameter values.
Follow-up questions to expect
- How would you handle a query that runs fast with small parameters but times out with large ones?
- What would you do if adding an index doesn't improve the query performance?
What is a query execution plan (EXPLAIN) and how do you interpret it?
What they're really asking
This tests whether you can analyze query performance beyond just writing correct SQL. The interviewer wants to see if you know how to read execution plans to identify bottlenecks like full table scans, missing indexes, and inefficient join strategies.
How you'll be scored
Knows EXPLAIN exists but cannot describe what information it provides or how to act on it.
Can run EXPLAIN and identify basic elements like sequential scans versus index scans.
Reads execution plans fluently, identifies costly operations, understands estimated versus actual row counts, and uses plan analysis to guide index creation and query rewrites.
How to structure your answer
- Explain what EXPLAIN does and what EXPLAIN ANALYZE adds.
- Describe the key elements of a plan: scan types, join methods, costs.
- Explain how to identify the most expensive operations.
- Show how plan analysis leads to optimization decisions.
Key points to hit
- EXPLAIN shows the planned execution strategy without running the query. EXPLAIN ANALYZE actually runs it and shows real timing and row counts.
- Sequential Scan (Seq Scan) means the database reads every row in the table, which is a red flag on large tables with selective WHERE conditions.
- The cost numbers represent the optimizer's estimate of work required, with the first number being startup cost and the second being total cost.
- A large gap between estimated and actual rows indicates stale statistics, which you fix with ANALYZE in PostgreSQL or UPDATE STATISTICS in SQL Server.
Common mistakes
- Running EXPLAIN ANALYZE on destructive statements like DELETE or UPDATE without wrapping them in a transaction and rolling back.
- Focusing only on the cost numbers without looking at actual row counts and whether the optimizer's estimates match reality.
Sample answer
EXPLAIN shows the database's planned approach for executing your query without actually running it. I use EXPLAIN ANALYZE to see actual execution times and row counts alongside the estimates. For example, running EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42 might show a Seq Scan on orders with cost=0.00..15234.00 rows=500.
That sequential scan tells me there is no index on customer_id, and the database is reading every row. After adding CREATE INDEX idx_orders_customer ON orders(customer_id), the plan switches to an Index Scan with cost=0.42..8.50 rows=500. I pay special attention to the actual rows versus estimated rows.
If the estimate says 10 but the actual is 100,000, the optimizer made a bad plan based on stale statistics, and I need to run ANALYZE on the table.
How to level up
- Use EXPLAIN (BUFFERS, ANALYZE) in PostgreSQL to see how many disk pages were read from cache versus disk, which reveals I/O bottlenecks.
- Look for Nested Loop joins on large tables, which often indicate a missing index that would enable a Hash Join or Merge Join instead.
- In SQL Server, check for Key Lookups in the plan which indicate the index does not cover all needed columns and a covering index would help.
Follow-up questions to expect
- What does it mean when the estimated rows in a plan are very different from the actual rows?
- How would you decide between adding an index and rewriting the query based on the execution plan?
- What is the difference between a Hash Join and a Nested Loop Join in an execution plan?
What is the difference between clustered and non-clustered indexes?
What they're really asking
This tests whether you understand how indexes are physically stored and how that affects query performance. The interviewer wants to see if you know why a table can have only one clustered index and how non-clustered indexes work alongside it.
How you'll be scored
Cannot explain the physical storage difference or says a table can have multiple clustered indexes.
Correctly states that a clustered index determines physical row order and a table can have only one.
Explains the B-tree structure, how non-clustered indexes store row locators back to the clustered index, and discusses performance implications for different query patterns.
How to structure your answer
- Define clustered index and its relationship to physical data order.
- Define non-clustered index and how it references data rows.
- Explain why only one clustered index is allowed per table.
- Discuss when to use each type.
Key points to hit
- A clustered index determines the physical storage order of data rows on disk. The table data IS the clustered index leaf level.
- A table can have only one clustered index because rows can only be physically sorted one way.
- Non-clustered indexes store a copy of the indexed columns plus a pointer (row locator) back to the actual data row.
- In SQL Server, the primary key creates a clustered index by default. In PostgreSQL, all indexes are non-clustered and the table heap is separate.
Common mistakes
- Saying PostgreSQL has clustered indexes in the same sense as SQL Server. PostgreSQL CLUSTER command reorders data once but does not maintain order on future inserts.
- Not understanding that non-clustered index lookups on a clustered table require a second lookup (key lookup) to fetch non-indexed columns.
Sample answer
A clustered index physically sorts the table data on disk by the indexed column. Think of it like a phone book sorted alphabetically by last name. Because the rows can only be stored in one physical order, you get exactly one clustered index per table. In SQL Server, the primary key is clustered by default.
A non-clustered index is a separate structure that stores copies of the indexed columns along with a pointer back to the full row. It is like the index at the back of a textbook, where you look up a topic, get a page number, and then flip to that page.
If my query is SELECT email FROM users WHERE last_name = 'Smith' and I have a non-clustered index on last_name, the database finds the matching entries in the index, then does a key lookup to fetch the email from the actual data row.
If I add email to the index as an included column, CREATE INDEX ix_name ON users(last_name) INCLUDE(email), it becomes a covering index and avoids the key lookup entirely.
How to level up
- Choose your clustered index based on your most common range query pattern since it excels at BETWEEN and ORDER BY queries on the indexed column.
- Avoid clustering on columns with frequent updates, as changing the clustered key value forces physical row movement.
- In PostgreSQL, use the CLUSTER command followed by periodic re-clustering since it does not maintain physical order automatically.
Follow-up questions to expect
- When would you choose a non-clustered index over changing the clustered index?
- What is a key lookup and how do covering indexes eliminate it?
- How does index fragmentation differ between clustered and non-clustered indexes?
What is a stored procedure? What are its advantages?
What they're really asking
This tests whether you understand server-side SQL programming and can evaluate the trade-offs of moving logic into the database layer. The interviewer wants to see if you know the real advantages beyond the textbook list and also understand the downsides.
How you'll be scored
Defines a stored procedure but cannot articulate specific advantages or mentions outdated benefits like precompilation that modern optimizers handle differently.
Correctly explains stored procedures with several valid advantages like reduced network traffic and centralized logic.
Discusses advantages and disadvantages with nuance, explains when stored procedures are the right choice versus application-level logic, and mentions debugging and deployment challenges.
How to structure your answer
- Define what a stored procedure is and basic syntax.
- List the main advantages: performance, security, reusability.
- Discuss the disadvantages and trade-offs.
- Explain when to use stored procedures versus application code.
Key points to hit
- A stored procedure is a named collection of SQL statements saved in the database that can accept parameters and return results.
- Network traffic reduction is a real advantage because the client sends one call instead of many individual queries.
- Security benefits include granting EXECUTE permission on a procedure without giving direct table access.
- The main disadvantage is that business logic in stored procedures is harder to version control, test, debug, and deploy compared to application code.
Common mistakes
- Claiming stored procedures are always faster than application code, which is not true for simple queries where the overhead of procedure call setup may exceed the network savings.
- Not mentioning the maintainability cost, which is the primary reason many modern teams avoid heavy stored procedure usage.
Sample answer
A stored procedure is a precompiled set of SQL statements stored in the database that you call by name. For example, CREATE PROCEDURE get_order_summary @customer_id INT AS BEGIN SELECT order_id, total, status FROM orders WHERE customer_id = @customer_id ORDER BY order_date DESC; END.
The main advantages are reduced network traffic since the client sends one call instead of multiple queries, security through granting EXECUTE without direct table access, and code reuse across different applications hitting the same database. However, I think it is important to be honest about the trade-offs.
Stored procedures are harder to version control, debug, and unit test compared to application code. Modern teams often use them for data-intensive operations like batch processing or complex reporting, but keep business logic in the application layer where it is easier to maintain and deploy.
How to level up
- Stored procedures can reduce SQL injection risk because parameterized procedure calls separate code from data by design.
- In PostgreSQL, functions and procedures differ in that only procedures support transaction control with COMMIT and ROLLBACK inside the body.
- Consider using stored procedures for cross-cutting database concerns like audit logging where you want guaranteed execution regardless of which application makes the change.
Follow-up questions to expect
- What is the difference between a stored procedure and a function in SQL?
- How would you handle error management inside a stored procedure?
- When would you choose to put logic in a stored procedure versus the application layer?
What is a trigger in SQL? What are the different types?
What they're really asking
This tests whether you understand event-driven database programming and can explain when triggers are appropriate versus problematic. The interviewer wants to see if you know the types of triggers and their real-world implications on debugging and performance.
How you'll be scored
Vaguely describes triggers as automatic actions but cannot name specific types or give syntax.
Correctly explains BEFORE and AFTER triggers with INSERT, UPDATE, and DELETE events.
Covers all trigger types including INSTEAD OF, explains the OLD and NEW row references, discusses cascading trigger risks, and offers guidance on when triggers are a good versus bad design choice.
How to structure your answer
- Define what a trigger is and when it fires.
- Explain BEFORE and AFTER trigger timing.
- Explain INSTEAD OF triggers and their use with views.
- Discuss row-level versus statement-level triggers.
- Cover the risks and maintenance challenges.
Key points to hit
- A trigger is a named database object that automatically executes SQL code in response to INSERT, UPDATE, or DELETE events on a table.
- BEFORE triggers fire before the event and can modify the new data or cancel the operation. AFTER triggers fire after the change is committed.
- INSTEAD OF triggers replace the triggering operation entirely and are commonly used to make views updatable.
- Triggers have access to OLD (the row before change) and NEW (the row after change) pseudo-records for accessing data being modified.
Common mistakes
- Using triggers for complex business logic that should live in the application layer, making the system harder to debug because the behavior is hidden from code review.
- Creating cascading triggers where trigger A fires trigger B which fires trigger A again, causing infinite loops or unexpected side effects.
Sample answer
A trigger is a database object that automatically runs SQL code when a specific event happens on a table.
There are three timing types: BEFORE triggers fire before the row is modified and can change the values or abort the operation, AFTER triggers fire after the change is saved, and INSTEAD OF triggers replace the operation entirely.
For example, CREATE TRIGGER audit_update AFTER UPDATE ON orders FOR EACH ROW BEGIN INSERT INTO audit_log(table_name, old_value, new_value, changed_at) VALUES('orders', OLD.status, NEW.status, NOW()); END. This logs every status change with the old and new values. Triggers can be row-level, firing once per affected row, or statement-level, firing once per SQL statement.
I use triggers primarily for audit logging and enforcing complex constraints that CHECK constraints cannot handle. I avoid putting business logic in triggers because they make debugging much harder since the code runs invisibly.
How to level up
- In PostgreSQL, triggers call separate trigger functions written in PL/pgSQL, which allows reusing the same function across multiple triggers.
- Use statement-level triggers for performance when you do not need per-row access, such as refreshing a materialized view after bulk inserts.
- Always document triggers prominently because developers who are unaware of them will spend hours debugging unexpected behavior.
Follow-up questions to expect
- How would you prevent an infinite loop if two triggers update each other's tables?
- What is the difference between a row-level and statement-level trigger?
- When would you use a trigger instead of application-level event handling?
What is a materialized view and how does it differ from a regular view?
What they're really asking
This tests whether you understand the trade-off between query performance and data freshness. The interviewer wants to see if you know when to cache query results in a materialized view versus using a regular view that always reflects current data.
How you'll be scored
Confuses materialized views with regular views or cannot explain the freshness trade-off.
Correctly explains that materialized views store results physically and need refreshing, while regular views are just saved queries.
Discusses refresh strategies, storage implications, index support on materialized views, and gives specific use cases where each is appropriate.
How to structure your answer
- Define a regular view as a saved query that runs on each access.
- Define a materialized view as a physically stored result set.
- Explain the freshness versus performance trade-off.
- Discuss refresh strategies and indexing.
Key points to hit
- A regular view is a stored query definition. Every time you SELECT from it, the underlying query runs against the current data.
- A materialized view stores the query result physically on disk. Reads are fast because they access precomputed data, but the data can be stale.
- Materialized views must be refreshed to pick up changes. PostgreSQL supports REFRESH MATERIALIZED VIEW and REFRESH MATERIALIZED VIEW CONCURRENTLY for non-blocking refresh.
- You can create indexes on materialized views to speed up queries further, which is not possible with regular views.
Common mistakes
- Assuming materialized views update automatically when the underlying tables change. In most databases, you must explicitly refresh them.
- Using materialized views for frequently changing data without a refresh strategy, which leads to users seeing stale results.
Sample answer
A regular view is essentially a saved SELECT statement. When you query SELECT * FROM my_view, the database runs the underlying query at that moment against live data. A materialized view physically stores the results on disk like a table.
So CREATE MATERIALIZED VIEW monthly_sales AS SELECT product_id, SUM(amount) AS total FROM orders GROUP BY product_id stores the aggregated results. Subsequent queries against monthly_sales read from this precomputed snapshot and are very fast. The trade-off is freshness. I need to run REFRESH MATERIALIZED VIEW monthly_sales to update it with new data.
In PostgreSQL, I can use REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_sales to allow reads during the refresh, but this requires a unique index on the view. I use materialized views for expensive aggregation queries in dashboards where data being a few minutes or hours old is acceptable.
How to level up
- Schedule materialized view refreshes using pg_cron or a background job at intervals that match your data freshness requirements.
- In Oracle, you can create materialized views with ON COMMIT refresh so they update automatically when the underlying tables are modified, but this adds write overhead.
- Consider partial refresh strategies or incremental materialized views for very large datasets where full refresh is too expensive.
Follow-up questions to expect
- How would you decide between a materialized view and a summary table that you maintain with triggers?
- What happens if someone queries a materialized view while it is being refreshed?
- How do materialized views interact with the query optimizer in PostgreSQL?
What are the different transaction isolation levels?
What they're really asking
This tests your understanding of ACID properties and concurrent transaction management. The interviewer wants to see if you understand how databases handle multiple users accessing the same data simultaneously and the trade-offs between data consistency and performance.
How you'll be scored
Lists isolation levels without explaining the problems they solve or their performance implications.
Correctly explains the four isolation levels and what phenomena each prevents.
Demonstrates understanding of isolation level trade-offs, mentions lock duration, and discusses real-world usage scenarios with performance considerations.
How to structure your answer
- Define what transaction isolation solves (concurrent access problems)
- List the four ANSI isolation levels in order.
- Explain what each level prevents (dirty reads, non-repeatable reads, phantom reads)
- Discuss performance trade-offs and when to use each.
- Mention implementation differences across databases.
Key points to hit
- Read Uncommitted allows dirty reads but maximum concurrency, while Serializable prevents all anomalies but may cause blocking.
- Each isolation level represents a trade-off between data consistency and system performance.
- Default isolation levels vary by database (PostgreSQL uses Read Committed, MySQL InnoDB uses Repeatable Read)
- Higher isolation levels typically hold locks longer, reducing concurrency but increasing consistency.
Common mistakes
- Confusing isolation levels with locking mechanisms or not understanding that stricter isolation reduces performance.
- Forgetting that phantom reads can still occur at Repeatable Read level in most databases.
Sample answer
Transaction isolation levels control how concurrent transactions see each other's changes. Read Uncommitted allows dirty reads for maximum performance, Read Committed prevents dirty reads by only showing committed data, Repeatable Read also prevents non-repeatable reads by maintaining consistent snapshots, and Serializable prevents all anomalies including phantom reads but with the highest locking overhead.
In practice, I'd use Read Committed for most OLTP applications because it balances consistency with performance, but might choose Repeatable Read for financial calculations where data consistency during the transaction is critical.
How to level up
- Understand that PostgreSQL implements Repeatable Read as Snapshot Isolation, which is stricter than the ANSI standard.
- Know that some databases like Oracle use multiversion concurrency control (MVCC) to reduce locking overhead.
- Be aware that application-level retry logic is often needed when using higher isolation levels due to serialization failures.
Follow-up questions to expect
- How would you handle a serialization failure in your application code?
- What isolation level would you choose for a banking transfer operation and why?
- How does MVCC help with read performance compared to traditional locking?
What is a deadlock? How do you detect and avoid deadlocks?
What they're really asking
This tests your understanding of concurrent transaction management and database troubleshooting skills. The interviewer wants to see if you can identify, diagnose, and prevent one of the most common database performance problems in multi-user systems.
How you'll be scored
Defines deadlock but cannot explain detection methods or prevention strategies.
Correctly explains deadlock formation and mentions basic detection through wait-for graphs or timeouts.
Demonstrates understanding of deadlock detection algorithms, discusses multiple prevention strategies, and mentions database-specific tools for monitoring and resolution.
How to structure your answer
- Define deadlock as circular wait condition between transactions.
- Explain how databases detect deadlocks (wait-for graphs, timeouts)
- Describe automatic resolution (victim selection and rollback)
- List prevention strategies (lock ordering, timeout values, transaction design)
- Mention monitoring and debugging tools.
Key points to hit
- Deadlocks occur when two or more transactions hold locks and wait for each other in a circular dependency.
- Databases automatically detect deadlocks using wait-for graphs and resolve them by rolling back one transaction (the victim)
- Prevention strategies include consistent lock ordering, keeping transactions short, and using appropriate isolation levels.
- Modern databases provide detailed deadlock information in error logs and monitoring views for debugging.
Common mistakes
- Confusing deadlocks with long-running transactions or simple lock waits.
- Not understanding that deadlock victim selection is typically based on factors like transaction cost or age.
Sample answer
A deadlock happens when two transactions each hold a lock the other needs, creating a circular wait. For example, Transaction A locks Table X then waits for Table Y, while Transaction B locks Table Y then waits for Table X. Databases detect this using wait-for graphs and automatically roll back one transaction as the victim.
To prevent deadlocks, I ensure transactions access tables in consistent order, keep transactions short, and use appropriate isolation levels. I also monitor deadlock graphs in the database logs to identify patterns and redesign problematic queries.
How to level up
- Use database-specific monitoring views like sys.dm_db_deadlock_reports in SQL Server or pg_locks in PostgreSQL to analyze deadlock patterns.
- Consider using SELECT FOR UPDATE with NOWAIT or SKIP LOCKED to avoid blocking in high-contention scenarios.
- Implement exponential backoff retry logic for deadlock victims rather than immediate retry to reduce repeated deadlocks.
Follow-up questions to expect
- How would you redesign a batch process that frequently deadlocks with user transactions?
- What factors does the database consider when choosing a deadlock victim?
- How would you monitor deadlock frequency in a production system?
What is a recursive CTE and when would you use it?
What they're really asking
This tests your knowledge of advanced SQL features for handling hierarchical or iterative data processing. The interviewer wants to see if you understand when recursive queries are appropriate and can write them correctly with proper termination conditions.
How you'll be scored
Explains basic CTE syntax but cannot write a correct recursive query or explain termination conditions.
Demonstrates understanding of recursive CTE structure with anchor and recursive parts, provides a simple example.
Shows mastery of recursive CTE syntax, discusses performance considerations, explains termination conditions, and provides real-world use cases beyond basic tree traversal.
How to structure your answer
- Define recursive CTE as self-referencing common table expression.
- Explain the two-part structure (anchor query and recursive query)
- Show concrete example with proper syntax.
- Discuss termination conditions and infinite loop prevention.
- Mention performance considerations and alternatives.
Key points to hit
- Recursive CTEs have an anchor query (base case) and a recursive query that references the CTE itself.
- The recursive part must eventually return no rows to terminate, or the query will run indefinitely.
- Common use cases include organizational hierarchies, bill of materials, graph traversal, and generating number sequences.
- Performance can degrade with deep recursion, so consider alternatives like iterative processing for large datasets.
Common mistakes
- Forgetting the termination condition which can cause infinite loops.
- Not understanding that the recursive part joins with the previous iteration's results, not the entire CTE.
Sample answer
A recursive CTE is a common table expression that references itself, useful for hierarchical data like organizational charts. It has two parts: an anchor query that defines the starting point, and a recursive query that joins with the CTE itself.
For example, to find all employees under a manager, the anchor selects the top manager, then the recursive part joins employees table with the CTE to find direct reports at each level. The recursion stops when no more rows match the join condition.
I use these for org charts, category trees, and finding connected components in graph data.
How to level up
- Add a depth counter in your recursive CTE to prevent runaway queries and enable depth-limited traversal.
- Use UNION ALL instead of UNION in recursive CTEs for better performance since duplicates are typically not an issue.
- Consider using breadth-first vs depth-first traversal by controlling the ORDER BY in your recursive member.
Follow-up questions to expect
- How would you modify this to do breadth-first instead of depth-first traversal?
- What would you do if the hierarchy could have cycles?
- How would you optimize a recursive CTE that's running too slowly on a large dataset?
Explain database partitioning (horizontal vs vertical).
What they're really asking
This tests your understanding of database scaling strategies and data organization techniques. The interviewer wants to see if you can distinguish between different partitioning approaches and understand when each is appropriate for performance and maintenance.
How you'll be scored
Confuses horizontal and vertical partitioning or cannot explain the benefits of each approach.
Correctly defines both types of partitioning with basic examples and mentions performance benefits.
Demonstrates deep understanding of partitioning strategies, discusses partition elimination, maintenance benefits, and provides specific scenarios where each approach excels.
How to structure your answer
- Define database partitioning as dividing large tables into smaller, manageable pieces.
- Explain horizontal partitioning (splitting rows)
- Explain vertical partitioning (splitting columns)
- Compare benefits and use cases for each.
- Discuss implementation considerations and trade-offs.
Key points to hit
- Horizontal partitioning splits table rows across multiple partitions based on key values (range, hash, or list partitioning)
- Vertical partitioning splits table columns, typically separating frequently accessed from rarely accessed data.
- Horizontal partitioning improves query performance through partition elimination and enables parallel processing.
- Vertical partitioning reduces I/O for queries that only need a subset of columns and can improve cache efficiency.
Common mistakes
- Confusing partitioning with sharding (partitioning is within one database instance)
- Not understanding that partition keys should align with common query patterns for effective partition elimination.
Sample answer
Database partitioning divides large tables into smaller pieces for better performance and maintenance. Horizontal partitioning splits rows, like partitioning an orders table by date range where each partition holds one month of data. This enables partition elimination where queries only scan relevant partitions.
Vertical partitioning splits columns, like separating customer basic info from rarely-used profile details into different partitions. Horizontal partitioning is great for time-series data and parallel processing, while vertical partitioning helps when you have wide tables with distinct access patterns for different column groups.
How to level up
- Choose partition keys that align with your most common WHERE clause conditions to maximize partition elimination benefits.
- Consider partition-wise joins where both tables are partitioned on the same key to enable parallel join processing.
- Design partition boundaries to avoid hot partitions where most inserts go to the same partition.
Follow-up questions to expect
- How would you handle a query that needs to scan all partitions?
- What challenges arise when you need to change the partition key of an existing table?
- How does partitioning affect foreign key constraints?
What is database sharding and how does it differ from partitioning?
What they're really asking
This tests your knowledge of distributed database architecture and horizontal scaling strategies. The interviewer wants to see if you understand the difference between single-instance partitioning and distributed system design, including the complexities that arise with cross-shard operations.
How you'll be scored
Cannot distinguish sharding from partitioning or explain the distributed nature of sharding.
Correctly explains sharding as distributing data across multiple database instances and mentions basic benefits.
Demonstrates understanding of sharding complexities including cross-shard queries, consistency challenges, and rebalancing strategies, while clearly contrasting with partitioning.
How to structure your answer
- Define sharding as horizontal distribution across multiple database instances.
- Contrast with partitioning (single instance vs distributed)
- Explain sharding benefits (horizontal scaling, fault isolation)
- Discuss challenges (cross-shard queries, consistency, rebalancing)
- Mention implementation strategies and when to consider sharding.
Key points to hit
- Sharding distributes data across multiple independent database instances, while partitioning organizes data within a single instance.
- Sharding enables horizontal scaling beyond single-server limits and provides fault isolation between shards.
- Cross-shard operations are expensive and complex, requiring application-level coordination or distributed query engines.
- Shard rebalancing and choosing the right shard key are critical design decisions that are difficult to change later.
Common mistakes
- Using sharding and partitioning interchangeably when they solve different scale problems.
- Not understanding that sharding introduces distributed system complexities like network partitions and consistency challenges.
Sample answer
Sharding distributes data across multiple separate database instances, while partitioning splits data within a single database. For example, sharding a users table might put users A-M on one server and N-Z on another server entirely. This enables scaling beyond single-server hardware limits and isolates failures.
However, sharding introduces complexity - cross-shard queries require application coordination, transactions across shards are difficult, and rebalancing data is operationally complex. I'd only consider sharding when vertical scaling and read replicas are no longer sufficient, and the application can be designed around single-shard operations.
How to level up
- Design your shard key to minimize cross-shard queries by keeping related data together (like user_id for user-centric applications)
- Implement consistent hashing or similar techniques to minimize data movement during shard rebalancing.
- Consider using a shard catalog service to track which data lives on which shard rather than encoding shard logic in application code.
Follow-up questions to expect
- How would you handle a query that needs data from multiple shards?
- What strategies would you use to rebalance shards when one becomes much larger than others?
- How does sharding affect backup and recovery procedures?
What is sargability in SQL and why does it matter for indexing?
What they're really asking
This tests your understanding of query optimization fundamentals and index performance. The interviewer wants to see if you know what makes a query fast or slow at the index level, not just whether you can write working queries.
How you'll be scored
Doesn't know what sargability means or gives vague answers about 'making queries faster.'
Knows sargability means 'search argument able' and that it relates to using indexes effectively.
Explains sargability clearly with examples of sargable vs non-sargable conditions and discusses query plan impact.
How to structure your answer
- Define sargability as 'search argument able' - conditions that can use indexes effectively.
- Give examples of sargable conditions (equality, range with proper operators)
- Show non-sargable examples (functions on columns, complex expressions)
- Explain the performance impact on query execution plans.
- Connect to real-world indexing strategy decisions.
Key points to hit
- Sargable conditions allow the query optimizer to use indexes efficiently because they can directly match index key values without scanning every row.
- Functions or calculations on indexed columns make them non-sargable because the database can't use the index to filter.
- Writing WHERE clauses with sargable predicates is crucial for performance in large tables with proper indexing.
- Non-sargable queries often result in full table scans even when appropriate indexes exist.
Common mistakes
- Confusing sargability with general query optimization or not understanding that it's specifically about index usage.
- Not providing concrete examples of what makes a condition sargable versus non-sargable.
Sample answer
Sargability means 'search argument able' and refers to whether a WHERE clause condition can effectively use an index. A sargable condition like WHERE customer_id = 123 or WHERE order_date >= '2023-01-01' allows the database to jump directly to relevant index entries.
But WHERE UPPER(customer_name) = 'SMITH' is non-sargable because the function prevents index usage, forcing a full table scan. This matters because non-sargable conditions make your indexes useless, turning what should be millisecond lookups into expensive table scans. When designing queries, I always check that my WHERE conditions can leverage existing indexes.
How to level up
- Learn to read execution plans to identify when sargability issues are causing performance problems in production queries.
- Consider computed columns or expression indexes for commonly used non-sargable expressions instead of rewriting all queries.
- Understand that sargability applies differently to different index types (B-tree vs bitmap vs functional indexes)
Follow-up questions to expect
- Can you show me how to rewrite this non-sargable query to make it sargable?
- How would you identify sargability issues in a slow-running query?
- What's the difference between a seek and a scan in a query execution plan?
What are the differences between OLTP and OLAP systems?
What they're really asking
This tests whether you understand fundamental database architecture patterns and can choose the right system design for different business needs. The interviewer wants to see if you grasp the performance and design tradeoffs between transactional and analytical workloads.
How you'll be scored
Confuses the two systems or only gives surface-level differences like 'one is for transactions, one is for reports.'
Correctly identifies OLTP for daily operations and OLAP for analytics with basic architectural differences.
Explains the fundamental design differences, query patterns, schema designs, and when to use each system architecture.
How to structure your answer
- Define OLTP as transaction-focused systems for daily business operations.
- Define OLAP as analytics-focused systems for business intelligence and reporting.
- Compare schema design approaches (normalized vs dimensional modeling)
- Contrast query patterns and performance characteristics.
- Discuss when to use each system type in practice.
Key points to hit
- OLTP systems prioritize fast, concurrent transactions with normalized schemas to maintain data consistency and support high write volumes.
- OLAP systems optimize for complex analytical queries using denormalized, dimensional schemas that support fast aggregations across large datasets.
- Query patterns differ fundamentally: OLTP handles many small, fast queries while OLAP processes fewer but more complex analytical queries.
- Most organizations need both systems, often using ETL processes to move data from OLTP to OLAP for reporting.
Common mistakes
- Thinking you can use the same database design effectively for both transactional and analytical workloads.
- Not understanding that the schema design principles are fundamentally different between the two approaches.
Sample answer
OLTP systems like your typical application database handle daily business transactions with lots of concurrent users doing inserts, updates, and simple lookups. They use normalized schemas to prevent data anomalies and support fast writes. OLAP systems are built for analytics and reporting, using star or snowflake schemas that are heavily denormalized for fast aggregations.
An e-commerce site needs OLTP for processing orders and OLAP for analyzing sales trends. You can't just dump analytical queries on your OLTP system because the normalized structure makes complex reporting queries slow, and heavy reporting can impact transaction performance.
How to level up
- Understand hybrid systems like HTAP (Hybrid Transactional Analytical Processing) that try to handle both workloads in one system.
- Learn about columnar storage and how it specifically benefits OLAP workloads compared to row-based storage in OLTP.
- Consider real-time analytics requirements and how they affect the traditional OLTP to OLAP data pipeline design.
Follow-up questions to expect
- How would you design the ETL process to move data from OLTP to OLAP?
- What are the tradeoffs of using a single database for both OLTP and OLAP workloads?
- How do you handle near real-time analytics when your OLAP system is updated nightly?
How do you handle slowly changing dimensions (SCD Type 2)?
What they're really asking
This tests your knowledge of data warehousing concepts and whether you understand how to track historical changes in dimensional data. The interviewer wants to see if you can design schemas that preserve data history for accurate historical reporting.
How you'll be scored
Doesn't know what SCD means or confuses it with general data versioning approaches.
Knows SCD Type 2 tracks history by creating new rows with effective dates but lacks implementation details.
Explains the complete SCD Type 2 pattern with proper date handling, surrogate keys, and discusses query implications.
How to structure your answer
- Define slowly changing dimensions and why tracking history matters for analytics.
- Explain SCD Type 2 approach of creating new rows for changes.
- Detail the technical implementation with surrogate keys and date columns.
- Show example of how the data looks before and after a change.
- Discuss query patterns and performance considerations.
Key points to hit
- SCD Type 2 preserves complete history by inserting new rows when dimension attributes change, keeping all historical versions accessible.
- Implementation requires surrogate keys, effective start/end dates, and often a current flag to identify the active record.
- Historical fact tables reference the appropriate dimension version through surrogate keys, ensuring point-in-time accuracy.
- Queries need special handling to either get current data or data as it existed at specific points in time.
Common mistakes
- Using natural keys instead of surrogate keys, which breaks historical fact table relationships when dimensions change.
- Not properly managing the effective date logic, leading to gaps or overlaps in the historical timeline.
Sample answer
SCD Type 2 handles changing dimension data by creating a new row each time an attribute changes, preserving the complete history. For example, if a customer moves, instead of updating their address, I insert a new row with the new address and update the date fields.
The old row gets an end date, the new row gets a start date and current flag. I use surrogate keys so historical facts still point to the correct customer information from when the transaction occurred.
This way, sales reports show accurate data as it existed at the time, not just current customer information applied retroactively.
How to level up
- Consider using temporal tables or system-versioned tables in modern databases for automated SCD Type 2 implementation.
- Design your ETL process to handle late-arriving data that might need to insert historical changes in the middle of existing timelines.
- Plan for performance impact of SCD Type 2 dimensions growing large and consider partitioning strategies based on effective dates.
Follow-up questions to expect
- How would you write a query to get customer data as it existed on a specific date?
- What's the difference between SCD Type 1, Type 2, and Type 3 approaches?
- How do you handle the ETL process when you discover a historical change that should have been recorded earlier?
What is dynamic SQL? What are its advantages and risks?
What they're really asking
This tests your understanding of programmatic SQL generation and whether you know the security and maintainability tradeoffs. The interviewer wants to see if you understand when dynamic SQL is appropriate and how to implement it safely.
How you'll be scored
Doesn't understand what dynamic SQL means or only mentions SQL injection without explaining proper use cases.
Knows dynamic SQL builds queries at runtime and mentions both benefits and SQL injection risks.
Explains dynamic SQL clearly with specific use cases, proper parameterization techniques, and discusses performance implications.
How to structure your answer
- Define dynamic SQL as programmatically building SQL statements at runtime.
- Explain legitimate use cases like flexible search interfaces or administrative tools.
- Detail the security risks, especially SQL injection vulnerabilities.
- Show how to implement safely using parameterized queries or stored procedures.
- Discuss performance and maintenance considerations.
Key points to hit
- Dynamic SQL allows building flexible queries based on runtime conditions, useful for complex search interfaces or reporting tools with variable criteria.
- The primary risk is SQL injection if user input is concatenated directly into SQL strings without proper sanitization.
- Safe implementation requires parameterized queries, input validation, and often whitelisting allowed column names or table names.
- Performance can suffer because dynamic queries may not reuse execution plans as effectively as static SQL.
Common mistakes
- Building dynamic SQL through simple string concatenation without parameterization, creating massive security vulnerabilities.
- Using dynamic SQL when static alternatives like conditional WHERE clauses would work just as well.
Sample answer
Dynamic SQL means building SQL statements programmatically at runtime rather than having fixed queries. I've used it for flexible search screens where users can filter by different combinations of fields, and you can't predict all possible WHERE clause combinations.
The main advantage is flexibility, but the huge risk is SQL injection if you concatenate user input directly. I always use parameterized queries and validate inputs, sometimes building a whitelist of allowed column names.
You also lose some query plan caching benefits since each dynamic query might be slightly different, so I only use it when static SQL really can't handle the requirements.
How to level up
- Use query builder libraries or ORM dynamic query features rather than manual string concatenation when possible.
- Consider stored procedures with conditional logic as an alternative that keeps the dynamic aspects on the database server.
- Monitor query plan cache hit rates when using dynamic SQL to identify performance impacts from too many unique query variations.
Follow-up questions to expect
- How would you prevent SQL injection in a dynamic query that needs to accept user-selected column names?
- What's the performance difference between dynamic SQL and using multiple WHERE conditions with OR logic?
- Can you show me how you'd build a safe dynamic query for a flexible reporting interface?
What is a cursor in SQL? When would you use one?
What they're really asking
This tests whether you understand cursor mechanics and can identify appropriate use cases versus set-based alternatives. The interviewer wants to see if you know when procedural row-by-row processing is necessary versus when it hurts performance.
How you'll be scored
Doesn't understand what cursors are or suggests using them for problems better solved with set-based operations.
Knows cursors process data row-by-row and mentions they're generally slower than set-based operations.
Explains cursor mechanics clearly, identifies legitimate use cases, and discusses performance tradeoffs with specific alternatives.
How to structure your answer
- Define cursors as database objects that allow row-by-row processing of result sets.
- Explain the cursor lifecycle (declare, open, fetch, close, deallocate)
- Identify appropriate use cases where row-by-row logic is actually needed.
- Discuss performance implications compared to set-based operations.
- Show alternatives and when to avoid cursors.
Key points to hit
- Cursors enable procedural, row-by-row processing when you need complex logic that can't be expressed in standard set-based SQL operations.
- Legitimate uses include ETL processes with complex business rules per row, generating sequential numbers with gaps, or calling external APIs for each record.
- Performance cost is significant because cursors break SQL's set-based approach and often prevent query optimization.
- Most cursor use cases can be replaced with window functions, CTEs, or other set-based approaches that perform much better.
Common mistakes
- Using cursors for operations that could easily be done with standard SQL aggregations or JOINs.
- Not properly closing and deallocating cursors, which can cause memory leaks and lock issues.
Sample answer
A cursor is a database object that lets you process a result set one row at a time, like a pointer that moves through query results. You declare it with a SELECT statement, open it, then fetch rows in a loop until you're done.
I've used cursors for complex ETL logic where each row needed different processing based on business rules that couldn't be expressed in standard SQL, like calling external web services for validation. The big downside is performance since you lose SQL's set-based optimization.
Most of the time I can avoid cursors by using window functions, CTEs, or JOINs that handle the same logic much faster.
How to level up
- When cursors are unavoidable, use FAST_FORWARD cursors for better performance if you only need to read data sequentially.
- Consider batch processing approaches where you process small sets of rows instead of true row-by-row cursor processing.
- Look into modern alternatives like SQL Server's STRING_AGG or PostgreSQL's array functions that eliminate many traditional cursor use cases.
Follow-up questions to expect
- How would you rewrite this cursor-based solution using set-based SQL instead?
- What's the difference between different cursor types like static, dynamic, and keyset cursors?
- When would you absolutely need a cursor instead of a set-based approach?
How do composite indexes work and how do you choose column order?
What they're really asking
This tests whether you understand multi-column index internals and the leftmost prefix rule. The interviewer wants to see if you can make smart decisions about column ordering that match your actual query patterns.
How you'll be scored
Cannot explain why column order matters or thinks a composite index on (A, B) helps queries filtering only on B.
Correctly explains the leftmost prefix rule and can give a basic example of choosing column order.
Explains the B-tree sorting structure, discusses selectivity-based ordering, covers range scan implications, and shows how one composite index can serve multiple query patterns.
How to structure your answer
- Explain what a composite index is and how it sorts data.
- Describe the leftmost prefix rule.
- Discuss how to choose column order based on query patterns.
- Explain range scan implications on trailing columns.
Key points to hit
- A composite index on (A, B, C) sorts data first by A, then by B within each A value, then by C within each (A, B) pair, similar to a phone book sorted by last name then first name.
- The leftmost prefix rule means the index can serve queries on (A), (A, B), or (A, B, C) but NOT queries filtering only on B or C alone.
- Place equality columns before range columns. An index on (status, created_at) serves WHERE status = 'active' AND created_at > '2026-01-01' efficiently, but reversing the order would not.
- Put the most selective column first among equality conditions to narrow down the search space fastest.
Common mistakes
- Creating a composite index on (A, B) and expecting it to speed up queries that filter only on B.
- Putting a range column before equality columns, which prevents the index from being fully utilized for the equality filter.
Sample answer
A composite index stores rows sorted by multiple columns in the order you specify. An index on (department, hire_date) sorts all rows by department first, then by hire_date within each department.
The leftmost prefix rule means this index works for WHERE department = 'Engineering' and for WHERE department = 'Engineering' AND hire_date > '2025-01-01', but it does NOT help WHERE hire_date > '2025-01-01' alone because the index is not sorted by hire_date globally. For column order, I follow two rules.
First, put equality columns before range columns. If my query is WHERE status = 'active' AND created_at BETWEEN X AND Y, the index should be (status, created_at) so the database finds the exact status partition then scans the date range. Second, among equality columns, put the most selective one first.
If status has 3 values but region has 50, I would order it as (region, status, created_at).
How to level up
- A composite index on (A, B) can also serve ORDER BY queries like WHERE A = 1 ORDER BY B because the B values are already sorted within each A partition.
- Use INCLUDE columns for non-key data that your query needs, making the composite index a covering index without affecting sort order.
- Analyze your workload holistically. One well-designed composite index can replace three single-column indexes and reduce write overhead.
Follow-up questions to expect
- If you have queries on (A, B) and (B, A), do you need two separate indexes?
- How does a composite index affect INSERT and UPDATE performance?
- How would you use EXPLAIN to verify that your composite index is being used correctly?
What is a covering index?
What they're really asking
This tests whether you understand how indexes can satisfy queries entirely without touching the main table. The interviewer wants to see if you know how covering indexes eliminate expensive key lookups and when to use INCLUDE columns.
How you'll be scored
Cannot explain what makes an index "covering" or confuses it with a regular index.
Correctly explains that a covering index contains all columns needed by a query, avoiding table access.
Explains the difference between key columns and INCLUDE columns, demonstrates with EXPLAIN output, and discusses the storage versus performance trade-off.
How to structure your answer
- Define what makes an index a covering index for a specific query.
- Explain the key lookup problem it solves.
- Show the INCLUDE syntax for non-key columns.
- Discuss storage trade-offs.
Key points to hit
- A covering index contains all columns that a query needs in its SELECT, WHERE, JOIN, and ORDER BY clauses, so the query can be answered entirely from the index without accessing the table.
- Without a covering index, the database performs a key lookup (also called bookmark lookup) to fetch missing columns from the table, which adds random I/O for each row.
- INCLUDE columns are stored in the leaf level of the index but not in the sort key, so they do not affect index ordering but make the index covering.
- In execution plans, a covered query shows Index Only Scan (PostgreSQL) or Index Seek without Key Lookup (SQL Server)
Common mistakes
- Adding every column to an index to make it covering, which bloats the index, slows down writes, and consumes excessive storage.
- Not realizing that a covering index is query-specific. The same index might cover one query but not another that selects different columns.
Sample answer
A covering index is one that contains all the columns a specific query needs, so the database never has to go back to the main table.
For example, if my query is SELECT name, email FROM users WHERE status = 'active', and I have an index only on status, the database finds matching rows in the index but then must do a key lookup for each row to fetch name and email. This is expensive.
If I create CREATE INDEX ix_users_covering ON users(status) INCLUDE(name, email), the index leaf pages contain all three columns. The query becomes an Index Only Scan, reading only from the index.
INCLUDE columns are important because they are stored in the index leaves but not in the B-tree sort structure, so they do not waste space in non-leaf pages. The trade-off is that wider indexes use more disk space and slow down inserts and updates slightly.
How to level up
- PostgreSQL does not have INCLUDE syntax before version 11. On older versions, you add the extra columns to the index key, accepting the sort overhead.
- Use execution plans to verify covering. In PostgreSQL look for Index Only Scan. In SQL Server look for the absence of a Key Lookup operator.
- For frequently run queries that select many columns, a covering index can cut query time by 90% or more by eliminating random I/O against the heap or clustered index.
Follow-up questions to expect
- What is the difference between putting a column in the index key versus the INCLUDE list?
- How do you determine which queries would benefit most from covering indexes?
- What is the impact of covering indexes on write performance?
What is the WITH (NOLOCK) hint in SQL Server? When should it be used?
What they're really asking
This tests whether you understand the relationship between locking and data consistency in SQL Server. The interviewer wants to see if you know both the performance benefit and the serious data integrity risks of reading uncommitted data.
How you'll be scored
Says NOLOCK makes queries faster but cannot explain what risks it introduces.
Correctly explains that NOLOCK reads uncommitted data and can see dirty reads, with a basic use case.
Explains dirty reads, phantom reads, and skipped or double-read rows. Discusses specific scenarios where NOLOCK is acceptable and where it is dangerous, and suggests better alternatives like Read Committed Snapshot Isolation.
How to structure your answer
- Explain what NOLOCK does at the locking level.
- Describe the data consistency risks: dirty reads, phantom reads, skipped rows.
- Identify when NOLOCK is acceptable.
- Suggest better alternatives like RCSI.
Key points to hit
- WITH (NOLOCK) is equivalent to READ UNCOMMITTED isolation. It tells SQL Server to skip acquiring shared locks, so it does not block or get blocked by writers.
- The biggest risk is dirty reads: you can read data from a transaction that later rolls back, meaning you saw values that never actually existed in a committed state.
- NOLOCK can also cause rows to be read twice or skipped entirely if a page split happens during your scan, which is a lesser-known but serious issue.
- Read Committed Snapshot Isolation (RCSI) gives similar non-blocking read behavior without dirty read risks by using row versioning in tempdb.
Common mistakes
- Using NOLOCK on tables involved in financial calculations, inventory counts, or any data where accuracy matters, because dirty reads can produce incorrect totals.
- Sprinkling NOLOCK everywhere as a performance fix without understanding that it trades correctness for speed.
Sample answer
WITH (NOLOCK) tells SQL Server to read data without acquiring shared locks, which means your SELECT will not block writers and writers will not block your SELECT. The syntax is SELECT * FROM orders WITH (NOLOCK) WHERE status = 'pending'. The problem is dirty reads.
If another transaction is inserting an order and has not committed yet, your query might see that uncommitted row. If the other transaction rolls back, you just processed data that never existed. Even worse, during a page split your NOLOCK scan can skip rows or read the same row twice.
I would only use NOLOCK for rough estimates on monitoring dashboards where exact numbers do not matter. For production queries that need both non-blocking reads and consistency, I recommend enabling Read Committed Snapshot Isolation at the database level with ALTER DATABASE MyDB SET READ_COMMITTED_SNAPSHOT ON.
RCSI uses row versioning to give you a consistent snapshot without blocking.
How to level up
- NOLOCK only applies to read operations. It has no effect on INSERT, UPDATE, or DELETE statements.
- The SNAPSHOT isolation level is another alternative that provides statement-level consistency like RCSI but at the transaction level, useful for longer-running report queries.
- If you see NOLOCK hints throughout a codebase, it is often a sign that the real fix is enabling RCSI at the database level rather than scattering table hints everywhere.
Follow-up questions to expect
- What is the difference between Read Committed Snapshot Isolation and Snapshot isolation?
- Can you give an example where a dirty read would cause a real business problem?
- How does NOLOCK interact with page splits and what data inconsistencies can result?
How does SQL handle recursive queries?
What they're really asking
This tests whether you can traverse hierarchical or graph-like data structures in SQL using recursive CTEs. The interviewer wants to see if you understand the anchor and recursive member pattern and can apply it to real problems like org charts and bill of materials.
How you'll be scored
Cannot write a recursive CTE or confuses it with a regular CTE.
Shows correct recursive CTE syntax with an anchor member and recursive member for a basic hierarchy.
Explains how the recursion terminates, handles cycle detection, discusses performance on deep hierarchies, and shows multiple practical use cases.
How to structure your answer
- Explain the WITH RECURSIVE CTE structure.
- Define the anchor member and recursive member.
- Show a practical example like an org chart traversal.
- Discuss termination conditions and cycle prevention.
Key points to hit
- Recursive CTEs use WITH RECURSIVE and consist of an anchor member (base case) that selects the starting rows and a recursive member that joins back to the CTE to traverse deeper.
- The recursion terminates when the recursive member returns no new rows, similar to a loop condition.
- The UNION ALL between anchor and recursive members combines results from all levels of the traversal.
- Most databases have a recursion limit (default 100 in PostgreSQL, configurable) to prevent infinite loops on cyclic data.
Common mistakes
- Forgetting UNION ALL between the anchor and recursive member, or using UNION which removes duplicates and can cause incorrect traversal in trees with shared nodes.
- Not adding a depth counter or maximum recursion limit, which risks infinite recursion on data that contains cycles.
Sample answer
SQL handles recursion through recursive CTEs. The pattern has two parts: an anchor member that selects starting rows and a recursive member that references the CTE itself. For example, to get the full reporting chain for employee 42: WITH RECURSIVE org_tree AS (SELECT id, name, manager_id, 1 AS depth FROM employees WHERE id = 42 UNION ALL SELECT e.id, e.name, e.manager_id, ot.depth + 1 FROM employees e JOIN org_tree ot ON e.manager_id = ot.id) SELECT * FROM org_tree. The anchor gets employee 42, then the recursive part finds everyone who reports to them, then everyone who reports to those people, and so on. It stops when no new rows are found. I always add a depth column and a WHERE depth < 20 safety check in the recursive member to prevent infinite loops if the data has cycles. In PostgreSQL, you can also use CYCLE detection syntax added in version 14.
How to level up
- Use recursive CTEs for generating series, like date ranges: start with a base date, then add one day in each recursive step until you hit the end date.
- For very deep hierarchies with thousands of levels, consider using materialized path (storing the full path as a string) or nested set models instead, which avoid recursion at query time.
- PostgreSQL 14 added CYCLE clause support for automatic cycle detection: CYCLE id SET is_cycle USING path.
Follow-up questions to expect
- How would you find all ancestors of a node instead of all descendants?
- What is the performance impact of recursive CTEs on very deep hierarchies?
- How would you detect cycles in hierarchical data using a recursive CTE?
What is lock escalation? Explain optimistic vs pessimistic locking.
What they're really asking
This tests your understanding of concurrency control mechanisms and when each locking strategy is appropriate. The interviewer wants to see if you understand the trade-offs between data safety and throughput.
How you'll be scored
Cannot explain the difference between optimistic and pessimistic locking or what lock escalation means.
Correctly describes both locking strategies and gives a basic explanation of lock escalation.
Explains lock escalation thresholds and memory implications, compares optimistic and pessimistic locking with concrete scenarios, and discusses which approach suits different workload patterns.
How to structure your answer
- Define lock escalation and why it happens.
- Explain pessimistic locking and its use cases.
- Explain optimistic locking and its use cases.
- Compare the two strategies with practical guidance.
Key points to hit
- Lock escalation occurs when the database converts many fine-grained locks (row or page) into a single coarser lock (table) to save memory, since each lock consumes memory.
- Pessimistic locking acquires locks upfront assuming conflicts are likely. SELECT FOR UPDATE locks rows until the transaction completes, preventing other transactions from modifying them.
- Optimistic locking assumes conflicts are rare. It reads data without locks, tracks a version number or timestamp, and checks at write time whether the data changed since the read.
- Pessimistic locking is better for high-contention scenarios. Optimistic locking is better for read-heavy workloads where conflicts are infrequent.
Common mistakes
- Implementing optimistic locking without handling the conflict case, which causes silent data loss when two users edit the same record.
- Using pessimistic locking in a read-heavy, low-contention system where it unnecessarily reduces throughput by blocking readers.
Sample answer
Lock escalation is when the database promotes many row-level locks to a single table-level lock. SQL Server does this around 5,000 row locks because each lock costs about 100 bytes of memory. If you UPDATE a million rows, holding a million row locks wastes memory, so the engine escalates to one table lock.
The downside is this blocks all other access to the table. For concurrency strategy, pessimistic locking grabs locks immediately. I use SELECT * FROM inventory WHERE product_id = 1 FOR UPDATE to lock the row, decrement the quantity, then COMMIT. Nobody else can modify that row until I am done. Optimistic locking works differently.
I read the row with its version: SELECT quantity, version FROM inventory WHERE product_id = 1. I get version 5. Later I write UPDATE inventory SET quantity = quantity - 1, version = 6 WHERE product_id = 1 AND version = 5.
If someone else changed it first, the WHERE clause matches zero rows and I know there was a conflict. I use pessimistic for inventory systems where overselling is unacceptable, and optimistic for user profile edits where conflicts are rare.
How to level up
- You can disable lock escalation on specific tables in SQL Server with ALTER TABLE SET (LOCK_ESCALATION = DISABLE) when table locks would be too disruptive.
- In PostgreSQL, SELECT FOR UPDATE with SKIP LOCKED is powerful for job queue patterns where workers grab the next available row without blocking each other.
- Consider hybrid approaches: use optimistic locking for most operations but fall back to pessimistic locking (SELECT FOR UPDATE) for high-value or high-contention operations.
Follow-up questions to expect
- How would you implement optimistic locking in an application with a version column?
- What happens when lock escalation blocks other queries and how would you prevent it?
- How does SKIP LOCKED work and what is it useful for?
What strategies protect a web application from SQL injection?
What they're really asking
This tests security-first thinking and understanding of SQL injection attack vectors. The interviewer wants to see if you understand both prevention techniques and the underlying vulnerability mechanisms that make SQL injection possible.
How you'll be scored
Only mentions parameterized queries without understanding why they work or other attack vectors.
Covers basic prevention like parameterized queries and input validation with some explanation.
Discusses multiple prevention layers including parameterized queries, least privilege, input validation, and demonstrates understanding of how SQL injection exploits query construction.
How to structure your answer
- Explain what SQL injection is and why it happens.
- Present parameterized queries as the primary defense.
- Cover input validation and sanitization strategies.
- Discuss database-level protections like least privilege.
- Mention additional security layers like WAFs and code review.
Key points to hit
- Parameterized queries prevent injection by separating SQL code from data, so user input never becomes executable code.
- Input validation should whitelist expected patterns rather than blacklist dangerous characters, since attackers find creative bypasses.
- Database users should have minimal necessary privileges so successful injection attacks have limited impact.
- Stored procedures can provide protection but only if they use parameters correctly and don't build dynamic SQL internally.
Common mistakes
- Thinking input sanitization alone is sufficient protection, when parameterized queries are the fundamental requirement.
- Believing that stored procedures automatically prevent injection without considering how they handle parameters internally.
Sample answer
SQL injection happens when user input gets concatenated directly into SQL strings, allowing attackers to inject malicious code. The primary defense is parameterized queries or prepared statements, which separate the SQL structure from the data.
For example, instead of building a query like 'SELECT * FROM users WHERE id = ' + userId, you use a parameter placeholder and bind the value separately.
I also implement input validation with whitelisting for expected patterns, ensure database users have minimal privileges so injection damage is limited, and use tools like static code analysis to catch dynamic query construction during development.
How to level up
- Discuss how ORMs can still be vulnerable if they allow raw SQL or dynamic query building.
- Mention specific database features like SQL Server's sp_executesql or MySQL's prepared statement protocols.
- Explain how second-order SQL injection works where malicious data is stored first then executed later.
Follow-up questions to expect
- How would you detect if your application is currently vulnerable to SQL injection?
- What's the difference between prepared statements and parameterized queries?
- How do you handle cases where you need dynamic table or column names in queries?
How do you ensure data consistency across distributed databases?
What they're really asking
This tests distributed systems thinking and understanding of consistency models. The interviewer wants to see if you grasp the fundamental challenges of maintaining ACID properties across multiple database instances and network partitions.
How you'll be scored
Mentions basic concepts like replication without understanding consistency trade-offs or CAP theorem implications.
Covers two-phase commit and discusses some trade-offs between consistency and availability.
Demonstrates understanding of consistency models, discusses specific protocols like two-phase commit and saga patterns, and explains trade-offs in terms of CAP theorem and business requirements.
How to structure your answer
- Define what data consistency means in distributed context.
- Explain two-phase commit protocol and its limitations.
- Discuss eventual consistency and compensation patterns.
- Cover practical implementation strategies like database sharding approaches.
- Address monitoring and conflict resolution mechanisms.
Key points to hit
- Two-phase commit provides strong consistency but creates availability risks since any node failure can block the entire transaction.
- Eventual consistency with saga patterns allows for better availability but requires designing compensation logic for failed operations.
- CAP theorem forces you to choose between consistency and availability during network partitions, which should align with business requirements.
- Consistent hashing and careful shard key selection can minimize cross-shard transactions that require distributed coordination.
Common mistakes
- Assuming two-phase commit solves all distributed consistency problems without considering its availability and performance costs.
- Not understanding that eventual consistency requires application-level logic to handle intermediate inconsistent states.
Sample answer
Data consistency across distributed databases requires choosing the right consistency model for your use case. For critical operations like financial transactions, I'd use two-phase commit where a coordinator ensures all nodes either commit or abort together, but this sacrifices availability if nodes fail.
For less critical data, I prefer eventual consistency with saga patterns, where each service performs its local transaction and publishes events, with compensation logic to handle failures. The key is designing your data model to minimize cross-database transactions through careful partitioning and accepting that some temporary inconsistency is often acceptable for better system availability.
How to level up
- Discuss specific consistency levels like read-after-write consistency and how they map to business requirements.
- Explain how vector clocks or logical timestamps help detect and resolve conflicts in eventually consistent systems.
- Mention database-specific features like PostgreSQL's logical replication or MongoDB's multi-document transactions.
Follow-up questions to expect
- How would you handle a scenario where two users simultaneously try to book the last available item?
- What's the difference between saga pattern and two-phase commit in terms of failure recovery?
- How do you test distributed consistency logic in your development environment?
What are the trade-offs of using indexes in SQL databases?
What they're really asking
This tests performance optimization thinking and understanding of index internals. The interviewer wants to see if you understand when indexes help versus hurt performance and can make informed decisions about index strategy.
How you'll be scored
Says indexes speed up reads and slow down writes without understanding the underlying mechanisms or specific trade-offs.
Explains basic read/write trade-offs and mentions storage overhead with some examples.
Discusses specific index types, explains B-tree traversal costs, covers maintenance overhead during writes, and demonstrates understanding of when not to use indexes.
How to structure your answer
- Explain how indexes improve read performance through reduced data scanning.
- Detail the write performance costs from index maintenance.
- Discuss storage overhead and memory implications.
- Cover scenarios where indexes can hurt performance.
- Address index selection strategies and monitoring.
Key points to hit
- Indexes speed up reads by creating sorted data structures that allow logarithmic search time instead of linear table scans, but this benefit only applies when queries can use the index.
- Every INSERT, UPDATE, and DELETE must maintain all relevant indexes, which can significantly slow write operations as the number of indexes increases.
- Indexes consume additional storage space and memory for caching, with composite indexes potentially being much larger than single-column ones.
- Too many indexes can confuse the query optimizer and lead to suboptimal execution plans, especially with complex WHERE clauses.
Common mistakes
- Thinking more indexes always improve performance without considering write costs and optimizer confusion.
- Not understanding that indexes are only beneficial when queries actually use them in their execution plans.
Sample answer
Indexes create sorted data structures that turn full table scans into efficient tree traversals, dramatically speeding up reads from potentially millions of row checks to maybe 20 B-tree node lookups. However, every write operation must update all relevant indexes, so a table with 10 indexes has to perform 11 writes for each INSERT.
Storage overhead is significant too since indexes can be as large as the original table. I've seen cases where too many indexes actually hurt performance because the optimizer makes poor choices or because write-heavy workloads spend more time maintaining indexes than the read speedup provides.
How to level up
- Discuss covering indexes that include all needed columns to avoid table lookups entirely.
- Explain index fragmentation and how it degrades performance over time, requiring maintenance.
- Mention partial indexes or filtered indexes that only index rows meeting certain conditions to reduce overhead.
Follow-up questions to expect
- How do you decide which columns should be indexed on a new table?
- What's the difference between clustered and non-clustered indexes in terms of performance?
- How would you identify unused indexes that are wasting resources?
How can you monitor query performance in a production database?
What they're really asking
This tests production database management skills and understanding of performance bottlenecks. The interviewer wants to see if you can proactively identify and diagnose query performance issues in live systems.
How you'll be scored
Mentions basic tools like EXPLAIN without understanding systematic monitoring or how to identify patterns in performance degradation.
Covers query execution plans and some monitoring tools with basic understanding of key metrics.
Discusses comprehensive monitoring strategy including query plan analysis, wait statistics, index usage tracking, and automated alerting for performance regressions.
How to structure your answer
- Establish baseline performance metrics and monitoring infrastructure.
- Use query execution plan analysis to identify bottlenecks.
- Monitor system-level metrics like CPU, I/O, and lock contention.
- Track query performance trends over time to catch regressions.
- Implement automated alerting for performance thresholds.
Key points to hit
- Query execution plans reveal whether queries use indexes effectively or perform expensive operations like full table scans and nested loop joins.
- Wait statistics show what resources queries spend time waiting for, like disk I/O, locks, or CPU, which guides optimization efforts.
- Tracking query duration trends over time helps identify performance regressions before they impact users severely.
- Index usage statistics help identify unused indexes wasting resources and missing indexes causing slow queries.
Common mistakes
- Only monitoring queries after performance problems are already impacting users instead of proactive monitoring.
- Focusing solely on individual slow queries without understanding system-wide resource contention patterns.
Sample answer
I set up comprehensive monitoring that tracks both individual query performance and system-wide patterns. I use execution plan analysis to identify queries doing full table scans or expensive joins, and I monitor wait statistics to see if queries are bottlenecked on disk I/O, CPU, or lock contention.
I maintain baselines for key application queries and set up alerts when their duration increases significantly. Tools like PostgreSQL's pg_stat_statements or SQL Server's Query Store help me track performance trends over time and identify regressions when new code deploys.
I also monitor index usage statistics to find unused indexes consuming resources and missing indexes causing repeated slow queries.
How to level up
- Discuss query fingerprinting to group similar queries with different parameter values for pattern analysis.
- Explain how to correlate database performance metrics with application-level monitoring to understand user impact.
- Mention specific tools like New Relic Database Monitoring, Datadog APM, or database-native solutions like Oracle's AWR.
Follow-up questions to expect
- How do you determine if a slow query is worth optimizing versus acceptable for its usage frequency?
- What's your process when you discover a query that was fast yesterday but is slow today?
- How do you balance monitoring overhead with the need for detailed performance data?
Practical Query Challenges (20)
Write a query to find the Nth highest salary among all employees.
What they're really asking
This tests window function knowledge and understanding of ranking versus filtering approaches. The interviewer wants to see if you can write efficient queries that handle edge cases like salary ties correctly.
How you'll be scored
Uses inefficient approaches like self-joins or multiple subqueries without handling ties correctly.
Provides a working solution using window functions but doesn't discuss tie-handling or performance considerations.
Uses appropriate ranking function, explains the difference between RANK and DENSE_RANK for handling ties, and discusses query performance and edge cases.
How to structure your answer
- Choose between RANK, DENSE_RANK, or ROW_NUMBER based on tie-handling requirements.
- Write the window function query with proper partitioning if needed.
- Filter the results to get the Nth ranked salary.
- Explain how the solution handles edge cases like ties or missing ranks.
- Consider performance implications and alternative approaches.
Key points to hit
- DENSE_RANK handles ties by giving the same rank to equal values and not skipping subsequent ranks, while RANK skips ranks after ties.
- Window functions with ORDER BY perform sorting once rather than multiple table scans like subquery approaches.
- The query needs to handle cases where fewer than N distinct salary values exist in the dataset.
- Performance depends on whether the salary column is indexed since the ORDER BY clause drives the window function.
Common mistakes
- Using ROW_NUMBER instead of RANK/DENSE_RANK, which arbitrarily breaks ties instead of handling them logically.
- Not considering what should happen when multiple employees share the Nth highest salary.
Sample answer
I'll use DENSE_RANK to handle salary ties properly. Here's my solution: WITH ranked_salaries AS (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM employees) SELECT DISTINCT salary FROM ranked_salaries WHERE rank = N. This uses DENSE_RANK because if two people share the second-highest salary, the next person should be ranked third, not fourth.
The DISTINCT ensures we get the salary value itself rather than multiple rows for employees with the same salary. If we need to handle cases where fewer than N salary levels exist, I'd add a check to ensure the rank exists before returning results.
How to level up
- Discuss using OFFSET/LIMIT with DISTINCT salary values as an alternative approach that might perform better with proper indexing.
- Explain when you might want ROW_NUMBER instead, such as when you need exactly one result even with ties.
- Consider partitioning by department if the requirement is Nth highest salary per department rather than globally.
Follow-up questions to expect
- How would you modify this to find the Nth highest salary per department?
- What happens if N is larger than the number of distinct salaries in the table?
- How would you optimize this query for a table with millions of employee records?
Write a query to find duplicate rows in a table and remove them while keeping one copy.
What they're really asking
This tests your ability to combine window functions with data modification to solve a common data quality problem. The interviewer wants to see a safe, working solution that identifies duplicates and removes them without losing any unique data.
How you'll be scored
Writes a DELETE that removes all copies of the duplicate instead of keeping one, or cannot produce a working query.
Produces a correct CTE with ROW_NUMBER approach that identifies and deletes duplicates while keeping one copy.
Provides a complete solution with verification step, explains why ROW_NUMBER is preferred over other methods, and handles edge cases like NULLable columns.
How to structure your answer
- Identify duplicate criteria columns.
- Use ROW_NUMBER to assign sequential numbers within each duplicate group.
- Preview with SELECT before deleting.
- Delete rows where row number is greater than 1.
Key points to hit
- ROW_NUMBER() OVER (PARTITION BY duplicate_columns ORDER BY id) assigns 1 to the row you want to keep and higher numbers to duplicates.
- The PARTITION BY clause defines what makes rows duplicates. If two rows have the same email, PARTITION BY email groups them.
- ORDER BY inside the window function determines which copy survives. ORDER BY id keeps the earliest insert.
- Always run the CTE as a SELECT first to verify the correct rows are targeted before changing it to DELETE.
Common mistakes
- Using GROUP BY with DELETE directly, which cannot target specific rows within each duplicate group.
- Not considering NULL values in duplicate columns, since NULL = NULL returns UNKNOWN and may cause incorrect grouping.
Sample answer
I use a CTE with ROW_NUMBER to number each duplicate. First, I verify with SELECT: WITH ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn FROM users) SELECT * FROM ranked WHERE rn > 1. This shows me exactly which rows will be deleted.
The row with rn = 1 is the one we keep, which is the oldest by id.
Once I confirm the results, I change it to a DELETE: WITH ranked AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn FROM users) DELETE FROM users WHERE id IN (SELECT id FROM ranked WHERE rn > 1).
In PostgreSQL, I can also use DELETE FROM ranked WHERE rn > 1 directly if the CTE is writable. After the delete, I add ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE(email) to prevent future duplicates.
How to level up
- In SQL Server, you can DELETE directly from the CTE: WITH ranked AS (...) DELETE FROM ranked WHERE rn > 1, which is cleaner syntax.
- For tables with no primary key, ROW_NUMBER with PARTITION BY on all columns can still identify true duplicates, but deletion requires using ctid in PostgreSQL or %%physloc%% in SQL Server.
- On very large tables, batch the deletion in chunks using TOP or LIMIT to avoid transaction log bloat and long lock times.
Follow-up questions to expect
- How would this change if the table has no primary key or unique identifier?
- How would you keep the most recent duplicate instead of the oldest?
- What would you do differently on a table with 500 million rows?
Write a query to calculate the running total of sales for each product.
What they're really asking
This tests your fluency with window functions, specifically SUM() OVER with PARTITION BY and ORDER BY to create cumulative totals. The interviewer wants to see if you understand how the window frame works and can partition results correctly.
How you'll be scored
Tries to use GROUP BY for a running total or cannot construct a window function with correct partitioning.
Writes a correct SUM() OVER (PARTITION BY ... ORDER BY ...) query that produces running totals per product.
Explains the default window frame, discusses ROWS versus RANGE behavior, and handles edge cases like ties in the order column.
How to structure your answer
- Explain why GROUP BY alone cannot produce a running total.
- Write the SUM() OVER window function with correct PARTITION BY and ORDER BY.
- Explain the window frame behavior.
- Discuss edge cases with tied order values.
Key points to hit
- SUM(amount) OVER (PARTITION BY product_id ORDER BY sale_date) creates a cumulative sum that resets for each product.
- PARTITION BY divides the result into groups. Each product gets its own independent running total.
- ORDER BY within the window determines the accumulation order. The running total grows as you move through the ordered rows.
- The default window frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which includes all rows with the same ORDER BY value in case of ties.
Common mistakes
- Forgetting ORDER BY in the OVER clause, which makes SUM compute the total for the entire partition in every row instead of a running total.
- Not understanding that RANGE (the default) groups tied values together, while ROWS processes each row individually even with ties.
Sample answer
A running total requires a window function because GROUP BY would collapse rows into one per group. Here is the query: SELECT product_id, sale_date, amount, SUM(amount) OVER (PARTITION BY product_id ORDER BY sale_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM sales ORDER BY product_id, sale_date.
The PARTITION BY product_id restarts the running total for each product. The ORDER BY sale_date accumulates in chronological order. I explicitly specify ROWS instead of RANGE because if two sales happen on the same date, RANGE would include both in the running total for both rows, while ROWS processes them one at a time.
For example, if Product A has sales of 100, 200, 300 on three dates, the running_total column shows 100, 300, 600.
How to level up
- You can add multiple window functions in the same query to show running total alongside a moving average: AVG(amount) OVER (PARTITION BY product_id ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
- If the running total needs to reset at certain boundaries like fiscal quarters, add those boundaries to the PARTITION BY clause.
- For very large datasets, window functions are typically more efficient than correlated subqueries because the database can compute them in a single pass.
Follow-up questions to expect
- What is the difference between ROWS and RANGE in a window frame specification?
- How would you calculate a 7-day moving average instead of a running total?
- How would you write this without window functions using a correlated subquery?
Find employees whose salary is greater than the average salary in their department.
What they're really asking
This tests your ability to compare individual row values against aggregate values within groups. The interviewer wants to see if you can choose between correlated subqueries, window functions, and JOIN-based approaches for this common pattern.
How you'll be scored
Compares against the overall average instead of the department average, or cannot produce a working query.
Writes a correct solution using one approach like a correlated subquery or window function.
Shows multiple approaches, explains the performance trade-offs, and handles edge cases like departments with only one employee.
How to structure your answer
- Show the correlated subquery approach.
- Show the window function approach with AVG() OVER.
- Show the JOIN with derived table approach.
- Compare the three for readability and performance.
Key points to hit
- A correlated subquery calculates the department average for each row: WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.dept_id = e1.dept_id)
- A window function approach computes AVG(salary) OVER (PARTITION BY dept_id) alongside each row and filters in an outer query.
- A JOIN approach calculates department averages in a subquery or CTE, then joins back: JOIN (SELECT dept_id, AVG(salary) as avg_sal FROM employees GROUP BY dept_id) d ON ...
- The JOIN approach is often most readable and performs well because the average is computed once per department rather than once per row.
Common mistakes
- Using WHERE salary > AVG(salary) directly, which is a syntax error because aggregate functions cannot appear in WHERE without a subquery.
- Forgetting that the comparison must be per-department, not across the entire table.
Sample answer
I would use three approaches depending on the situation. The cleanest for readability is a CTE join: WITH dept_avg AS (SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY department_id) SELECT e.name, e.salary, e.department_id, da.avg_salary FROM employees e JOIN dept_avg da ON e.department_id = da.department_id WHERE e.salary > da.avg_salary.
The window function version is: SELECT * FROM (SELECT name, salary, department_id, AVG(salary) OVER (PARTITION BY department_id) AS dept_avg FROM employees) sub WHERE salary > dept_avg. The correlated subquery is: SELECT name, salary FROM employees e1 WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e2.department_id = e1.department_id).
I prefer the CTE approach because it is easiest to read and the aggregate is computed once.
How to level up
- For large tables, the JOIN approach often outperforms correlated subqueries because it avoids recomputing the average for every row in the outer query.
- You can extend this pattern to find employees above the median by using PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY salary) instead of AVG.
- Add the department name and the percentage above average to make the result more useful: (salary - avg_salary) / avg_salary * 100 AS pct_above.
Follow-up questions to expect
- How would you find employees whose salary is within 10% of their department average?
- How would you modify this to use the median instead of the average?
- Which approach would perform best on a table with 10 million employees?
Write a query to retrieve the latest record per user/group.
What they're really asking
This tests your ability to solve the "greatest N per group" problem, which is one of the most common SQL interview patterns. The interviewer wants to see if you know ROW_NUMBER and can compare it to alternative approaches.
How you'll be scored
Uses GROUP BY with MAX but cannot return the full row, only the aggregated columns.
Writes a correct ROW_NUMBER solution with PARTITION BY and filters for row number 1.
Shows multiple approaches including ROW_NUMBER, correlated subquery, and DISTINCT ON (PostgreSQL), and discusses performance differences.
How to structure your answer
- Explain the problem: getting full row data for the latest record per group.
- Show the ROW_NUMBER approach.
- Show alternative approaches like correlated subquery or DISTINCT ON.
- Discuss which performs best and why.
Key points to hit
- ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) assigns 1 to the most recent record per user.
- Wrapping in a CTE or subquery and filtering WHERE rn = 1 gives exactly one row per group.
- PostgreSQL DISTINCT ON is a concise alternative: SELECT DISTINCT ON (user_id) * FROM events ORDER BY user_id, created_at DESC.
- A correlated subquery approach joins on the MAX date: WHERE created_at = (SELECT MAX(created_at) FROM events e2 WHERE e2.user_id = e1.user_id)
Common mistakes
- Using GROUP BY with MAX(created_at) alone, which gives you the latest date but not the other columns from that row.
- Not handling ties where two records have the exact same timestamp, which causes ROW_NUMBER to arbitrarily pick one while RANK would return both.
Sample answer
The standard approach is ROW_NUMBER in a CTE: WITH latest AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn FROM user_events) SELECT * FROM latest WHERE rn = 1. This assigns rn = 1 to the most recent event for each user, then I filter.
In PostgreSQL, the shorter version is SELECT DISTINCT ON (user_id) * FROM user_events ORDER BY user_id, created_at DESC, which returns the first row per user_id after sorting. Another approach is a correlated subquery: SELECT * FROM user_events e1 WHERE created_at = (SELECT MAX(created_at) FROM user_events e2 WHERE e2.user_id = e1.user_id).
The correlated subquery can return multiple rows if two events have the same timestamp. I prefer ROW_NUMBER because it guarantees exactly one row per group and is explicit about tiebreaking.
How to level up
- An index on (user_id, created_at DESC) makes all three approaches much faster by providing sorted access within each group.
- For "latest N per group" instead of just latest 1, change the filter to WHERE rn <= N.
- On very large tables with many groups, a LATERAL JOIN approach can outperform ROW_NUMBER because it can use an index seek per group instead of scanning the entire table.
Follow-up questions to expect
- How would you get the latest 3 records per user instead of just 1?
- What happens if two records have the exact same timestamp?
- How would you optimize this query for a table with 100 million rows and 10 million users?
Calculate month-over-month change in revenue.
What they're really asking
This tests your ability to compare values across adjacent rows using the LAG window function. The interviewer wants to see if you can combine date aggregation with window functions to produce time-series analysis.
How you'll be scored
Cannot use LAG or tries to solve this with a self-join on dates but gets the syntax wrong.
Correctly uses LAG to access the previous month's revenue and calculates the difference.
Produces both absolute and percentage changes, handles the first month gracefully with COALESCE or NULLIF, and discusses edge cases like months with zero revenue.
How to structure your answer
- Aggregate revenue by month first.
- Use LAG to access the previous month's total.
- Calculate both absolute and percentage change.
- Handle the first row where there is no previous month.
Key points to hit
- First aggregate to monthly totals with GROUP BY, then apply LAG on the aggregated result.
- LAG(revenue, 1) OVER (ORDER BY month) gets the previous row's revenue. The second argument is the offset, defaulting to 1.
- Percentage change is (current - previous) / previous * 100. Use NULLIF(previous, 0) to avoid division by zero.
- The first month returns NULL for the LAG value since there is no previous row, which is correct behavior for the first data point.
Common mistakes
- Applying LAG before aggregating, which compares individual transactions instead of monthly totals.
- Dividing by the previous month without handling the case where it might be zero, causing a division by zero error.
Sample answer
I solve this in two steps. First, I aggregate monthly revenue, then use LAG to compare.
WITH monthly AS (SELECT DATE_TRUNC('month', order_date) AS month, SUM(amount) AS revenue FROM orders GROUP BY DATE_TRUNC('month', order_date)) SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev_month_revenue, revenue - LAG(revenue) OVER (ORDER BY month) AS absolute_change, ROUND((revenue - LAG(revenue) OVER (ORDER BY month)) * 100.0 / NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 2) AS pct_change FROM monthly ORDER BY month.
The LAG function pulls the revenue from the previous row ordered by month. I use NULLIF to handle the edge case where previous revenue is zero. The first month will show NULL for previous revenue and changes, which is expected since there is no baseline to compare against.
How to level up
- Use LEAD instead of LAG if you want to show the change relative to the next month rather than the previous one.
- For year-over-year comparison, use LAG(revenue, 12) to look back 12 months instead of 1.
- If months with no sales are missing from the data, generate a complete month series first and LEFT JOIN to fill gaps with zero before applying LAG.
Follow-up questions to expect
- How would you handle months with zero revenue or missing months in the data?
- How would you calculate year-over-year change instead of month-over-month?
- How would you calculate a 3-month rolling average alongside the month-over-month change?
Write a query to find all employees without a manager (orphan rows).
What they're really asking
This tests your understanding of outer join behavior and NULL handling for finding missing relationships. The interviewer wants to see if you can identify orphaned records and understand when LEFT JOIN with IS NULL is more appropriate than NOT EXISTS.
How you'll be scored
Uses INNER JOIN or writes a query that doesn't handle NULL manager_id correctly, missing truly orphaned employees.
Correctly uses LEFT JOIN with IS NULL or NOT EXISTS to find employees without managers.
Provides correct query with explanation of join behavior, discusses NULL handling edge cases, and mentions performance trade-offs between LEFT JOIN and NOT EXISTS approaches.
How to structure your answer
- Identify the relationship between employees and managers.
- Choose between LEFT JOIN with IS NULL vs NOT EXISTS approach.
- Handle edge cases like NULL manager_id vs missing manager records.
- Consider performance implications.
- Test the logic with sample data scenarios.
Key points to hit
- LEFT JOIN preserves all employee records even when no manager match exists, then IS NULL filters to only unmatched rows.
- Distinguish between employees with NULL manager_id (top-level executives) versus employees whose manager_id references non-existent records.
- NOT EXISTS can be more performant than LEFT JOIN when the manager table is large because it can stop at first match.
- Always consider whether the business wants both types of 'orphans' or just one specific case.
Common mistakes
- Using INNER JOIN which eliminates the exact rows you're trying to find.
- Forgetting to handle the case where manager_id is explicitly NULL versus referencing a non-existent manager.
Sample answer
I'll use LEFT JOIN to find employees without managers. Here's my query: SELECT e.employee_id, e.name FROM employees e LEFT JOIN employees m ON e.manager_id = m.employee_id WHERE m.employee_id IS NULL. This joins the employees table to itself, preserving all employee records even when no manager exists.
The WHERE clause filters to only rows where the manager side is NULL, meaning either the manager_id is NULL or references a non-existent employee. I'm using LEFT JOIN with IS NULL rather than NOT EXISTS because it's often more readable, though NOT EXISTS might perform better with proper indexing.
How to level up
- Discuss whether you want employees with explicit NULL manager_id versus those referencing deleted managers, as these might need different business handling.
- Consider using NOT EXISTS for better performance when dealing with large datasets and proper indexing exists.
- Mention that this pattern is useful for data quality checks to find referential integrity violations.
Follow-up questions to expect
- How would you modify this to find employees whose managers were recently deleted?
- Which approach would perform better with 1 million employees: LEFT JOIN or NOT EXISTS?
- How would you handle a multi-level hierarchy where you want employees with no manager at any level?
Compute a funnel conversion rate (visit -> signup -> purchase).
What they're really asking
This tests your ability to use conditional aggregation and understand funnel analysis patterns. The interviewer wants to see if you can calculate conversion rates across sequential steps using CASE statements within aggregate functions.
How you'll be scored
Attempts multiple separate queries or uses incorrect aggregation that double-counts users across funnel steps.
Correctly uses conditional aggregation with CASE statements to count users at each funnel step and calculates conversion rates.
Provides correct funnel query with proper user deduplication, explains the conditional aggregation pattern, and discusses how to handle edge cases like users skipping steps.
How to structure your answer
- Identify the sequential funnel steps and their relationships.
- Use conditional aggregation to count unique users at each step.
- Calculate conversion rates as ratios between consecutive steps.
- Handle edge cases like users who skip steps.
- Consider time windows and user deduplication.
Key points to hit
- Conditional aggregation with CASE inside COUNT lets you count different events in a single pass through the data.
- Always use DISTINCT user_id within conditional counts to avoid double-counting users who perform the same action multiple times.
- Conversion rates should be calculated as step N / step N-1, not step N / step 1, unless measuring overall funnel conversion.
- Consider whether users can skip steps and how that affects your funnel logic.
Common mistakes
- Double-counting users who perform the same action multiple times by not using DISTINCT.
- Calculating all conversion rates from the first step rather than consecutive steps.
Sample answer
I'll use conditional aggregation to calculate funnel conversion rates in a single query.
Here's my approach: WITH funnel AS (SELECT COUNT(DISTINCT CASE WHEN event_type = 'visit' THEN user_id END) as visits, COUNT(DISTINCT CASE WHEN event_type = 'signup' THEN user_id END) as signups, COUNT(DISTINCT CASE WHEN event_type = 'purchase' THEN user_id END) as purchases FROM events WHERE event_date >= '2024-01-01') SELECT visits, signups, purchases, ROUND(100.0 * signups / visits, 2) as visit_to_signup_rate, ROUND(100.0 * purchases / signups, 2) as signup_to_purchase_rate FROM funnel.
The CASE statements count distinct users at each step, and I calculate conversion rates as percentages between consecutive steps.
How to level up
- Add time window constraints to ensure you're measuring conversions within a reasonable timeframe.
- Consider using window functions to analyze conversion rates across different time periods or user segments.
- Handle the edge case where users might skip the signup step by going directly from visit to purchase.
Follow-up questions to expect
- How would you modify this to show conversion rates by day or week?
- What if users can purchase without signing up? How does that affect the funnel?
- How would you identify where users are dropping off most in the funnel?
Write a query to find customers who haven't ordered in the last 60 days (churned).
What they're really asking
This tests your understanding of date arithmetic and ability to identify inactive users using temporal logic. The interviewer wants to see if you can correctly handle date comparisons and choose the right approach between LEFT JOIN and NOT EXISTS for finding missing recent activity.
How you'll be scored
Uses incorrect date arithmetic or writes a query that includes customers who have ordered recently.
Correctly identifies customers without orders in the last 60 days using proper date arithmetic and NULL handling.
Provides correct query with clear date logic, discusses edge cases like new customers, and explains performance considerations between different approaches.
How to structure your answer
- Define the 60-day cutoff date using current date.
- Choose between LEFT JOIN with date filter vs NOT EXISTS approach.
- Handle edge cases like customers who never ordered.
- Consider timezone and date precision issues.
- Optimize for performance with proper indexing strategy.
Key points to hit
- Use CURRENT_DATE - INTERVAL 60 DAY or equivalent date arithmetic to define the cutoff dynamically.
- LEFT JOIN with date range in the ON clause preserves all customers, then filter for NULL order matches.
- Distinguish between customers who haven't ordered recently versus customers who never ordered if business requirements differ.
- Date comparisons should consider whether you want exactly 60 days or more than 60 days ago.
Common mistakes
- Putting the date filter in WHERE instead of ON clause when using LEFT JOIN, which converts it to an inner join.
- Using incorrect date arithmetic that doesn't account for the database's date function syntax.
Sample answer
I need to find customers with no orders in the last 60 days. Here's my query: SELECT c.customer_id, c.name FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id AND o.order_date >= CURRENT_DATE - INTERVAL 60 DAY WHERE o.customer_id IS NULL.
The key is putting the date filter in the ON clause so the LEFT JOIN preserves all customers, then filtering for NULL matches. This captures both customers who haven't ordered recently and customers who never ordered. The INTERVAL 60 DAY gives me exactly 60 days ago from today.
How to level up
- Consider whether the business wants to distinguish between 'never ordered' and 'hasn't ordered recently' for different retention strategies.
- Use NOT EXISTS instead of LEFT JOIN for better performance when the orders table is very large.
- Add customer registration date to exclude customers who signed up less than 60 days ago if that's not true churn.
Follow-up questions to expect
- How would you modify this to exclude customers who registered in the last 60 days?
- What if you wanted to find customers churning at different time intervals like 30, 60, and 90 days?
- How would you make this query perform better with millions of orders?
Sessionize user events using a 30-minute inactivity window.
What they're really asking
This tests your understanding of window functions and temporal logic for complex session analysis. The interviewer wants to see if you can use LAG to compare timestamps and implement stateful logic with cumulative operations.
How you'll be scored
Attempts to solve with basic GROUP BY or doesn't understand how to use LAG for comparing consecutive events.
Correctly uses LAG to identify session breaks and assigns session IDs, but explanation may be unclear.
Provides correct sessionization logic with clear explanation of LAG function, discusses edge cases like first events, and explains how the cumulative sum creates session boundaries.
How to structure your answer
- Order events by user and timestamp to enable LAG comparison.
- Use LAG to get previous event timestamp and identify session breaks.
- Use cumulative SUM to assign session IDs based on session break flags.
- Handle edge cases like first event per user.
- Consider performance optimization for large datasets.
Key points to hit
- LAG gets the previous event timestamp within each user's partition, enabling comparison of consecutive events.
- A session break occurs when the gap between current and previous event exceeds 30 minutes.
- Cumulative SUM over the session break flags creates incrementing session IDs.
- The first event for each user always starts a new session since LAG returns NULL.
Common mistakes
- Forgetting to partition by user_id in the LAG function, which would compare events across different users.
- Not handling the NULL case from LAG for the first event of each user.
Sample answer
I'll use window functions to sessionize user events with a 30-minute inactivity threshold.
Here's my approach: WITH session_breaks AS (SELECT user_id, event_time, CASE WHEN LAG(event_time) OVER (PARTITION BY user_id ORDER BY event_time) IS NULL OR event_time > LAG(event_time) OVER (PARTITION BY user_id ORDER BY event_time) + INTERVAL 30 MINUTE THEN 1 ELSE 0 END as new_session FROM events), sessions AS (SELECT user_id, event_time, SUM(new_session) OVER (PARTITION BY user_id ORDER BY event_time) as session_id FROM session_breaks) SELECT user_id, session_id, MIN(event_time) as session_start, MAX(event_time) as session_end FROM sessions GROUP BY user_id, session_id.
The LAG function compares each event to the previous one, flagging session breaks when the gap exceeds 30 minutes, then cumulative SUM creates unique session IDs.
How to level up
- Consider using ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW in your window frame to make the cumulative sum explicit.
- For very large datasets, consider partitioning by date in addition to user to improve performance.
- Add session duration and event count metrics to make the output more useful for analysis.
Follow-up questions to expect
- How would you modify this to handle different inactivity thresholds for different user types?
- What if you wanted to exclude very short sessions with only one event?
- How would you optimize this query for a table with billions of events?
Compute D1/D7/D30 retention cohorts.
What they're really asking
This tests your ability to use self-joins and date arithmetic for cohort analysis. The interviewer wants to see if you can join a table to itself with complex date conditions and understand retention metrics calculation.
How you'll be scored
Attempts separate queries for each retention period or doesn't understand how to self-join with date arithmetic.
Correctly uses self-joins with date arithmetic to calculate retention rates for the specified periods.
Provides correct cohort retention query with clear date logic, explains the self-join pattern, and discusses how to handle edge cases like incomplete cohorts.
How to structure your answer
- Identify user first activity date as cohort assignment.
- Self-join to find return activity at specific intervals.
- Use conditional aggregation to calculate retention rates for multiple periods.
- Handle edge cases like users at cohort boundaries.
- Consider calendar vs business day calculations.
Key points to hit
- Self-join the users table where the first instance gets the cohort start date and the second instance checks for return activity.
- Use DATE arithmetic like cohort_date + INTERVAL 1 DAY for D1, + INTERVAL 7 DAY for D7, etc.
- Conditional aggregation counts retained users as a percentage of the original cohort size.
- Cohort date should typically be the user's first activity date, not registration date.
Common mistakes
- Using registration date instead of first activity date for cohort assignment, which can skew retention metrics.
- Not handling incomplete cohorts where insufficient time has passed to measure retention.
Sample answer
I'll calculate retention cohorts using self-joins with date arithmetic.
First, I'll get each user's first activity date as their cohort, then self-join to check for return visits: WITH cohorts AS (SELECT user_id, DATE(MIN(activity_date)) as cohort_date FROM user_activity GROUP BY user_id), retention AS (SELECT c.cohort_date, COUNT(DISTINCT c.user_id) as cohort_size, COUNT(DISTINCT CASE WHEN a1.user_id IS NOT NULL THEN c.user_id END) as d1_retained, COUNT(DISTINCT CASE WHEN a7.user_id IS NOT NULL THEN c.user_id END) as d7_retained, COUNT(DISTINCT CASE WHEN a30.user_id IS NOT NULL THEN c.user_id END) as d30_retained FROM cohorts c LEFT JOIN user_activity a1 ON c.user_id = a1.user_id AND DATE(a1.activity_date) = c.cohort_date + INTERVAL 1 DAY LEFT JOIN user_activity a7 ON c.user_id = a7.user_id AND DATE(a7.activity_date) = c.cohort_date + INTERVAL 7 DAY LEFT JOIN user_activity a30 ON c.user_id = a30.user_id AND DATE(a30.activity_date) = c.cohort_date + INTERVAL 30 DAY GROUP BY c.cohort_date) SELECT cohort_date, cohort_size, ROUND(100.0 * d1_retained / cohort_size, 2) as d1_retention_rate, ROUND(100.0 * d7_retained / cohort_size, 2) as d7_retention_rate, ROUND(100.0 * d30_retained / cohort_size, 2) as d30_retention_rate FROM retention ORDER BY cohort_date.
This gives me retention percentages for each cohort.
How to level up
- Filter out incomplete cohorts that don't have enough time for full retention measurement.
- Consider using date ranges instead of exact dates for retention periods to capture more user activity.
- Add cohort size thresholds to exclude small cohorts that might have unstable retention rates.
Follow-up questions to expect
- How would you modify this to show retention curves over time rather than specific day intervals?
- What if you wanted to segment retention by user acquisition channel or demographics?
- How would you handle users who are active multiple days around the retention measurement date?
Write a query to detect overlapping date ranges (e.g., subscriptions).
What they're really asking
This tests your ability to work with date range logic and self-joins to detect data quality issues. The interviewer wants to see if you can write queries that identify overlapping periods without missing edge cases like touching dates or nested ranges.
How you'll be scored
Uses a cross join without proper conditions, creating a Cartesian product, or misses edge cases like same start/end dates.
Writes a correct self-join with proper overlap conditions but doesn't explain the logic or consider performance.
Delivers a correct self-join with clear overlap logic, explains why the conditions work, and discusses indexing strategy for date columns.
How to structure your answer
- Define what constitutes an overlap (start1 < end2 AND start2 < end1)
- Set up self-join to compare each row against all others.
- Add conditions to avoid comparing a row to itself.
- Include proper date range overlap logic.
- Consider performance implications for large datasets.
Key points to hit
- Overlap occurs when start1 < end2 AND start2 < end1, which handles all overlap scenarios including nested ranges.
- Self-join requires filtering out same-row comparisons using unique identifiers.
- Consider whether touching dates (end1 = start2) should count as overlaps based on business rules.
- Index strategy on date columns is crucial for performance on subscription or booking tables.
Common mistakes
- Using >= or <= incorrectly, which can miss true overlaps or include false positives.
- Forgetting to exclude self-comparisons, leading to every row appearing to overlap with itself.
Sample answer
I'd use a self-join approach here. SELECT s1.subscription_id, s2.subscription_id FROM subscriptions s1 JOIN subscriptions s2 ON s1.user_id = s2.user_id AND s1.subscription_id < s2.subscription_id AND s1.start_date < s2.end_date AND s2.start_date < s1.end_date. The key insight is that two date ranges overlap when the first starts before the second ends AND the second starts before the first ends. I'm using subscription_id < to avoid comparing each pair twice, and I'm filtering to the same user since overlaps only matter within a user's subscriptions.
How to level up
- Add a CASE statement to categorize overlap types: nested, partial, or identical ranges.
- Consider using window functions with LEAD/LAG if data is naturally ordered and you only need to check adjacent periods.
- For very large tables, consider partitioning the self-join by a dimension like user_id or region to improve performance.
Follow-up questions to expect
- How would you modify this to find gaps between date ranges instead of overlaps?
- What indexes would you create to optimize this query on a table with millions of subscription records?
- How would you handle the case where you want to find overlaps across different subscription types?
Find the top N rows per group (e.g., top 3 products per category).
What they're really asking
This tests your understanding of window functions and ranking logic to solve common analytical problems. The interviewer wants to see if you can partition data correctly and handle ties appropriately when finding top performers within groups.
How you'll be scored
Attempts to use GROUP BY with LIMIT or tries a correlated subquery that performs poorly and may not handle ties correctly.
Uses ROW_NUMBER() or RANK() with proper PARTITION BY but doesn't explain the difference between ranking functions or performance considerations.
Chooses the right ranking function for the use case, explains partitioning logic clearly, and discusses how to handle ties and performance optimization.
How to structure your answer
- Choose appropriate ranking function (ROW_NUMBER, RANK, or DENSE_RANK)
- Set up PARTITION BY for the grouping dimension.
- Define ORDER BY for the ranking criteria.
- Wrap in subquery or CTE to filter to top N.
- Consider tie-breaking logic if needed.
Key points to hit
- ROW_NUMBER() assigns unique ranks and breaks ties arbitrarily, while RANK() gives tied rows the same rank but skips subsequent ranks.
- PARTITION BY resets the ranking for each group, which is essential for top-N-per-group queries.
- The outer query filters WHERE rank <= N to get the top N from each partition.
- Performance depends on having proper indexes on both the partition column and order column.
Common mistakes
- Using GROUP BY instead of window functions, which limits what columns you can select.
- Forgetting that you can't filter window function results directly in WHERE clause, requiring a subquery or CTE.
Sample answer
I'd use a window function approach with ROW_NUMBER(). WITH ranked_products AS (SELECT product_id, category_id, revenue, ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY revenue DESC) as rn FROM products) SELECT product_id, category_id, revenue FROM ranked_products WHERE rn <= 3. The PARTITION BY resets the ranking for each category, and ORDER BY revenue DESC puts highest revenue first. I chose ROW_NUMBER() over RANK() because it guarantees exactly 3 products per category even with ties.
How to level up
- Use DENSE_RANK() if you want exactly N distinct values per group, even when there are ties.
- Consider adding tie-breaking criteria in ORDER BY (like product_name) for consistent results across query runs.
- For very large datasets, ensure your partition key has good cardinality to avoid memory issues with large window partitions.
Follow-up questions to expect
- How would you modify this to get the top 3 and bottom 3 products per category in a single query?
- What's the difference between using ROW_NUMBER() and RANK() for this problem when there are tied revenue values?
- How would you optimize this query if you had millions of products across thousands of categories?
Calculate year-over-year sales growth by product or region.
What they're really asking
This tests your ability to work with LAG window functions and percentage calculations to analyze time-series data. The interviewer wants to see if you can correctly calculate growth rates while handling edge cases like null previous values and division by zero.
How you'll be scored
Attempts self-joins or correlated subqueries instead of window functions, or calculates percentage growth incorrectly.
Uses LAG correctly to get previous year values and calculates growth percentage, but doesn't handle null or zero denominators.
Implements LAG with proper partitioning, calculates growth correctly with null and division-by-zero handling, and explains when to use different growth formulas.
How to structure your answer
- Use LAG to get previous year's sales value within each partition.
- Set up PARTITION BY for product/region to keep comparisons within groups.
- Calculate percentage growth as (current - previous) / previous * 100.
- Handle null previous values and division by zero.
- Consider date filtering and aggregation if needed.
Key points to hit
- LAG(sales, 1) OVER (PARTITION BY product_id ORDER BY year) gets the previous year's sales for each product separately.
- Growth percentage formula is ((current - previous) / previous) * 100, but handle division by zero when previous sales were zero.
- NULLIF helps prevent division by zero: NULLIF(previous_sales, 0)
- Partitioning by product/region ensures you're comparing the same entity across time periods.
Common mistakes
- Forgetting to partition by product/region, causing LAG to compare across different entities.
- Not handling null values from LAG (when there's no previous year) or zero denominators in percentage calculations.
Sample answer
I'd use LAG to get each product's previous year sales, then calculate the growth rate.
WITH sales_with_previous AS (SELECT product_id, year, sales, LAG(sales, 1) OVER (PARTITION BY product_id ORDER BY year) as previous_year_sales FROM annual_sales) SELECT product_id, year, sales, CASE WHEN previous_year_sales IS NULL THEN NULL WHEN previous_year_sales = 0 THEN NULL ELSE ROUND(((sales - previous_year_sales) / previous_year_sales * 100), 2) END as yoy_growth FROM sales_with_previous.
The PARTITION BY product_id ensures I'm comparing each product to its own previous year, not mixing products.
How to level up
- Consider using COALESCE or CASE to provide meaningful labels like 'New Product' when previous year sales are null.
- For more complex growth analysis, you might want LAG(sales, 2) to compare against two years ago or use multiple LAG functions.
- Add data quality checks to ensure your date/year columns have the expected values before calculating growth.
Follow-up questions to expect
- How would you modify this to calculate quarter-over-quarter growth instead of year-over-year?
- What would you do if you wanted to calculate growth compared to the same month last year, handling seasonal patterns?
- How would you identify products with the highest growth acceleration (growth rate that's increasing over time)?
Write a query to deduplicate rows and keep only the latest record.
What they're really asking
This tests your understanding of window functions for data quality tasks and your knowledge of DELETE operations with CTEs. The interviewer wants to see if you can identify duplicates correctly and safely remove them while preserving the most recent data.
How you'll be scored
Uses GROUP BY with MAX/MIN in a way that makes it hard to delete specific rows, or writes a DELETE that could remove wrong records.
Uses ROW_NUMBER() to identify duplicates and writes a working DELETE statement, but doesn't explain the logic or consider safety measures.
Implements ROW_NUMBER() with proper partitioning and ordering, writes a safe DELETE with CTE, and discusses backup strategies and verification steps.
How to structure your answer
- Define what makes rows duplicates (partition columns)
- Use ROW_NUMBER() to rank rows within each duplicate group.
- Order by timestamp/date to keep the latest record.
- Write DELETE statement using CTE to remove rows where ROW_NUMBER > 1.
- Verify the deduplication worked correctly.
Key points to hit
- ROW_NUMBER() OVER (PARTITION BY duplicate_key_columns ORDER BY timestamp DESC) assigns rank 1 to the most recent duplicate.
- Partition by the columns that define duplicates (like email, product_id, etc.) while ordering by timestamp to preserve latest.
- DELETE with CTE allows you to use window functions: WITH cte AS (SELECT *, ROW_NUMBER()...) DELETE FROM cte WHERE rn > 1.
- Always test the logic with SELECT first before running DELETE to verify you're removing the right rows.
Common mistakes
- Ordering by timestamp ASC instead of DESC, which would keep the oldest record instead of the newest.
- Forgetting that you can't use window functions directly in DELETE WHERE clause without a CTE.
Sample answer
I'd use ROW_NUMBER() with a CTE to identify and remove duplicates. First, I'd test with SELECT: WITH duplicate_cte AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY email, product_id ORDER BY created_at DESC) as rn FROM user_purchases) SELECT * FROM duplicate_cte WHERE rn > 1. This shows me exactly which rows will be deleted.
Then I'd run the DELETE: WITH duplicate_cte AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY email, product_id ORDER BY created_at DESC) as rn FROM user_purchases) DELETE FROM duplicate_cte WHERE rn > 1. The PARTITION BY defines what makes rows duplicates, and ORDER BY created_at DESC ensures I keep the most recent purchase.
How to level up
- Consider using a backup table or transaction with rollback capability before running DELETE operations on important data.
- For very large tables, you might want to DELETE in batches to avoid locking issues and long-running transactions.
- Add a verification step after deletion to count remaining rows and ensure no valid data was accidentally removed.
Follow-up questions to expect
- How would you handle this deduplication if the table didn't have a reliable timestamp column?
- What approach would you use for deduplication on a table with millions of rows where the DELETE might time out?
- How would you modify this logic if you wanted to merge data from duplicates instead of just keeping the latest?
Compute A/B test conversion uplift from experiment data.
What they're really asking
This tests your ability to use conditional aggregation with CASE statements to analyze experiment results. The interviewer wants to see if you can calculate conversion rates by group and compute statistical significance measures for A/B testing.
How you'll be scored
Calculates basic conversion rates but doesn't compute uplift correctly or misses the statistical significance aspect of A/B testing.
Uses conditional aggregation to get conversion rates by variant and calculates uplift percentage, but doesn't discuss confidence or sample size considerations.
Implements proper conditional aggregation, calculates uplift with statistical context, and discusses sample size requirements and confidence intervals for valid A/B test results.
How to structure your answer
- Use conditional aggregation to calculate conversions and total users per variant.
- Calculate conversion rates for control and treatment groups.
- Compute absolute and relative uplift (treatment - control)
- Consider statistical significance and sample size.
- Format results clearly showing both rates and uplift.
Key points to hit
- Conditional aggregation: SUM(CASE WHEN variant = 'treatment' AND converted = 1 THEN 1 ELSE 0 END) counts treatment conversions.
- Conversion rate = conversions / total_users for each variant, multiplied by 100 for percentage.
- Relative uplift = ((treatment_rate - control_rate) / control_rate) * 100 shows percentage improvement.
- Sample size and conversion counts determine if results are statistically significant, typically need hundreds of conversions per variant.
Common mistakes
- Calculating uplift as treatment_rate - control_rate without dividing by control_rate, giving absolute difference instead of relative improvement.
- Not considering sample size, which makes it impossible to determine if differences are meaningful or just random variation.
Sample answer
I'd use conditional aggregation to get conversion rates by variant, then calculate uplift.
SELECT SUM(CASE WHEN variant = 'control' AND converted = 1 THEN 1 ELSE 0 END) as control_conversions, COUNT(CASE WHEN variant = 'control' THEN 1 END) as control_users, SUM(CASE WHEN variant = 'treatment' AND converted = 1 THEN 1 ELSE 0 END) as treatment_conversions, COUNT(CASE WHEN variant = 'treatment' THEN 1 END) as treatment_users FROM experiment_data.
Then I'd calculate rates and uplift: treatment_rate = treatment_conversions/treatment_users, control_rate = control_conversions/control_users, and relative_uplift = ((treatment_rate - control_rate) / control_rate) * 100. This tells me the percentage improvement of treatment over control.
How to level up
- Add confidence interval calculations using standard error formulas for conversion rates to determine statistical significance.
- Consider segmentation by user characteristics or time periods to identify where the uplift is strongest.
- Include checks for minimum sample size requirements before declaring results significant, typically 1000+ users and 100+ conversions per variant.
Follow-up questions to expect
- How would you modify this query to calculate conversion uplift segmented by user demographics like age group or region?
- What additional metrics would you calculate to understand if this uplift is practically significant, not just statistically significant?
- How would you extend this analysis to handle a multi-variant test with 3 or more treatment groups?
Write a query to find the longest continuous login streak per user.
What they're really asking
This tests window function mastery and date manipulation skills. The interviewer wants to see if you can identify data gaps and consecutive patterns using LAG and partitioning logic.
How you'll be scored
Uses cursors or multiple self-joins without window functions, creating inefficient solutions.
Correctly uses LAG with ROW_NUMBER but doesn't handle edge cases like missing days.
Efficiently uses window functions with proper gap detection and explains the streak calculation logic clearly.
How to structure your answer
- Identify what constitutes a 'streak' (consecutive login days)
- Use LAG to find gaps between login dates.
- Create streak groups using cumulative logic.
- Calculate streak lengths and find the maximum per user.
- Handle edge cases like same-day multiple logins.
Key points to hit
- LAG function compares current login date with previous to identify gaps greater than 1 day.
- ROW_NUMBER combined with date arithmetic creates unique streak identifiers.
- PARTITION BY user_id ensures streak calculations are isolated per user.
- Handle duplicate login dates on same day by using DISTINCT or DATE function.
Common mistakes
- Not accounting for multiple logins on the same day, which can break streak logic.
- Using LEAD instead of LAG, which looks forward instead of backward in the date sequence.
Sample answer
I'd start with a CTE that uses LAG to compare each login date with the previous one per user. SELECT user_id, login_date, LAG(login_date) OVER (PARTITION BY user_id ORDER BY login_date) as prev_date. Then I'd identify streak breaks where the date difference is greater than 1 day using CASE WHEN DATEDIFF(login_date, prev_date) > 1.
Finally, I'd use SUM with a window frame to create streak group IDs, then calculate the length of each streak and find the maximum per user. The key is handling same-day duplicates upfront with DISTINCT.
How to level up
- Consider using DENSE_RANK instead of ROW_NUMBER if you need to handle ties in login timestamps.
- For very large datasets, ensure there's a composite index on (user_id, login_date) for optimal window function performance.
- Discuss whether to count streaks as calendar days or 24-hour periods, as this affects the business logic.
Follow-up questions to expect
- How would you modify this to find streaks within the last 90 days only?
- What if we wanted to allow 1-day gaps in streaks (like weekends don't break streaks)?
- How would you optimize this query for a table with 100 million login records?
Calculate customer lifetime value (LTV) and bucket users by tier.
What they're really asking
This tests aggregation skills and business metric understanding. The interviewer wants to see if you can calculate complex business KPIs using conditional logic and handle customer segmentation.
How you'll be scored
Calculates simple revenue totals without considering time periods or proper LTV methodology.
Correctly sums revenue per customer and creates basic tiers using CASE statements.
Implements proper LTV calculation with time-weighted analysis and creates meaningful business tiers with statistical justification.
How to structure your answer
- Define LTV calculation method (total spend, average order value times frequency, or predictive)
- Aggregate customer data across all transactions.
- Calculate relevant metrics like recency, frequency, monetary value.
- Create tier boundaries using statistical methods or business rules.
- Present results with tier counts and LTV ranges.
Key points to hit
- LTV calculation should consider customer lifespan, not just total historical spend.
- Use CASE statements with percentiles or fixed dollar amounts to create meaningful tiers.
- Include metrics like average order value and purchase frequency for richer segmentation.
- Consider using NTILE function to create evenly distributed tiers based on LTV distribution.
Common mistakes
- Calculating LTV as simple SUM of purchases without considering customer lifecycle stage.
- Creating arbitrary tier boundaries without understanding the actual data distribution.
Sample answer
I'd calculate LTV by joining customers with their order history and summing total spend, then add frequency metrics. WITH customer_metrics AS (SELECT customer_id, SUM(order_amount) as total_spend, COUNT(*) as order_count, AVG(order_amount) as avg_order_value, DATEDIFF(CURDATE(), MAX(order_date)) as days_since_last FROM orders GROUP BY customer_id).
Then I'd create tiers using CASE WHEN total_spend >= 1000 THEN 'High Value' WHEN total_spend >= 500 THEN 'Medium Value' ELSE 'Low Value'. I'd validate tier boundaries by checking the distribution to ensure each tier has meaningful customer counts.
How to level up
- Consider using RFM analysis (Recency, Frequency, Monetary) with weighted scoring for more sophisticated segmentation.
- Implement predictive LTV using customer cohort analysis and churn probability.
- Use window functions like PERCENT_RANK to create dynamic tier boundaries based on data distribution.
Follow-up questions to expect
- How would you adjust LTV calculation for subscription businesses versus transactional businesses?
- What metrics would you add to identify customers at risk of churning within each tier?
- How would you handle seasonal customers who make large purchases infrequently?
Write a query that dynamically pivots rows into columns.
What they're really asking
This tests advanced SQL techniques and dynamic query construction. The interviewer wants to see if you understand PIVOT operations and can discuss when dynamic SQL is appropriate versus static solutions.
How you'll be scored
Suggests manual CASE statements for each column without understanding dynamic requirements.
Uses PIVOT syntax correctly but doesn't address the dynamic nature of unknown column values.
Demonstrates both static PIVOT and dynamic SQL approaches, explaining trade-offs and security considerations.
How to structure your answer
- Clarify whether column values are known in advance or truly dynamic.
- Show static PIVOT approach for known values.
- Demonstrate dynamic SQL construction for unknown values.
- Discuss security implications and alternatives.
- Compare performance characteristics of both approaches.
Key points to hit
- Static PIVOT requires knowing column values at query time but is more secure and performant.
- Dynamic PIVOT uses string concatenation to build SQL but requires careful SQL injection protection.
- Consider using conditional aggregation with CASE statements as an alternative to PIVOT.
- Dynamic SQL should use parameterization or whitelist validation for column names.
Common mistakes
- Building dynamic SQL with direct string concatenation, creating SQL injection vulnerabilities.
- Not considering that PIVOT creates fixed columns, making it unsuitable for truly dynamic scenarios in application code.
Sample answer
For known values, I'd use static PIVOT: SELECT * FROM (SELECT customer_id, product_category, revenue FROM sales) t PIVOT (SUM(revenue) FOR product_category IN ('Electronics', 'Clothing', 'Books')).
For dynamic columns, I'd build the query string: DECLARE @sql NVARCHAR(MAX); SELECT @sql = 'SELECT * FROM sales_data PIVOT (SUM(revenue) FOR product_category IN (' + @cols + '))'; where @cols comes from a subquery of DISTINCT values. However, I'd prefer conditional aggregation for better maintainability: SELECT customer_id, SUM(CASE WHEN category='Electronics' THEN revenue END) as Electronics.
How to level up
- Use QUOTENAME() function to properly escape dynamic column names and prevent injection.
- Consider creating a stored procedure that accepts category list as table-valued parameter for safer dynamic pivoting.
- For very wide pivots, evaluate whether a reporting tool or application-level transformation might be more appropriate.
Follow-up questions to expect
- How would you handle NULL values in the pivot columns differently than zero values?
- What's your approach when the number of pivot columns exceeds database column limits?
- How would you modify this to show both counts and sums in the pivoted result?
Flag outliers based on z-score calculation.
What they're really asking
This tests statistical analysis capabilities and window function expertise. The interviewer wants to see if you can implement statistical concepts in SQL and understand when to flag data anomalies.
How you'll be scored
Uses simple comparison logic without understanding z-score calculation or statistical significance.
Correctly implements z-score formula using AVG and STDDEV with basic outlier flagging.
Implements robust z-score calculation with proper null handling, discusses threshold selection, and considers different outlier detection methods.
How to structure your answer
- Calculate population mean and standard deviation for the dataset.
- Implement z-score formula: (value - mean) / standard_deviation.
- Define outlier threshold (typically |z-score| > 2 or 3)
- Flag records exceeding the threshold.
- Handle edge cases like zero standard deviation or null values.
Key points to hit
- Z-score formula measures how many standard deviations a value is from the mean.
- Use STDDEV() window function to calculate standard deviation across the population or partition.
- Typical outlier thresholds are z-score > 2 (95% confidence) or z-score > 3 (99.7% confidence)
- Handle division by zero when standard deviation is zero (all values identical)
Common mistakes
- Using sample standard deviation (STDDEV_SAMP) when you want population standard deviation (STDDEV_POP)
- Not handling the edge case where standard deviation is zero, causing division by zero errors.
Sample answer
I'd calculate the z-score using window functions: WITH stats AS (SELECT value, AVG(value) OVER() as mean_val, STDDEV_POP(value) OVER() as stddev_val FROM dataset), z_scores AS (SELECT value, CASE WHEN stddev_val = 0 THEN 0 ELSE (value - mean_val) / stddev_val END as z_score FROM stats).
Then I'd flag outliers: SELECT *, CASE WHEN ABS(z_score) > 2.5 THEN 'Outlier' ELSE 'Normal' END as outlier_flag. I chose 2.5 as the threshold to catch significant outliers while avoiding too many false positives. I also handled the zero standard deviation case to prevent division errors.
How to level up
- Consider using modified z-score with median and MAD (median absolute deviation) for more robust outlier detection with skewed data.
- Implement rolling z-scores using window frames if you want to detect outliers within time periods rather than globally.
- For large datasets, consider using APPROX_QUANTILES for percentile-based outlier detection as an alternative to z-scores.
Follow-up questions to expect
- How would you modify this to detect outliers within different categories or time periods?
- What would you do if the data is heavily skewed and z-scores aren't appropriate?
- How would you handle seasonal patterns where outliers are relative to expected seasonal values?
Ready to put this into practice?
Try these questions in a mock interview →Still applying for jobs? Let Auto Apply do it
Database Design Questions (15)
What is normalization? Explain 1NF, 2NF, 3NF, and BCNF.
What they're really asking
This tests fundamental database design knowledge and data integrity understanding. The interviewer wants to see if you grasp why normalization prevents data anomalies and can design maintainable schemas.
How you'll be scored
Gives vague definitions without explaining the problems normalization solves or providing concrete examples.
Correctly defines each normal form with basic examples but doesn't connect to real-world design decisions.
Explains each normal form with clear examples, discusses trade-offs between normalization and performance, and demonstrates understanding of when to denormalize.
How to structure your answer
- Define normalization as eliminating data redundancy and update anomalies.
- Explain each normal form with progression and examples.
- Discuss the problems each form solves (insert, update, delete anomalies)
- Address when denormalization might be appropriate.
- Connect to practical database design decisions.
Key points to hit
- 1NF requires atomic values and eliminates repeating groups in single columns.
- 2NF eliminates partial dependencies where non-key columns depend on part of a composite key.
- 3NF eliminates transitive dependencies where non-key columns depend on other non-key columns.
- BCNF is stricter 3NF where every determinant is a candidate key, handling edge cases with multiple overlapping candidate keys.
Common mistakes
- Confusing functional dependency direction (A determines B means B depends on A, not vice versa)
- Not understanding that normalization primarily prevents update anomalies, not just saves storage space.
Sample answer
Normalization eliminates data redundancy to prevent update anomalies. 1NF requires atomic values, so instead of storing 'phone1, phone2' in one column, you separate them. 2NF eliminates partial dependencies, like moving customer details out of an order-item table since they depend on order_id, not the full composite key. 3NF removes transitive dependencies, such as storing customer_state separately from customer_zip since state depends on zip, not customer.
BCNF handles cases where multiple candidate keys create dependencies. The goal is preventing situations where updating one row requires updating multiple places, which causes inconsistency bugs. However, I'd consider denormalization for read-heavy reporting tables where query performance outweighs update complexity.
How to level up
- Learn about 4NF and 5NF for handling multivalued dependencies, though they're rarely needed in practice.
- Understand that most OLTP systems target 3NF while OLAP systems often denormalize for query performance.
- Consider using views to provide denormalized query interfaces over normalized storage tables.
Follow-up questions to expect
- Can you give an example where you might intentionally violate 3NF for performance reasons?
- How do you handle normalization in a system that needs both fast writes and fast reads?
- What's your approach to normalizing hierarchical data like organizational charts or product categories?
What is denormalization and when would you use it?
What they're really asking
This tests your understanding of database normalization trade-offs and when performance or query simplicity justifies breaking normal forms. The interviewer wants to see if you can balance data integrity against practical system requirements.
How you'll be scored
Only defines denormalization as storing duplicate data without understanding when or why to use it.
Correctly explains denormalization and provides basic use cases like read performance.
Explains denormalization with specific trade-offs, discusses when normalized vs denormalized designs are appropriate, and mentions maintenance costs.
How to structure your answer
- Define denormalization clearly.
- Explain the trade-offs between normalization and denormalization.
- Give specific scenarios where denormalization helps.
- Discuss the costs and risks.
- Mention implementation strategies.
Key points to hit
- Denormalization intentionally introduces redundancy to improve query performance by reducing joins.
- Use when read performance is critical and you can manage data consistency through application logic.
- Common in data warehousing, reporting systems, and high-traffic read-heavy applications.
- Always weigh faster reads against slower writes and potential data inconsistency.
Common mistakes
- Suggesting denormalization without considering the maintenance overhead of keeping redundant data synchronized.
- Not mentioning that denormalization typically helps reads but hurts writes and storage.
Sample answer
Denormalization means intentionally adding redundant data to reduce the number of joins needed for common queries. I'd use it when read performance is more critical than storage efficiency or write speed.
For example, in a reporting system where we're constantly joining orders with customer data, I might store customer names directly in the orders table instead of always joining to the customers table.
The trade-off is that updates become more complex since I need to update customer names in multiple places, but queries run much faster since they avoid expensive joins.
How to level up
- Discuss materialized views as a middle ground between full normalization and denormalization.
- Mention specific denormalization patterns like storing calculated values or flattening hierarchies.
- Consider modern solutions like read replicas with different schemas for analytical vs transactional workloads.
Follow-up questions to expect
- How would you handle data consistency when you have denormalized data?
- What are some alternatives to denormalization for improving query performance?
- Can you give an example of when you would NOT denormalize despite performance benefits?
How do you implement one-to-one, one-to-many, and many-to-many relationships?
What they're really asking
This tests your knowledge of foreign key implementations and relationship cardinality in database design. The interviewer wants to see if you understand how to properly model different business relationships using tables and constraints.
How you'll be scored
Vaguely describes relationships without showing concrete table structures or foreign key usage.
Correctly shows table structures for each relationship type with proper foreign key placement.
Shows proper table designs with foreign keys, discusses indexing considerations, and explains how to enforce referential integrity for each relationship type.
How to structure your answer
- Explain one-to-one with table example and foreign key placement.
- Show one-to-many implementation with parent-child tables.
- Demonstrate many-to-many using junction tables.
- Discuss foreign key constraints and referential integrity.
- Mention indexing implications for each type.
Key points to hit
- One-to-one uses a foreign key in either table, often with a unique constraint to enforce the relationship.
- One-to-many places the foreign key in the 'many' side table pointing to the 'one' side primary key.
- Many-to-many requires a junction table containing foreign keys to both related tables.
- Always consider which direction queries will flow to determine optimal foreign key placement and indexing.
Common mistakes
- Putting foreign keys on the wrong side of one-to-many relationships, which creates multiple columns for the same data.
- Not using junction tables for many-to-many, which violates first normal form.
Sample answer
For one-to-one, like users and user profiles, I put a foreign key in one table pointing to the other's primary key, usually with a unique constraint. For one-to-many, like customers to orders, the foreign key goes in the orders table pointing to the customer ID.
For many-to-many, like students and courses, I create a junction table called student_courses with foreign keys to both the students and courses tables. I always add indexes on foreign key columns since they're frequently used in joins, and I use foreign key constraints to maintain referential integrity.
How to level up
- Consider performance implications of cascade deletes and updates in high-volume systems.
- Discuss when to use composite foreign keys for relationships involving composite primary keys.
- Mention how relationship types affect query patterns and whether you need indexes on both sides of relationships.
Follow-up questions to expect
- How would you handle a relationship that could be either one-to-many or many-to-many depending on business requirements?
- What are the performance implications of different foreign key constraint actions like CASCADE vs RESTRICT?
- How do you decide whether to split a one-to-one relationship into separate tables?
What is a composite key? When would you use one?
What they're really asking
This tests your understanding of multi-column primary keys and when single-column keys aren't sufficient. The interviewer wants to see if you recognize business scenarios where natural composite keys are the best solution.
How you'll be scored
Defines composite key as multiple columns but doesn't explain when or why you'd use one.
Correctly explains composite keys and gives a basic example like order line items.
Explains composite keys with multiple realistic examples, discusses trade-offs versus surrogate keys, and mentions indexing implications.
How to structure your answer
- Define composite key as primary key made of multiple columns.
- Explain when no single column uniquely identifies a row.
- Provide concrete business examples.
- Discuss indexing and performance considerations.
- Compare to surrogate key alternatives.
Key points to hit
- Composite keys use multiple columns together to uniquely identify each row when no single column is sufficient.
- Common in junction tables, time-series data, and situations modeling real-world compound identifiers.
- The order of columns in a composite key affects index performance for partial key lookups.
- Consider surrogate keys as alternatives when composite keys become unwieldy or when you need simpler foreign key references.
Common mistakes
- Using composite keys when a simple surrogate key would be more maintainable.
- Not considering that partial key lookups only use the index if they include the leftmost columns of the composite key.
Sample answer
A composite key is a primary key made up of multiple columns that together uniquely identify each row. I use them when no single column can guarantee uniqueness. For example, in an order_items table, I might use order_id plus product_id as the composite key since a customer can only order each product once per order.
Another example is time-series data where I might use sensor_id plus timestamp. The main consideration is that queries using only part of the key can only use the index efficiently if they include the leftmost columns.
How to level up
- Discuss how composite key column order affects query performance for different access patterns.
- Consider when adding a surrogate key alongside a composite unique constraint gives you flexibility.
- Mention that foreign keys referencing composite keys must include all columns, which can make related table designs more complex.
Follow-up questions to expect
- When would you choose a surrogate key instead of a natural composite key?
- How does the order of columns in a composite key affect query performance?
- Can you give an example of when a composite key might need to be changed and how you'd handle that migration?
Define candidate key, alternate key, and surrogate key.
What they're really asking
This tests your knowledge of different key types in relational database theory and their practical applications. The interviewer wants to see if you understand the theoretical foundation behind primary key selection and database design choices.
How you'll be scored
Confuses the definitions or can't explain the practical differences between key types.
Correctly defines each key type and provides basic examples.
Defines each key type clearly, explains when to use each one, and discusses the trade-offs between natural and surrogate keys in real systems.
How to structure your answer
- Define candidate key as any column set that could uniquely identify rows.
- Explain alternate keys as candidate keys not chosen as primary.
- Define surrogate keys as artificial identifiers.
- Compare natural vs surrogate key trade-offs.
- Give examples of when each type is most appropriate.
Key points to hit
- Candidate keys are any combination of columns that could serve as a primary key for the table.
- Alternate keys are candidate keys you didn't select as the primary key, often enforced with unique constraints.
- Surrogate keys are artificially generated identifiers like auto-increment IDs that have no business meaning.
- Choose natural keys when the business identifier is stable, surrogate keys when natural identifiers might change or are complex.
Common mistakes
- Thinking alternate keys aren't important after choosing a primary key, when they often represent important business constraints.
- Always defaulting to surrogate keys without considering whether natural keys would be more appropriate.
Sample answer
A candidate key is any column or combination that could uniquely identify every row, like email address or social security number in a users table. Alternate keys are the candidate keys I didn't choose as primary, but I still enforce them with unique constraints since they represent real business rules.
Surrogate keys are artificial identifiers I generate, like auto-increment IDs, that have no business meaning. I prefer natural keys when they're stable and simple, like product codes, but use surrogate keys when natural identifiers might change or when I need to hide internal structure from external APIs.
How to level up
- Discuss how surrogate keys can simplify foreign key relationships and make schema changes easier.
- Consider the security implications of exposing natural keys vs surrogate keys in URLs or APIs.
- Mention that you can use both surrogate keys for internal relationships and natural keys for business logic.
Follow-up questions to expect
- What are the advantages and disadvantages of using UUIDs as surrogate keys instead of auto-increment integers?
- How do you handle a situation where a natural key you've been using turns out not to be as unique as expected?
- When might you have multiple alternate keys on the same table?
How do you design a database schema for high scalability?
What they're really asking
This tests your understanding of database architecture decisions for high-traffic systems and data growth. The interviewer wants to see if you can think beyond basic normalization to consider partitioning, replication, and schema design for scale.
How you'll be scored
Focuses only on basic normalization without considering performance, partitioning, or scaling strategies.
Mentions key concepts like indexing, partitioning, and read replicas with basic explanations.
Discusses comprehensive scaling strategies including horizontal partitioning, denormalization trade-offs, caching layers, and how schema design affects scaling decisions.
How to structure your answer
- Start with proper normalization as foundation.
- Discuss indexing strategy for high-volume queries.
- Explain partitioning and sharding approaches.
- Cover read replica and caching strategies.
- Address denormalization decisions for performance.
Key points to hit
- Begin with properly normalized schema but plan for strategic denormalization in high-read areas.
- Design partitioning strategy early, typically by date ranges or hash of user IDs for even distribution.
- Index strategy must consider both query patterns and write performance since indexes slow down inserts.
- Separate read and write workloads through replicas and potentially different schema optimizations for each.
Common mistakes
- Over-normalizing without considering query patterns, leading to complex joins on high-traffic queries.
- Not planning for data growth and having to retrofit partitioning later when tables are already huge.
Sample answer
I start with a properly normalized schema but immediately identify high-traffic query patterns that might need denormalization. For partitioning, I typically use time-based partitioning for event data and hash-based partitioning for user data to distribute load evenly. I'm strategic about indexes, focusing on the most critical queries while avoiding over-indexing that would slow writes.
I plan for read replicas early and sometimes maintain slightly different schemas on replicas optimized for reporting workloads. The key is designing the schema so it can scale horizontally, which often means avoiding complex cross-partition joins.
How to level up
- Consider event sourcing or CQRS patterns where write and read models can have completely different optimizations.
- Plan for schema migrations at scale by designing backward-compatible changes and feature flags for gradual rollouts.
- Design primary keys that distribute evenly across partitions, avoiding hotspots from sequential IDs or timestamp-based keys.
Follow-up questions to expect
- How do you handle transactions that need to span multiple partitions or shards?
- What strategies do you use for schema migrations in a high-availability system?
- How do you decide between vertical scaling database hardware versus horizontal scaling through sharding?
What is a star schema vs snowflake schema in data warehousing?
What they're really asking
This tests data warehousing schema design expertise and ability to make architectural decisions. The interviewer wants to see if you understand dimensional modeling concepts and can choose appropriate schemas based on query patterns and maintenance requirements.
How you'll be scored
Confuses the schemas or gives vague descriptions without explaining the structural differences and use cases.
Correctly describes both schemas with basic structural differences but lacks insight into when to use each.
Explains both schemas clearly, discusses trade-offs between query performance vs maintenance complexity, and provides specific use cases for each approach.
How to structure your answer
- Define star schema structure with fact table at center connected to dimension tables.
- Define snowflake schema as normalized version where dimension tables are broken into sub-dimensions.
- Compare query performance characteristics of each approach.
- Discuss storage and maintenance trade-offs.
- Provide specific scenarios where each is preferred.
Key points to hit
- Star schema has denormalized dimension tables directly connected to fact table, enabling simpler joins and faster queries.
- Snowflake schema normalizes dimension tables into multiple related tables, reducing storage redundancy but requiring more complex joins.
- Query performance generally favors star schema due to fewer joins, while snowflake schema offers better data integrity and storage efficiency.
- Choice depends on query complexity, data volume, update frequency, and whether storage or performance is the priority.
Common mistakes
- Thinking snowflake schema is always better because it's normalized, ignoring the query performance impact of additional joins.
- Not explaining the practical implications of each design choice on actual warehouse operations and query patterns.
Sample answer
A star schema has a central fact table surrounded by denormalized dimension tables, like a star. For example, a sales fact table directly connects to customer, product, and time dimension tables. A snowflake schema takes those dimension tables and normalizes them further, so the customer dimension might split into customer, city, and region tables.
Star schemas are faster for queries because you need fewer joins, but they use more storage due to denormalization. Snowflake schemas save storage and maintain better data integrity, but queries are more complex.
I'd choose star schema for read-heavy analytics workloads where query speed matters most, and snowflake when storage costs are high or dimension data changes frequently.
How to level up
- Discuss hybrid approaches where only frequently changing dimensions are normalized while stable ones remain denormalized.
- Mention how modern columnar databases and in-memory processing can affect the performance trade-offs between these schemas.
- Consider data loading complexity and how dimension changes propagate differently in each schema type.
Follow-up questions to expect
- How would you handle slowly changing dimensions in each schema type?
- What factors would make you choose a galaxy schema over star or snowflake?
- How do modern cloud data warehouses like Snowflake or BigQuery affect these design decisions?
What is the difference between OLTP and OLAP database design?
What they're really asking
This tests understanding of fundamental database architecture patterns and ability to choose appropriate designs for different workloads. The interviewer wants to see if you can distinguish between transactional and analytical database requirements.
How you'll be scored
Confuses OLTP and OLAP characteristics or gives superficial definitions without understanding the design implications.
Correctly identifies basic differences but doesn't explain how these differences drive specific design decisions.
Clearly explains both systems, discusses specific design patterns for each, and demonstrates understanding of how workload characteristics determine schema choices.
How to structure your answer
- Define OLTP as transaction-focused systems optimized for concurrent read/write operations.
- Define OLAP as analytics-focused systems optimized for complex queries and reporting.
- Compare normalization approaches and why they differ.
- Discuss indexing strategies and performance characteristics.
- Explain how business requirements drive the choice between approaches.
Key points to hit
- OLTP systems use highly normalized schemas to minimize data redundancy and ensure fast individual transactions with ACID compliance.
- OLAP systems often use denormalized or dimensional schemas to optimize for complex analytical queries across large datasets.
- OLTP focuses on row-level operations with many concurrent users, while OLAP handles batch processing and aggregations across historical data.
- Indexing strategies differ significantly, with OLTP using indexes for specific lookups and OLAP using columnstore or bitmap indexes for analytical queries.
Common mistakes
- Assuming OLTP must always be fully normalized without considering performance trade-offs for specific use cases.
- Not recognizing that modern systems often blend OLTP and OLAP characteristics depending on specific requirements.
Sample answer
OLTP systems like e-commerce databases are designed for high-volume transactions with many concurrent users. They use normalized schemas to prevent update anomalies and ensure data consistency. For example, customer orders would be split across orders, order_items, and products tables. OLAP systems like data warehouses are optimized for analytical queries.
They often denormalize data into fact and dimension tables because analysts need to aggregate sales across multiple dimensions quickly. OLTP prioritizes fast inserts, updates, and individual record lookups, while OLAP prioritizes complex queries that scan large amounts of historical data.
The choice depends on whether you're building an operational system that processes transactions or an analytical system that supports business intelligence.
How to level up
- Mention HTAP (Hybrid Transactional/Analytical Processing) systems that attempt to handle both workloads efficiently.
- Discuss how cloud architectures enable separating OLTP and OLAP concerns while keeping data synchronized.
- Consider how real-time analytics requirements are blurring the traditional boundaries between OLTP and OLAP.
Follow-up questions to expect
- How would you design a system that needs both real-time transactions and analytical reporting?
- What are the challenges of synchronizing data between OLTP and OLAP systems?
- How do modern technologies like columnar storage affect OLTP vs OLAP design decisions?
How do you enforce referential integrity in a database?
What they're really asking
This tests knowledge of database constraints and relationship management. The interviewer wants to see if you understand how to maintain data consistency across related tables and prevent orphaned records.
How you'll be scored
Only mentions foreign keys without understanding cascade options or practical implementation considerations.
Correctly explains foreign key constraints but lacks depth on cascade behaviors and performance implications.
Explains multiple referential integrity mechanisms, discusses cascade options thoughtfully, and addresses performance and design trade-offs.
How to structure your answer
- Define referential integrity as ensuring relationships between tables remain consistent.
- Explain foreign key constraints as the primary enforcement mechanism.
- Discuss cascade options and their appropriate use cases.
- Address performance considerations and indexing requirements.
- Mention alternative approaches and when they're necessary.
Key points to hit
- Foreign key constraints automatically prevent insertion of records with invalid references and deletion of referenced parent records.
- CASCADE DELETE removes child records when parent is deleted, while CASCADE UPDATE maintains relationships when primary keys change.
- RESTRICT or NO ACTION options prevent parent record changes that would violate referential integrity, requiring manual cleanup first.
- Foreign keys require indexes on both sides of the relationship for optimal performance, especially on the referencing column.
Common mistakes
- Using CASCADE DELETE carelessly without considering the business impact of automatically deleting related data.
- Not indexing foreign key columns, leading to performance problems during joins and constraint checking.
Sample answer
I enforce referential integrity primarily through foreign key constraints, which ensure that child table records can only reference existing parent records. For example, an order_items table would have a foreign key to the orders table, preventing orphaned line items.
I'm careful with cascade options, using CASCADE DELETE only when child records should always be removed with parents, like deleting all order items when an order is cancelled. For cases like customer deletion where orders should be preserved, I use RESTRICT to prevent deletion until orders are handled appropriately.
I always ensure foreign key columns are indexed since the database needs to check these relationships frequently, and unindexed foreign keys can cause serious performance issues during deletes and updates.
How to level up
- Consider using soft deletes instead of CASCADE DELETE for audit trail requirements and to prevent accidental data loss.
- Discuss deferred constraint checking for complex multi-table operations that might temporarily violate integrity.
- Mention how distributed databases handle referential integrity differently and may require application-level enforcement.
Follow-up questions to expect
- How would you handle referential integrity in a microservices architecture where tables are in different databases?
- What's your approach when you need to delete a parent record that has many child references?
- How do you balance referential integrity with performance in high-throughput systems?
What are the best practices for ensuring data integrity?
What they're really asking
This tests comprehensive understanding of data quality and consistency mechanisms beyond just referential integrity. The interviewer wants to see if you can design robust systems that prevent data corruption and maintain accuracy.
How you'll be scored
Lists basic constraints without understanding their appropriate use or implementation strategies.
Mentions multiple integrity mechanisms but lacks insight into how they work together as a comprehensive strategy.
Presents a holistic approach combining database constraints, application logic, and validation strategies with clear reasoning for each choice.
How to structure your answer
- Outline database-level constraints as the foundation of data integrity.
- Discuss application-level validation and business rule enforcement.
- Address transaction management and consistency requirements.
- Explain monitoring and validation strategies for ongoing integrity.
- Consider backup and recovery procedures as integrity safeguards.
Key points to hit
- Use database constraints (NOT NULL, CHECK, UNIQUE, FOREIGN KEY) as the first line of defense because they cannot be bypassed.
- Implement application-level validation for complex business rules that cannot be expressed in simple database constraints.
- Design transactions carefully to maintain consistency across multiple tables, using appropriate isolation levels and rollback strategies.
- Establish regular data validation processes and integrity checks to detect and fix corruption that might occur over time.
Common mistakes
- Relying only on application-level validation without database constraints, which leaves data vulnerable to direct database modifications.
- Creating overly complex CHECK constraints that hurt performance, when business logic validation might be more appropriate.
Sample answer
I ensure data integrity through multiple layers of protection. At the database level, I use NOT NULL constraints for required fields, CHECK constraints for valid ranges like positive prices, and UNIQUE constraints for business keys. Foreign keys maintain referential integrity between related entities.
At the application level, I validate complex business rules that can't be expressed as simple constraints, like ensuring order quantities don't exceed inventory. I use transactions to group related changes and ensure they succeed or fail together.
For ongoing integrity, I implement regular validation jobs that check for data anomalies and automated tests that verify critical business rules. Finally, I maintain comprehensive backups and test recovery procedures because even the best prevention can't stop all corruption.
How to level up
- Implement data lineage tracking to understand how data flows through your system and identify integrity issues at their source.
- Use database triggers judiciously for complex integrity rules that span multiple tables but be aware of their performance impact.
- Consider implementing data quality metrics and monitoring to proactively detect integrity issues before they impact users.
Follow-up questions to expect
- How do you handle data integrity during large-scale data migrations or system integrations?
- What's your strategy for maintaining integrity in eventually consistent distributed systems?
- How do you balance strict data validation with system performance and user experience?
What is an ER diagram and how do you use it in schema design?
What they're really asking
This tests ability to translate business requirements into logical data models and understand the relationship between conceptual design and physical implementation. The interviewer wants to see if you can bridge business analysis and technical database design.
How you'll be scored
Describes ER diagrams superficially without connecting them to actual schema design decisions or business requirements.
Correctly explains ER diagram components but doesn't demonstrate how to use them effectively in the design process.
Shows how ER diagrams drive schema decisions, discusses relationship cardinalities and their implementation implications, and connects logical design to physical optimization.
How to structure your answer
- Define ER diagrams as visual representations of entities, attributes, and relationships.
- Explain how to identify entities and their attributes from business requirements.
- Discuss relationship types and cardinalities and their significance.
- Show how to translate the logical ER model into physical database schema.
- Address iterative refinement and normalization considerations.
Key points to hit
- Entities represent distinct business objects with attributes that describe their properties, while relationships show how entities connect to each other.
- Relationship cardinalities (one-to-one, one-to-many, many-to-many) directly determine table structure and foreign key placement in the physical schema.
- Use ER diagrams to validate business requirements by walking through scenarios and ensuring all necessary data and relationships are captured.
- Transform many-to-many relationships into junction tables and consider how relationship attributes become columns in the physical design.
Common mistakes
- Creating overly complex ER diagrams that try to capture every possible detail instead of focusing on core business entities and relationships.
- Not validating the ER diagram with stakeholders before implementation, leading to schema changes that could have been avoided.
Sample answer
An ER diagram is a visual model that shows entities as rectangles, attributes as ovals, and relationships as diamonds connecting entities. I start by identifying core business objects like Customer, Order, and Product from requirements, then determine their attributes and how they relate. For example, customers place orders (one-to-many) and orders contain products (many-to-many).
The cardinalities tell me exactly how to structure tables. One-to-many becomes a foreign key in the 'many' table, while many-to-many requires a junction table. I use the diagram to walk through business scenarios with stakeholders, ensuring we capture all necessary data relationships.
Once validated, I translate it directly to a physical schema, with entities becoming tables, attributes becoming columns, and relationships determining foreign keys and junction tables.
How to level up
- Include relationship attributes in your ER diagrams because they often become important columns in junction tables or need special handling.
- Use different notation styles (Chen, crow's foot, UML) appropriately for your audience, with crow's foot being most intuitive for developers.
- Consider using ER diagrams iteratively, starting with high-level conceptual models and refining them through logical and physical design phases.
Follow-up questions to expect
- How do you handle inheritance relationships in ER diagrams and translate them to relational schemas?
- What's your process when the ER diagram reveals conflicting business requirements?
- How do you use ER diagrams when designing APIs or microservice boundaries?
What is data redundancy and how does normalization address it?
What they're really asking
This tests data modeling fundamentals and schema design thinking. The interviewer wants to see if you understand how poor normalization creates data inconsistencies and maintenance problems in production systems.
How you'll be scored
Gives a vague definition without explaining anomalies or provides incorrect normalization examples.
Correctly defines redundancy and explains basic normalization forms with simple examples.
Explains redundancy with specific anomaly examples, demonstrates normalization process, and discusses when denormalization might be acceptable.
How to structure your answer
- Define data redundancy with a concrete example.
- Explain the three anomalies: insert, update, delete.
- Walk through normalization forms (1NF, 2NF, 3NF)
- Show before/after table examples.
- Mention when controlled redundancy might be beneficial.
Key points to hit
- Data redundancy means storing the same information multiple times, leading to inconsistency when updates happen in one place but not others.
- Insert anomalies occur when you cannot add data without having unrelated information, update anomalies happen when changing data requires multiple row updates, and delete anomalies mean losing important data when removing records.
- First Normal Form eliminates repeating groups, Second Normal Form removes partial dependencies, and Third Normal Form eliminates transitive dependencies.
- Normalization trades storage efficiency and data integrity for query complexity and potential performance costs.
Common mistakes
- Confusing normalization levels or providing examples that don't actually demonstrate the normal form being discussed.
- Not explaining the real business impact of anomalies, like why duplicate customer addresses cause shipping errors.
Sample answer
Data redundancy means storing the same piece of information in multiple places. For example, if we store customer name and address in both an Orders table and a Customers table, we have redundancy.
This creates three types of anomalies: insert anomalies where you can't add an order without customer data, update anomalies where changing a customer's address requires updating multiple tables, and delete anomalies where removing the last order for a customer loses their information entirely. Normalization addresses this by organizing data into separate tables with relationships.
We'd move customer information to its own table and reference it with foreign keys, eliminating the redundancy while maintaining data integrity.
How to level up
- Discuss functional dependencies using notation like 'CustomerID โ CustomerName, CustomerAddress' to show what determines what.
- Mention that some redundancy is acceptable in data warehouses for query performance, but should be controlled and documented.
Follow-up questions to expect
- Can you walk through normalizing this specific table structure I'm showing you?
- When might you intentionally denormalize a database design?
- How would you handle normalization in a high-traffic OLTP system versus an analytics data warehouse?
What is a slowly changing dimension (SCD)? Describe Type 1, 2, and 3.
What they're really asking
This tests data warehousing knowledge and understanding of how dimensional models handle changing data over time. The interviewer wants to see if you can design systems that preserve historical accuracy while supporting current reporting needs.
How you'll be scored
Cannot explain what SCD means or confuses the different types with incorrect examples.
Correctly describes all three SCD types with basic examples but misses implementation details.
Explains each SCD type with concrete business scenarios, discusses implementation approaches, and mentions performance and storage tradeoffs.
How to structure your answer
- Define slowly changing dimensions in the context of data warehousing.
- Explain Type 1: overwrite with business example.
- Explain Type 2: historical tracking with versioning approach.
- Explain Type 3: limited history with additional columns.
- Compare when to use each type based on business requirements.
Key points to hit
- Slowly changing dimensions handle attributes in dimension tables that change over time, like customer addresses or product categories, without losing analytical accuracy.
- Type 1 overwrites old values with new ones, losing history but keeping the table simple and current.
- Type 2 creates new records for each change, preserving full history using techniques like effective dates, version numbers, or current flags.
- Type 3 stores both old and new values in separate columns, providing limited history for specific attributes that need comparison.
Common mistakes
- Mixing up which type preserves history and which doesn't, or giving examples that don't match the SCD type being described.
- Not considering the business impact of choosing the wrong SCD type, like losing audit trails or creating excessive storage growth.
Sample answer
A slowly changing dimension handles when attributes in dimension tables change over time. Type 1 simply overwrites the old value with the new one, like updating a customer's phone number where we only care about the current contact info.
Type 2 preserves history by creating a new record for each change, so if a customer moves, we'd insert a new row with the new address and mark the old one as inactive using effective dates or a current flag.
Type 3 stores both values in the same record using separate columns, like having both 'Previous_Territory' and 'Current_Territory' when we need to compare where a salesperson worked before versus now. The choice depends on whether you need full history, current data only, or limited historical comparison.
How to level up
- Discuss hybrid approaches like Type 6 (combining Type 1, 2, and 3) for complex business requirements.
- Mention implementation considerations like using surrogate keys for Type 2 to maintain referential integrity when dimension records change.
Follow-up questions to expect
- How would you implement Type 2 SCD using SQL to handle a customer address change?
- What are the storage and performance implications of each SCD type?
- How do you handle SCD processing in an ETL pipeline with daily batch updates?
How do you design SQL tables for a star schema data model?
What they're really asking
This tests data warehousing architecture knowledge and dimensional modeling skills. The interviewer wants to see if you understand how to structure analytical databases for efficient querying and business intelligence reporting.
How you'll be scored
Cannot distinguish between fact and dimension tables or provides incorrect examples of star schema structure.
Correctly identifies fact table in center with dimension tables around it and provides basic examples.
Explains fact and dimension table design principles, discusses grain definition, surrogate keys, and mentions performance benefits of star schema for analytics.
How to structure your answer
- Define star schema as central fact table surrounded by dimension tables.
- Explain fact table design: measures, foreign keys, grain definition.
- Explain dimension table design: descriptive attributes, surrogate keys.
- Provide concrete business example with specific tables.
- Discuss benefits for query performance and business understanding.
Key points to hit
- Star schema consists of one central fact table containing measurable events or transactions, surrounded by dimension tables that provide context and descriptive attributes.
- Fact tables store numeric measures (like sales amount, quantity) and foreign keys to dimensions, with each row representing one occurrence at a specific grain level.
- Dimension tables contain descriptive attributes (like customer name, product category) and typically use surrogate keys to handle slowly changing dimensions and improve performance.
- The star shape enables simple JOIN operations and makes the model intuitive for business users writing reports and analytics queries.
Common mistakes
- Putting descriptive attributes in the fact table or measures in dimension tables, which violates star schema principles.
- Not defining the grain clearly, leading to confusion about what each fact table row represents and causing incorrect aggregations.
Sample answer
A star schema puts a fact table in the center containing the business events you want to measure, surrounded by dimension tables that describe those events. For a sales example, the fact table would have measures like sales_amount and quantity, plus foreign keys to dimension tables.
The dimension tables would be Customer with attributes like name and region, Product with category and description, and Date with year, month, quarter. Each fact table row represents one sale at the transaction line item level.
This design makes queries simple because you JOIN the fact table to whatever dimensions you need, and it's intuitive for business users who think about analyzing sales by customer, product, or time period.
How to level up
- Discuss the importance of grain definition upfront, ensuring all measures are at the same level of detail to avoid aggregation errors.
- Mention that surrogate keys in dimension tables provide stability when business keys change and improve JOIN performance compared to natural keys.
Follow-up questions to expect
- How would you handle a many-to-many relationship in a star schema, like products with multiple categories?
- What's the difference between a star schema and a snowflake schema, and when would you choose each?
- How do you design fact tables when you have measures at different grain levels, like daily sales totals and individual transactions?
What is a tablespace and how does it relate to database storage?
What they're really asking
This tests database administration knowledge and understanding of storage management. The interviewer wants to see if you understand how logical database structures map to physical storage and can manage space allocation effectively.
How you'll be scored
Cannot explain what a tablespace is or confuses it with tables, schemas, or other database objects.
Correctly defines tablespace as logical storage unit and explains basic relationship to physical files.
Explains tablespace as logical storage abstraction, discusses multiple tablespace strategies, mentions performance and management benefits, and covers backup/recovery implications.
How to structure your answer
- Define tablespace as logical storage container that maps to physical files.
- Explain how tables, indexes, and other objects are assigned to tablespaces.
- Describe common tablespace strategies: data vs indexes, temporary space.
- Discuss administration benefits: space management, backup, performance.
- Mention database-specific implementation differences.
Key points to hit
- A tablespace is a logical storage unit that groups database objects and maps them to one or more physical data files on disk, providing an abstraction layer between logical database structure and physical storage.
- Database objects like tables and indexes are assigned to specific tablespaces, allowing administrators to control where data is physically stored and how space is allocated.
- Common strategies include separating data and indexes into different tablespaces for performance, creating dedicated temporary tablespaces for sorting operations, and isolating high-activity tables.
- Tablespaces enable granular control over backup and recovery, space allocation, and I/O distribution across storage devices.
Common mistakes
- Confusing tablespaces with schemas or databases, or thinking they're the same as physical files rather than logical containers.
- Not understanding that tablespace design affects backup strategies and recovery point objectives.
Sample answer
A tablespace is a logical storage container that acts as a bridge between your database objects and the physical files on disk. When you create a table or index, it gets assigned to a tablespace, which then determines where that data physically lives.
For example, you might have a 'DATA_TS' tablespace for your tables mapped to fast SSD storage, and an 'INDEX_TS' tablespace for indexes on different drives to spread I/O. There's usually also a temporary tablespace for sort operations.
This gives database administrators control over storage allocation, makes backups more granular since you can back up individual tablespaces, and helps with performance tuning by putting frequently accessed data on faster storage devices.
How to level up
- Discuss how tablespace placement affects parallel query performance and I/O distribution in enterprise environments.
- Mention that some databases support online tablespace operations, allowing you to move objects between tablespaces without downtime.
Follow-up questions to expect
- How would you design a tablespace strategy for a high-transaction OLTP system?
- What happens to database performance if a tablespace runs out of space?
- How do tablespaces factor into your backup and recovery strategy?
Performance & Optimization Questions (15)
How do you optimize a slow-running SQL query?
What they're really asking
This tests systematic troubleshooting approach and performance tuning knowledge. The interviewer wants to see if you can methodically identify bottlenecks and apply appropriate optimization techniques rather than guessing randomly.
How you'll be scored
Suggests only basic solutions like adding indexes without systematic analysis or understanding of query execution.
Mentions examining execution plans and a few optimization techniques but lacks structured approach.
Demonstrates systematic methodology using execution plans, identifies common bottlenecks, discusses multiple optimization strategies, and considers monitoring and measurement.
How to structure your answer
- Start with measuring and establishing baseline performance.
- Analyze the query execution plan to identify bottlenecks.
- Apply targeted optimizations based on execution plan findings.
- Test and measure improvements after each change.
- Consider broader system factors like statistics and hardware.
Key points to hit
- Always start by examining the query execution plan to understand how the database is processing your query and identify the most expensive operations.
- Look for table scans that could benefit from indexes, inefficient JOIN orders, or missing statistics that cause poor cardinality estimates.
- Common optimizations include adding appropriate indexes, rewriting queries to use better JOIN conditions, and eliminating unnecessary subqueries or functions in WHERE clauses.
- Measure performance before and after changes, since some optimizations help certain queries but hurt others, and always update table statistics after significant data changes.
Common mistakes
- Adding indexes without understanding query patterns, which can slow down INSERT/UPDATE operations and waste storage space.
- Making multiple changes at once without measuring individual impact, making it impossible to know which optimization actually helped.
Sample answer
I always start by looking at the execution plan to see where the database is spending time. I use EXPLAIN PLAN or similar tools to find expensive operations like full table scans or nested loop joins on large tables.
If I see table scans, I check whether appropriate indexes exist for the WHERE and JOIN conditions. For expensive joins, I might rewrite the query to change the join order or add hints if needed.
I also look for functions in WHERE clauses that prevent index usage, like WHERE UPPER(name) = 'SMITH' instead of a case-insensitive index. After each change, I measure the performance impact and update table statistics to make sure the optimizer has current information for making good decisions.
How to level up
- Use database-specific tools like query stores or performance monitors to identify the most impactful queries to optimize first.
- Consider partitioning strategies for very large tables where indexes alone aren't sufficient to improve performance.
Follow-up questions to expect
- Walk me through optimizing this specific slow query I'm showing you.
- How do you balance query performance with the overhead of maintaining additional indexes?
- What tools and metrics do you use to monitor query performance in production?
What is an index? What are the different types (clustered, non-clustered, composite, covering)?
What they're really asking
This tests your foundational understanding of database indexing concepts and whether you can differentiate between index types based on their storage structure and use cases. The interviewer wants to see if you understand how indexes physically organize data and when to choose each type.
How you'll be scored
Vague explanation like 'indexes make queries faster' without explaining the different types or their specific characteristics.
Correctly defines indexes and lists the types but doesn't explain the key differences or when to use each.
Clear definition with accurate explanations of each index type, including storage differences and practical use cases for each.
How to structure your answer
- Define what an index is conceptually.
- Explain clustered indexes and their unique properties.
- Describe non-clustered indexes and how they differ.
- Define composite and covering indexes with examples.
- Mention when you'd choose each type.
Key points to hit
- An index is a data structure that creates shortcuts to table rows, similar to a book's index pointing to page numbers.
- Clustered indexes physically reorder table data and determine row storage order (one per table)
- Non-clustered indexes create separate structures that point back to table rows (multiple allowed per table)
- Composite indexes cover multiple columns while covering indexes include all needed columns to avoid key lookups.
Common mistakes
- Confusing clustered with primary key (a primary key creates a clustered index by default, but they're different concepts)
- Not understanding that clustered indexes physically reorder data while non-clustered indexes are separate pointer structures.
Sample answer
An index is a data structure that creates fast access paths to table data, like a book's index pointing to specific pages. A clustered index physically reorders and stores the table data based on the index key, so there can only be one per table.
Non-clustered indexes create separate structures with pointers back to the actual rows, allowing multiple per table. A composite index spans multiple columns like (lastname, firstname) for queries filtering on both. A covering index includes all columns needed by a query in the index itself, eliminating the need to access the base table.
How to level up
- Understand that clustered index key becomes part of every non-clustered index, affecting their size.
- Know that covering indexes can dramatically improve performance but increase storage and maintenance overhead.
Follow-up questions to expect
- When would you choose a composite index over multiple single-column indexes?
- How does the clustered index key affect the size of non-clustered indexes?
- What happens to query performance when you have too many indexes on a table?
How does indexing improve query performance? What are the trade-offs?
What they're really asking
This tests whether you understand the performance mechanics of indexing and can evaluate trade-offs rather than just knowing 'indexes are good.' The interviewer wants to see if you think about the full lifecycle impact of indexes on database operations.
How you'll be scored
Only mentions that indexes speed up queries without explaining how or acknowledging any downsides.
Explains basic performance improvement and mentions some trade-offs like slower writes.
Detailed explanation of how indexes avoid full table scans, plus comprehensive discussion of storage, maintenance, and write performance trade-offs.
How to structure your answer
- Explain how indexes improve read performance mechanically.
- Describe the difference between index seeks and table scans.
- Detail the storage overhead trade-off.
- Explain write performance impact.
- Discuss maintenance overhead considerations.
Key points to hit
- Indexes convert expensive full table scans into fast index seeks by providing direct paths to matching rows.
- Storage overhead increases because indexes duplicate and reorganize data in additional structures.
- Write operations (INSERT, UPDATE, DELETE) become slower because indexes must be maintained alongside table changes.
- Too many indexes can overwhelm the query optimizer and consume excessive memory for index maintenance.
Common mistakes
- Thinking indexes always improve performance (they can actually hurt queries that don't benefit from them)
- Not considering that UPDATE and DELETE operations can become significantly slower with many indexes.
Sample answer
Indexes improve performance by converting full table scans into targeted index seeks. Instead of reading every row to find matches, the database can jump directly to relevant data using the index structure. However, there are significant trade-offs. Storage requirements increase because indexes duplicate data in sorted structures.
Write performance suffers because every INSERT, UPDATE, or DELETE must maintain all relevant indexes, not just modify the base table. I've seen cases where over-indexing made batch operations 10x slower due to index maintenance overhead.
How to level up
- Consider index maintenance during bulk operations and know when to temporarily drop indexes for large data loads.
- Understand that unused indexes waste space and slow writes without providing any benefit.
Follow-up questions to expect
- How would you identify indexes that aren't being used and are just slowing down writes?
- What's your approach for indexing a table that has heavy write traffic?
- How do you balance read performance needs with write performance constraints?
What is a query execution plan and how do you read it?
What they're really asking
This tests whether you can analyze query performance systematically rather than guessing why queries are slow. The interviewer wants to see if you use execution plans as diagnostic tools and understand key performance indicators.
How you'll be scored
Vague description of execution plans without knowing how to interpret key elements or performance indicators.
Basic understanding of execution plans and can identify major operations but misses cost analysis details.
Demonstrates ability to read execution plans systematically, identify bottlenecks, and translate findings into optimization actions.
How to structure your answer
- Define what an execution plan shows.
- Explain how to identify expensive operations.
- Describe key operators to look for.
- Explain how to spot performance bottlenecks.
- Mention tools for viewing execution plans.
Key points to hit
- Execution plans show the step-by-step operations the database engine uses to execute a query, including cost estimates.
- Look for high-cost operations like table scans, nested loops on large datasets, and sort operations.
- Key operators include Index Seek (good), Index Scan (moderate), Table Scan (usually bad), and Hash Match (expensive joins)
- Reading plans flows right to left and top to bottom, with the root node showing overall query cost.
Common mistakes
- Focusing only on individual operator costs without considering row counts and data flow between operations.
- Not understanding that estimated plans may differ significantly from actual execution when statistics are outdated.
Sample answer
An execution plan is the database engine's roadmap showing exactly how it will execute a query, including estimated costs and row counts for each step. I read them right to left, top to bottom, looking for expensive operations.
Table scans and index scans on large tables are red flags, as are nested loop joins with high row counts. I pay attention to the thickness of arrows between operations because that shows data volume.
Recently I found a query doing a sort operation on 2 million rows that was killing performance, which led me to add an index to eliminate the sort.
How to level up
- Compare estimated vs actual execution plans to identify parameter sniffing or outdated statistics issues.
- Look for implicit conversions in execution plans, which often indicate data type mismatches hurting performance.
Follow-up questions to expect
- What would you do if you see a large discrepancy between estimated and actual row counts in an execution plan?
- How do you identify when parameter sniffing is causing performance problems?
- What are some common execution plan patterns that indicate indexing opportunities?
What is sargability and how do non-sargable conditions hurt performance?
What they're really asking
This tests your deep understanding of query optimization principles and whether you can write queries that leverage indexes effectively. The interviewer wants to see if you understand why certain WHERE clause patterns prevent index usage.
How you'll be scored
Cannot define sargability or gives incorrect examples of what makes conditions non-sargable.
Understands basic concept and can identify obvious non-sargable conditions like functions on columns.
Comprehensive understanding with multiple examples and can explain the underlying reasons why these patterns hurt performance.
How to structure your answer
- Define sargability clearly.
- Explain why non-sargable conditions hurt performance.
- Give specific examples of non-sargable patterns.
- Show how to rewrite non-sargable conditions.
- Mention impact on query execution plans.
Key points to hit
- Sargable means Search ARGument ABLE - conditions that can use indexes efficiently for fast data retrieval.
- Non-sargable conditions force full table scans because the database cannot use index structures to eliminate rows.
- Common non-sargable patterns include functions on columns (UPPER(name) = 'SMITH'), leading wildcards (LIKE '%smith'), and mathematical operations on indexed columns.
- Rewrite non-sargable conditions by moving operations to the right side of comparisons or restructuring logic.
Common mistakes
- Writing WHERE YEAR(date_column) = 2023 instead of date_column >= '2023-01-01' AND date_column < '2024-01-01'
- Using LIKE '%searchterm%' when LIKE 'searchterm%' would work for the business requirement.
Sample answer
Sargability means Search ARGument Able - it refers to WHERE conditions that can effectively use indexes. Non-sargable conditions force full table scans because they prevent the database from using index structures. For example, WHERE UPPER(lastname) = 'SMITH' is non-sargable because applying a function to the column means the index can't be used.
Instead, I'd write WHERE lastname = 'SMITH' if case doesn't matter, or create a computed index on UPPER(lastname). Similarly, WHERE salary * 1.1 > 50000 should be rewritten as WHERE salary > 50000/1.1 to make it sargable.
How to level up
- Use computed indexes or indexed computed columns for cases where you must apply functions to columns in WHERE clauses.
- Understand that some database systems can handle certain function patterns through functional indexes or expression indexes.
Follow-up questions to expect
- How would you handle a requirement to search for partial matches in the middle of text fields?
- What's your approach when you need to query on calculated values that can't easily be made sargable?
- How do you identify non-sargable conditions in existing queries?
What are the considerations for indexing very large tables?
What they're really asking
This tests whether you understand the unique challenges of indexing at scale and can make strategic trade-offs between performance, storage, and maintenance overhead. The interviewer wants to see enterprise-level thinking about index management.
How you'll be scored
Treats large table indexing the same as small tables without considering scale-specific issues.
Mentions some considerations like storage space and maintenance time but lacks comprehensive strategy.
Demonstrates understanding of partitioning, selective indexing, maintenance windows, and performance monitoring strategies for large-scale systems.
How to structure your answer
- Identify what makes large table indexing different.
- Discuss storage and memory implications.
- Explain index maintenance challenges.
- Cover partitioning strategies.
- Address monitoring and maintenance approaches.
Key points to hit
- Large tables require careful index selection because storage overhead and maintenance costs multiply significantly with table size.
- Index maintenance operations (rebuilds, reorganizations) take much longer and may require dedicated maintenance windows.
- Partitioning strategies become critical for both table and index management, allowing maintenance on subsets of data.
- Memory pressure increases as index pages compete with data pages and query caches for available RAM.
Common mistakes
- Creating too many indexes without measuring their actual usage, leading to massive maintenance overhead.
- Not considering partitioning alignment between tables and indexes, which can cause inefficient query plans.
Sample answer
With very large tables, indexing becomes a strategic decision because every index multiplies storage and maintenance costs. I focus on the most critical queries first and measure index usage religiously. Storage overhead is huge - a 1TB table might need 200-300GB just for indexes.
Maintenance becomes challenging because index rebuilds on billion-row tables can take hours. I typically implement partitioning to make maintenance manageable, allowing index operations on monthly or yearly partitions instead of the entire table. Memory pressure is also a factor since large indexes compete with data for buffer pool space.
How to level up
- Implement index usage monitoring to identify and drop unused indexes that are just consuming resources at scale.
- Consider columnstore indexes for very large analytical workloads as they provide better compression and performance than traditional B-tree indexes.
Follow-up questions to expect
- How do you handle index maintenance on 24/7 systems that can't afford downtime?
- What's your approach for monitoring index effectiveness on tables with billions of rows?
- How do you decide between horizontal partitioning and better indexing for query performance?
How do you perform bulk inserts efficiently?
What they're really asking
This tests bulk data loading optimization and understanding of database internals. The interviewer wants to see if you know techniques beyond basic INSERT statements and understand the performance implications of different approaches.
How you'll be scored
Only mentions basic INSERT statements or batch inserts without considering transaction overhead or database-specific optimizations.
Describes batch inserts with transaction batching but misses database-specific tools or performance considerations.
Covers multiple techniques including database-specific bulk loaders, discusses transaction batching, indexing strategies, and validates data integrity.
How to structure your answer
- Start with the performance problem of individual INSERTs.
- Present batch INSERT techniques and transaction management.
- Discuss database-specific bulk loading tools.
- Address indexing and constraint considerations.
- Mention data validation and error handling.
Key points to hit
- Batch multiple rows in single INSERT statements to reduce network round trips and transaction overhead.
- Use database-specific bulk loading tools like BULK INSERT, LOAD DATA, or COPY for maximum performance.
- Temporarily disable or drop indexes during large loads, then rebuild them afterward.
- Control transaction size to balance performance with rollback risk and lock duration.
Common mistakes
- Using individual INSERT statements in loops instead of batching operations.
- Forgetting to disable foreign key checks or indexes during bulk operations, causing massive slowdowns.
Sample answer
For bulk inserts, I start with batching multiple rows into single INSERT statements, typically 1000-5000 rows per statement depending on row size. For really large datasets, I use database-specific tools like PostgreSQL's COPY or SQL Server's BULK INSERT which bypass much of the normal SQL processing overhead.
Before the bulk load, I'll drop non-clustered indexes and foreign key constraints, then recreate them afterward since building indexes incrementally is much slower than building them once on the full dataset. I also manage transaction size carefully, committing every 10,000-50,000 rows to avoid long-running transactions that could block other operations.
How to level up
- Consider using UNLOGGED tables in PostgreSQL or turning off WAL logging temporarily to skip write-ahead logging overhead.
- Use parallel bulk loading techniques when the database supports it, splitting data across multiple connections.
- Pre-sort data by clustered index order to minimize page splits and improve insert performance.
Follow-up questions to expect
- How would you handle duplicate key errors during a bulk insert operation?
- What's your approach for validating data quality during bulk loads?
- How do you monitor and troubleshoot slow bulk insert operations?
What are the trade-offs of indexing vs denormalization?
What they're really asking
This tests architectural decision-making and understanding of performance trade-offs. The interviewer wants to see if you can weigh the benefits and costs of different optimization strategies based on specific use cases.
How you'll be scored
Claims one approach is always better without considering use cases or mentions only benefits without understanding the costs.
Lists pros and cons of each approach but doesn't connect them to specific scenarios or query patterns.
Analyzes both approaches with specific use cases, discusses maintenance overhead, and explains when to choose each strategy based on read vs write patterns.
How to structure your answer
- Define what indexing and denormalization optimize for.
- Compare performance characteristics of each approach.
- Discuss maintenance overhead and storage costs.
- Present decision criteria based on workload patterns.
- Give specific examples of when to use each strategy.
Key points to hit
- Indexes speed up reads without changing data structure but slow down writes due to index maintenance overhead.
- Denormalization reduces JOIN complexity and improves read performance but creates data redundancy and update anomalies.
- Choose indexing for normalized schemas with complex queries, denormalization for read-heavy workloads with simple access patterns.
- Consider hybrid approaches where you selectively denormalize hot paths while keeping most data normalized.
Common mistakes
- Thinking denormalization always improves performance without considering the overhead of maintaining duplicate data.
- Over-indexing tables without considering the write performance penalty and storage overhead.
Sample answer
Indexing and denormalization solve different performance problems. Indexes maintain normalized data structure while speeding up specific queries, but they add overhead to INSERT, UPDATE, and DELETE operations since the database has to maintain multiple data structures.
Denormalization reduces JOIN operations by duplicating data, which can dramatically speed up reads, but you pay the cost in storage space and complexity of keeping duplicate data synchronized. I choose indexing when I have a normalized schema with varied query patterns since indexes can support multiple access paths.
I use denormalization for read-heavy systems with predictable access patterns, like reporting databases or when I need to eliminate expensive JOINs that are killing performance.
How to level up
- Use covering indexes as a middle ground that provides denormalization benefits without duplicate base table data.
- Consider partial denormalization where you only duplicate frequently accessed columns rather than entire tables.
- Monitor index usage statistics to identify unused indexes that are hurting write performance without providing read benefits.
Follow-up questions to expect
- How would you decide which columns to include in a covering index?
- What strategies do you use to keep denormalized data consistent?
- How do you measure whether an optimization is actually helping performance?
What is database partitioning and how does it improve performance?
What they're really asking
This tests basic understanding of horizontal scaling concepts and performance optimization strategies. The interviewer wants to see if you know fundamental partitioning concepts and can explain performance benefits clearly.
How you'll be scored
Confuses partitioning with other concepts or gives vague answers about 'making things faster' without explaining the mechanism.
Correctly defines partitioning and mentions performance benefits but lacks specific examples or partitioning strategies.
Explains partitioning clearly with specific partition types, discusses partition pruning and parallel processing benefits, and gives relevant use cases.
How to structure your answer
- Define database partitioning as dividing tables into smaller pieces.
- Explain how partition pruning improves query performance.
- Describe different partitioning strategies and when to use them.
- Discuss parallel processing and maintenance benefits.
- Give specific examples of good partitioning candidates.
Key points to hit
- Partitioning divides large tables into smaller, more manageable pieces based on partition keys like date ranges or hash values.
- Query performance improves through partition pruning where the database only scans relevant partitions instead of the entire table.
- Common strategies include range partitioning for time-series data and hash partitioning for even data distribution.
- Maintenance operations like backups and index rebuilds can run on individual partitions rather than the entire table.
Common mistakes
- Confusing partitioning with sharding or thinking they're the same concept.
- Choosing poor partition keys that result in uneven data distribution or don't align with common query patterns.
Sample answer
Database partitioning splits large tables into smaller physical pieces while keeping them logically as one table. The main performance benefit comes from partition pruning, where queries only scan the partitions they need instead of the entire table.
For example, if I partition a sales table by month and query for last month's data, the database only scans that one partition instead of scanning years of historical data. I typically use range partitioning for time-series data like logs or transactions, and hash partitioning when I need even data distribution.
Partitioning also helps with maintenance since I can backup, rebuild indexes, or archive individual partitions without affecting the whole table.
How to level up
- Choose partition keys that align with your most common WHERE clause filters to maximize partition pruning benefits.
- Consider partition-wise JOINs where both tables are partitioned on the same key to enable parallel processing.
- Plan for partition maintenance operations like automatically dropping old partitions or splitting large ones.
Follow-up questions to expect
- How would you handle queries that need data from multiple partitions?
- What happens to foreign key constraints across partitions?
- How do you monitor partition performance and determine if partitioning is helping?
How do you optimize JOIN operations on large tables?
What they're really asking
This tests JOIN performance optimization knowledge and understanding of query execution plans. The interviewer wants to see if you can identify JOIN bottlenecks and apply specific optimization techniques beyond basic indexing.
How you'll be scored
Only mentions adding indexes without understanding JOIN algorithms or considering query execution plans and data distribution.
Discusses indexing strategies and mentions JOIN order but lacks depth on execution algorithms or advanced techniques.
Covers multiple optimization strategies including appropriate indexes, JOIN algorithms, statistics, and query rewriting techniques with awareness of when each applies.
How to structure your answer
- Identify common JOIN performance bottlenecks on large tables.
- Discuss indexing strategies specific to JOIN optimization.
- Explain JOIN algorithm selection and how to influence it.
- Cover query rewriting techniques for better performance.
- Address data distribution and statistics considerations.
Key points to hit
- Create indexes on JOIN columns with foreign key columns indexed and consider covering indexes to avoid key lookups.
- Understand that nested loop JOINs work well for small result sets while hash JOINs perform better for large data sets.
- JOIN order matters significantly, start with the most selective table to reduce intermediate result sets.
- Keep table statistics updated so the query optimizer can make good decisions about JOIN algorithms and order.
Common mistakes
- Assuming the database will automatically optimize JOIN order without considering the impact of outdated statistics.
- Creating indexes only on one side of the JOIN relationship instead of ensuring both tables have appropriate indexes.
Sample answer
When optimizing JOINs on large tables, I start by ensuring both sides of the JOIN have appropriate indexes, typically on foreign key columns, and consider covering indexes if the query selects many columns.
I analyze the execution plan to see which JOIN algorithm is being used, since nested loop JOINs can be slow with large datasets while hash JOINs handle large data better. I pay attention to JOIN order and try to start with the most selective table to minimize intermediate result sets.
For really problematic JOINs, I might rewrite the query using EXISTS instead of INNER JOIN or break complex multi-table JOINs into smaller steps with temporary results.
How to level up
- Use JOIN hints sparingly but consider them when you know the data distribution better than the optimizer.
- Consider denormalizing frequently joined data into a single table if the JOIN cost consistently outweighs the benefits of normalization.
- Analyze actual vs estimated row counts in execution plans to identify statistics problems that hurt JOIN optimization.
Follow-up questions to expect
- How would you handle a situation where a JOIN is returning more rows than expected?
- What's your approach when the query optimizer chooses a suboptimal JOIN order?
- How do you decide between rewriting a complex JOIN vs optimizing the existing query?
What are materialized views and when do they help performance?
What they're really asking
This tests understanding of pre-computed result caching and when it's appropriate for performance optimization. The interviewer wants to see if you know the trade-offs between storage, freshness, and query speed.
How you'll be scored
Confuses materialized views with regular views or gives vague answers about caching without understanding refresh strategies.
Correctly defines materialized views and mentions performance benefits but doesn't discuss refresh overhead or appropriate use cases.
Explains materialized views clearly, discusses refresh strategies and their trade-offs, and identifies specific scenarios where they provide the most benefit.
How to structure your answer
- Define materialized views as pre-computed and stored query results.
- Explain how they improve read performance by avoiding expensive computations.
- Describe refresh strategies and their implications.
- Identify ideal use cases for materialized views.
- Discuss trade-offs in storage and data freshness.
Key points to hit
- Materialized views store the actual result set of a query on disk, eliminating the need to recompute expensive operations like aggregations and JOINs.
- They're most beneficial for complex analytical queries with aggregations, multiple JOINs, or expensive calculations that run frequently.
- Refresh strategies include on-demand, scheduled, and incremental updates, each with different trade-offs between performance and data freshness.
- Consider them when query computation cost is high but underlying data changes infrequently relative to read frequency.
Common mistakes
- Using materialized views for frequently changing data without considering the refresh overhead and potential staleness.
- Creating materialized views for simple queries that would perform fine with proper indexing.
Sample answer
Materialized views are pre-computed query results stored physically on disk, unlike regular views which are just stored SQL. They help performance by eliminating expensive computations on every query, especially for complex analytics with aggregations across multiple large tables.
For example, instead of calculating monthly sales totals by joining orders, customers, and products every time, I can create a materialized view that stores these pre-calculated results. The trade-off is keeping the data fresh, either through scheduled refreshes or incremental updates when base data changes.
They work best for reporting scenarios where you have expensive analytical queries running frequently but the underlying data doesn't change constantly.
How to level up
- Use incremental materialized view refreshes when possible to update only changed data rather than rebuilding the entire view.
- Consider indexed materialized views that can automatically maintain themselves but have higher overhead on base table modifications.
- Design materialized views to serve multiple similar queries rather than creating one per specific query.
Follow-up questions to expect
- How would you handle a materialized view that's taking too long to refresh?
- What's your strategy for determining optimal refresh frequency?
- How do you ensure applications can handle potentially stale data from materialized views?
What causes double counting in joins and how can it be prevented?
What they're really asking
This tests your understanding of join semantics and data multiplication issues. The interviewer wants to see if you can identify when joins create duplicate data and implement solutions to maintain data integrity.
How you'll be scored
Describes double counting vaguely without showing how to prevent it or demonstrating understanding of why it happens.
Correctly explains double counting occurs with one-to-many joins and mentions DISTINCT as a solution.
Explains the root cause in join cardinality, demonstrates multiple prevention strategies including proper aggregation and query restructuring, and discusses performance implications.
How to structure your answer
- Define what double counting means in join context.
- Explain the root cause (one-to-many or many-to-many relationships)
- Provide a concrete example showing the problem.
- Present multiple solutions with their trade-offs.
- Discuss prevention strategies during query design.
Key points to hit
- Double counting occurs when joining tables with one-to-many or many-to-many relationships causes rows to multiply, inflating aggregated values.
- Prevention methods include using DISTINCT, proper GROUP BY clauses, subqueries to pre-aggregate, or window functions instead of joins.
- The best approach is often restructuring the query to avoid the problematic join entirely rather than fixing it afterward.
- Always verify join cardinality before writing aggregation queries to prevent data multiplication.
Common mistakes
- Using DISTINCT as a blanket solution without understanding why double counting occurred, which can mask other query problems.
- Not recognizing that COUNT(*) with joins will inflate results even when other aggregations look correct.
Sample answer
Double counting happens when you join a parent table to a child table with multiple related rows, causing the parent data to appear multiple times in your result set. For example, if I join customers to orders and then try to SUM(customer.credit_limit), each customer's credit limit gets counted once per order they have.
To prevent this, I can use subqueries to pre-aggregate the child data before joining, or use window functions instead of GROUP BY. The key is recognizing one-to-many relationships during query planning and choosing the right approach upfront rather than trying to fix it with DISTINCT afterward.
How to level up
- Use EXISTS instead of JOIN when you only need to check for related records without retrieving child table data.
- Consider materialized views or summary tables for frequently queried aggregations that involve complex joins.
- Analyze execution plans to understand how join algorithms affect performance when avoiding double counting.
Follow-up questions to expect
- How would you rewrite this specific query to avoid double counting while maintaining the same result set?
- What indexing strategy would you use to optimize the subquery approach?
- When might you accept double counting and handle it in application logic instead?
How do you handle performance tuning in production SQL databases?
What they're really asking
This tests your practical experience with database performance issues in live systems. The interviewer wants to see if you have systematic approaches to diagnosis and optimization under production constraints.
How you'll be scored
Suggests basic optimizations like adding indexes without demonstrating a methodical approach to identifying bottlenecks.
Shows understanding of query analysis tools and common optimization techniques with some process awareness.
Demonstrates a systematic diagnostic process, mentions monitoring tools, discusses change management in production, and shows awareness of business impact.
How to structure your answer
- Outline your diagnostic process for identifying performance issues.
- Describe tools and techniques for analysis.
- Explain your approach to testing and implementing changes safely.
- Discuss monitoring and validation of improvements.
- Address coordination with stakeholders during optimization.
Key points to hit
- Start with monitoring tools to identify slow queries, resource bottlenecks, and patterns rather than guessing at problems.
- Use query execution plans to understand why queries are slow before attempting optimizations.
- Test changes in staging environments that mirror production data volumes and hardware specifications.
- Implement changes incrementally with rollback plans, especially for schema modifications or major query rewrites.
Common mistakes
- Making changes directly in production without proper testing, which can cause outages or data corruption.
- Focusing only on individual query optimization without considering overall system resource allocation and concurrent workload.
Sample answer
I start by analyzing slow query logs and using tools like EXPLAIN ANALYZE to identify bottlenecks and understand execution plans. At my last job, we had a reporting query taking 3 minutes during business hours. I found it was doing sequential scans on a 50 million row table.
Before making changes, I replicated the issue in staging with production-sized data, then tested a composite index solution. I coordinated with the ops team to implement the index during low-traffic hours and monitored query performance for 24 hours to confirm the 90% improvement held under normal load.
How to level up
- Set up automated monitoring for query performance regression to catch issues before users complain.
- Document your optimization decisions and results to build institutional knowledge for future performance work.
- Consider query hints and plan guides as temporary solutions while working on longer-term optimizations.
Follow-up questions to expect
- How do you prioritize which performance issues to tackle first when you have multiple slow queries?
- What's your approach when application changes are needed to fix performance issues?
- How do you handle performance tuning when you can't modify the schema due to business constraints?
What is the difference between vertical and horizontal scaling in databases?
What they're really asking
This tests your understanding of database architecture scaling strategies and when each approach is appropriate. The interviewer wants to see if you can evaluate scaling options based on specific performance bottlenecks and business requirements.
How you'll be scored
Provides basic definitions of vertical and horizontal scaling without demonstrating understanding of when to use each approach.
Correctly explains both scaling types and mentions some trade-offs like cost and complexity.
Explains scaling strategies with specific use cases, discusses architectural implications, addresses consistency and performance trade-offs, and shows awareness of hybrid approaches.
How to structure your answer
- Define vertical scaling and its characteristics.
- Define horizontal scaling and its characteristics.
- Compare the trade-offs and limitations of each approach.
- Provide specific scenarios where each is most appropriate.
- Discuss hybrid strategies and practical considerations.
Key points to hit
- Vertical scaling increases single server capacity (CPU, RAM, storage) while horizontal scaling distributes load across multiple servers.
- Vertical scaling is simpler to implement but has physical limits and single points of failure, while horizontal scaling offers better fault tolerance but adds complexity.
- Horizontal scaling requires careful consideration of data partitioning strategies and may introduce consistency challenges.
- The choice depends on workload characteristics, budget constraints, and acceptable complexity levels.
Common mistakes
- Assuming horizontal scaling is always better without considering the added complexity of distributed systems.
- Not recognizing that some database operations don't scale horizontally well, particularly those requiring cross-partition transactions.
Sample answer
Vertical scaling means upgrading your single database server with more powerful hardware like additional CPU cores or RAM, which is straightforward but eventually hits physical and cost limits. Horizontal scaling distributes your database across multiple servers, either through read replicas, sharding, or clustering.
At my previous company, we started with vertical scaling for our OLTP workload because it kept our application logic simple, but when we hit I/O bottlenecks on our analytics queries, we implemented read replicas for horizontal scaling of reporting workloads. The key is matching the scaling approach to your specific bottleneck and complexity tolerance.
How to level up
- Consider workload-specific scaling strategies like read replicas for read-heavy applications or functional partitioning for different service boundaries.
- Evaluate cloud database services that can provide both scaling options with managed complexity.
- Plan for data migration and application changes early when considering horizontal scaling approaches.
Follow-up questions to expect
- How would you decide between read replicas and sharding for horizontal scaling?
- What are the challenges of maintaining data consistency across horizontally scaled databases?
- How do you handle database schema changes in a horizontally scaled environment?
How do you compare performance between two SQL queries?
What they're really asking
This tests your knowledge of performance measurement techniques and analytical thinking about query optimization. The interviewer wants to see if you can systematically evaluate query performance beyond just execution time.
How you'll be scored
Only mentions timing queries with basic methods without considering other performance metrics or proper testing methodology.
Uses execution plans and timing with some awareness of testing conditions and multiple performance metrics.
Demonstrates comprehensive performance analysis including execution plans, resource utilization, statistical significance, and considers various performance dimensions like scalability and concurrency.
How to structure your answer
- Describe your testing environment setup for fair comparison.
- Explain the metrics you measure beyond just execution time.
- Detail your methodology for ensuring reliable results.
- Discuss how you analyze and interpret the differences.
- Address how findings translate to production performance.
Key points to hit
- Compare queries in identical environments with warmed caches and representative data volumes to ensure fair testing.
- Analyze execution plans to understand resource usage patterns, not just final execution time.
- Measure multiple metrics including CPU usage, I/O operations, memory consumption, and concurrent query performance.
- Run multiple iterations and consider statistical significance rather than relying on single test results.
Common mistakes
- Comparing queries with different cache states or data volumes, which can make slower queries appear faster.
- Focusing only on execution time without considering resource consumption that might affect overall system performance.
Sample answer
I start by setting up identical test conditions with the same data set, cleared caches, and isolated environment. I use EXPLAIN ANALYZE to compare execution plans and see differences in scan types, join algorithms, and estimated vs actual row counts. For timing, I run each query multiple times and calculate averages to account for variability.
I also monitor resource usage like buffer reads, CPU time, and I/O operations because a query might run faster but use more resources.
At my last job, I compared two report queries where one was 20% faster but used 3x more memory, so we chose the slower option to avoid affecting concurrent users during peak hours.
How to level up
- Use query plan hashes to identify when optimizer chooses different execution paths for seemingly identical queries.
- Test queries under realistic concurrent load conditions since single-user performance can be misleading.
- Consider parameterized query performance with different parameter values to avoid plan cache sensitivity issues.
Follow-up questions to expect
- How do you account for different data distributions when comparing query performance?
- What tools do you use to simulate realistic concurrent workloads during performance testing?
- How would you compare performance when queries return different result sets?
Ready to put this into practice?
Try these questions in a mock interview →Still applying for jobs? Let Auto Apply do it
Top 15 Recommended for MockIF Page (8)
What are the different types of JOINs in SQL? Explain INNER, LEFT, RIGHT, FULL, and CROSS JOIN with examples.
What they're really asking
This tests your fundamental understanding of join operations and data retrieval patterns. The interviewer wants to see if you can explain join semantics clearly and choose appropriate join types for different business scenarios.
How you'll be scored
Lists join types but struggles to explain the differences or provides incorrect examples.
Correctly defines most join types with basic examples and shows understanding of when to use each.
Clearly explains all join types with practical examples, discusses null handling behavior, and demonstrates understanding of result set implications.
How to structure your answer
- Define each join type systematically.
- Provide concrete examples showing the differences.
- Explain when each join type is most appropriate.
- Address null handling and result set characteristics.
- Mention performance considerations for different join types.
Key points to hit
- INNER JOIN returns only matching rows from both tables, LEFT JOIN returns all left table rows plus matches, RIGHT JOIN returns all right table rows plus matches.
- FULL OUTER JOIN returns all rows from both tables with nulls where no match exists, CROSS JOIN returns the Cartesian product of both tables.
- LEFT and RIGHT JOINs preserve rows from one table and are crucial for finding missing relationships or avoiding data loss.
- Join choice affects both correctness and performance, with INNER JOIN typically being fastest due to smaller result sets.
Common mistakes
- Confusing LEFT and RIGHT JOIN behavior or not understanding that they can return different result sets.
- Using CROSS JOIN accidentally when missing a join condition, which creates massive result sets.
Sample answer
INNER JOIN returns only rows where the join condition matches in both tables. LEFT JOIN returns all rows from the left table plus matching rows from the right, with nulls for non-matches. For example, SELECT customers.name, orders.total FROM customers LEFT JOIN orders would show all customers including those without orders.
RIGHT JOIN works opposite to LEFT JOIN. FULL OUTER JOIN combines both LEFT and RIGHT behavior, showing all rows from both tables. CROSS JOIN multiplies every row from the first table with every row from the second table, which is rarely needed but useful for generating combinations like all possible product-color pairs.
How to level up
- Use EXISTS instead of INNER JOIN when you only need to check for related records without retrieving columns from the joined table.
- Consider join order and cardinality when writing complex multi-table joins as it affects query execution plans.
- Be aware that NULL values in join conditions never match, even with other NULLs, which can cause unexpected missing results.
Follow-up questions to expect
- How would you find customers who have never placed an order using these join types?
- What happens when you join on columns that contain NULL values?
- When might you use a RIGHT JOIN instead of rewriting it as a LEFT JOIN?
What is the difference between WHERE and HAVING?
What they're really asking
This tests your understanding of SQL clause execution order and filtering mechanics. The interviewer wants to see if you know when to filter rows versus groups and understand performance implications.
How you'll be scored
Gives vague answers about individual rows vs groups without explaining execution order or performance impact.
Correctly explains WHERE filters rows and HAVING filters groups with basic examples.
Explains execution order, performance differences, provides clear examples, and discusses when each clause runs in query processing.
How to structure your answer
- Define WHERE as row-level filtering that happens before grouping.
- Define HAVING as group-level filtering that happens after GROUP BY.
- Explain the execution order and performance implications.
- Provide concrete examples showing when each is appropriate.
Key points to hit
- WHERE executes before GROUP BY and filters individual rows, making it more efficient for reducing dataset size early.
- HAVING executes after GROUP BY and can only filter on aggregate functions or grouped columns.
- Performance consideration: WHERE reduces rows before expensive grouping operations, HAVING processes after grouping.
- You cannot use aggregate functions in WHERE clause, but you can in HAVING clause.
Common mistakes
- Saying they're interchangeable or can always be used in place of each other.
- Not mentioning that WHERE cannot contain aggregate functions while HAVING can.
Sample answer
WHERE and HAVING both filter data, but they work at different stages of query execution. WHERE filters individual rows before any grouping happens, so it runs early and reduces the dataset size efficiently. HAVING filters groups after GROUP BY has already created them.
For example, 'WHERE salary > 50000' filters employees before grouping, while 'HAVING COUNT(*) > 5' filters departments that have more than 5 employees after grouping. The key performance difference is that WHERE reduces data early in the process, making subsequent operations faster, while HAVING works on the already-grouped results.
How to level up
- Always prefer WHERE over HAVING when possible because filtering rows early is more efficient than filtering groups.
- Remember that WHERE cannot reference column aliases from SELECT, but HAVING can reference aggregate results.
- Consider that WHERE can use indexes effectively, while HAVING typically cannot since it operates on grouped data.
Follow-up questions to expect
- Can you write a query that uses both WHERE and HAVING clauses appropriately?
- What happens if you try to use an aggregate function in a WHERE clause?
- How would you optimize a query that currently uses HAVING for non-aggregate conditions?
What is a subquery? Explain correlated vs non-correlated subqueries.
What they're really asking
This tests your understanding of nested query execution and data dependency patterns. The interviewer wants to see if you know when subqueries execute and can identify performance implications of different subquery types.
How you'll be scored
Defines subquery as nested query but cannot explain execution differences or performance implications between correlated and non-correlated types.
Correctly explains basic difference that correlated subqueries reference outer query and non-correlated ones don't, with simple examples.
Explains execution patterns, performance implications, provides clear examples, and discusses when to use each type or alternatives like JOINs.
How to structure your answer
- Define subquery as a nested query within another SQL statement.
- Explain non-correlated subqueries execute once independently.
- Explain correlated subqueries execute once per outer row.
- Compare performance characteristics and appropriate use cases.
Key points to hit
- Non-correlated subqueries execute once and return results that the outer query uses, making them generally more efficient.
- Correlated subqueries reference columns from the outer query and execute repeatedly for each outer row, creating potential performance issues.
- Subqueries can appear in SELECT, FROM, WHERE, and HAVING clauses with different performance characteristics in each location.
- Many correlated subqueries can be rewritten as JOINs for better performance, but some logic is clearer with subqueries.
Common mistakes
- Not understanding that correlated subqueries execute multiple times, leading to performance problems with large datasets.
- Thinking all subqueries are bad for performance when non-correlated ones can be quite efficient.
Sample answer
A subquery is a query nested inside another SQL statement. Non-correlated subqueries are independent and execute once, like 'SELECT * FROM employees WHERE department_id IN (SELECT id FROM departments WHERE location = "New York")'. The inner query runs first and returns department IDs, then the outer query uses those results.
Correlated subqueries reference the outer query and execute once for each outer row, like 'SELECT * FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department = e.department)'. Here, the subquery runs for every employee to calculate their department's average.
Correlated subqueries can be slower because they execute repeatedly, but they're useful for row-by-row comparisons that JOINs cannot easily express.
How to level up
- Consider rewriting correlated subqueries as window functions or JOINs when possible for better performance.
- Use EXISTS instead of IN with correlated subqueries when checking for presence rather than specific values.
- Be aware that subqueries in SELECT clauses (scalar subqueries) must return exactly one value or will cause errors.
Follow-up questions to expect
- How would you rewrite this correlated subquery as a JOIN for better performance?
- When would you prefer a subquery over a JOIN despite potential performance costs?
- What are the risks of using IN with subqueries that might return NULL values?
What is a CTE (Common Table Expression) and when would you use one?
What they're really asking
This tests your understanding of query organization and reusability patterns. The interviewer wants to see if you know when CTEs improve readability and performance compared to subqueries or temporary tables.
How you'll be scored
Knows CTE is a named temporary result set but cannot explain advantages or appropriate use cases compared to alternatives.
Correctly explains CTE syntax and basic use for readability, with simple examples of replacing subqueries.
Explains readability benefits, recursive capabilities, performance considerations, multiple reference advantages, and when to choose CTEs over alternatives.
How to structure your answer
- Define CTE as a named temporary result set that exists within a single statement.
- Explain the WITH clause syntax and how CTEs are referenced.
- Discuss advantages: readability, reusability, and recursive queries.
- Compare with alternatives like subqueries, temp tables, and views.
Key points to hit
- CTEs improve query readability by breaking complex logic into named, reusable components that can be referenced multiple times.
- Unlike subqueries, CTEs are defined once and can be referenced multiple times in the main query, avoiding duplication.
- Recursive CTEs enable hierarchical queries like organizational charts or bill of materials that are difficult with standard SQL.
- CTEs exist only for the duration of the statement, unlike temporary tables, and are often optimized by the query engine.
Common mistakes
- Thinking CTEs always improve performance when they might be materialized or executed multiple times depending on usage.
- Not understanding that CTEs cannot be indexed like temporary tables, which may impact performance for complex operations.
Sample answer
A CTE or Common Table Expression is a named temporary result set defined with the WITH clause that exists only within a single SQL statement. For example, 'WITH high_performers AS (SELECT * FROM employees WHERE rating > 4) SELECT * FROM high_performers WHERE department = "Sales"'.
I use CTEs when complex queries become hard to read with nested subqueries, when I need to reference the same subquery multiple times, or when writing recursive queries for hierarchical data like manager-employee relationships. They make queries more maintainable because the logic is broken into named, understandable chunks.
Unlike temporary tables, CTEs don't persist beyond the statement, and unlike subqueries, I can reference them multiple times without rewriting the logic.
How to level up
- Use multiple CTEs in sequence to build complex transformations step by step, making debugging easier.
- Consider that CTEs can sometimes be less efficient than JOINs if the optimizer materializes them unnecessarily.
- Leverage recursive CTEs for tree traversal problems, but set appropriate recursion limits to prevent infinite loops.
Follow-up questions to expect
- How would you write a recursive CTE to find all employees in a management hierarchy?
- When would you choose a temporary table over a CTE for complex data processing?
- Can you show how a CTE might be more readable than equivalent subqueries in a complex report query?
Write a query to find the Nth highest salary in a table.
What they're really asking
This tests window functions knowledge and ranking logic. The interviewer wants to see if you can handle the edge case where multiple people have the same salary and understand different approaches like DENSE_RANK vs ROW_NUMBER.
How you'll be scored
Provides a solution that doesn't handle ties correctly or uses inefficient approaches like multiple subqueries.
Uses window functions correctly but doesn't discuss the tie-handling differences between RANK, DENSE_RANK, and ROW_NUMBER.
Provides multiple solutions, explains tie-handling behavior, discusses performance considerations, and asks clarifying questions about business requirements.
How to structure your answer
- Clarify how to handle ties (what does 'Nth highest' mean with duplicates)
- Present the window function solution with appropriate ranking function.
- Explain the difference between RANK, DENSE_RANK, and ROW_NUMBER for this use case.
- Show the complete query with proper filtering.
- Mention alternative approaches and their trade-offs.
Key points to hit
- DENSE_RANK() handles ties by giving the same rank to equal values and continues ranking without gaps, making it ideal for 'Nth distinct salary'
- ROW_NUMBER() assigns unique sequential numbers even for ties, which may not match business logic expectations.
- The window function approach with PARTITION and filtering is more efficient than multiple nested subqueries.
- Always consider edge cases like fewer than N distinct salaries in the table.
Common mistakes
- Using ROW_NUMBER() without understanding it will arbitrarily pick one person when salaries are tied.
- Writing inefficient nested subqueries instead of using window functions for ranking operations.
Sample answer
I'd first clarify whether we want the Nth distinct salary value or if tied salaries should be handled in a specific way. Assuming we want the Nth distinct highest salary, I'd use: SELECT DISTINCT salary FROM (SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM employees) ranked WHERE rank = N.
I'm using DENSE_RANK because it handles ties properly - if two people have the same salary, they get the same rank, and the next rank continues sequentially. This is different from ROW_NUMBER which would arbitrarily assign different ranks to tied salaries, or RANK which would skip numbers after ties.
How to level up
- Discuss using LIMIT/OFFSET with ORDER BY as an alternative approach and when it might be more appropriate.
- Mention indexing strategy - a descending index on salary would optimize this query significantly.
- Consider mentioning the business context - sometimes you want the person with Nth salary, sometimes just the salary value itself.
Follow-up questions to expect
- How would you modify this to find the Nth highest salary within each department?
- What if the requirement was to find all employees who have the Nth highest salary?
- How would you optimize this query if the employee table had millions of records?
What are the ACID properties of a database transaction?
What they're really asking
This tests fundamental database transaction knowledge and system design understanding. The interviewer wants to see if you understand each ACID property conceptually and can explain how they work together to ensure data integrity in concurrent systems.
How you'll be scored
Lists the acronym without explaining what each property means or why they matter for data integrity.
Defines each property correctly but with limited understanding of how they interact or their practical implications.
Explains each property with concrete examples, discusses how they work together, mentions trade-offs with performance, and understands isolation levels.
How to structure your answer
- Define ACID as the four fundamental properties ensuring transaction reliability.
- Explain Atomicity with an example of all-or-nothing behavior.
- Describe Consistency and how it maintains database rules and constraints.
- Cover Isolation and how it handles concurrent transaction interference.
- Explain Durability and persistence guarantees after transaction completion.
Key points to hit
- Atomicity ensures transactions are all-or-nothing - if any part fails, the entire transaction is rolled back to maintain data integrity.
- Consistency guarantees that transactions only leave the database in valid states that respect all constraints and business rules.
- Isolation prevents concurrent transactions from interfering with each other through various isolation levels like READ COMMITTED or SERIALIZABLE.
- Durability ensures that once a transaction is committed, the changes are permanently stored even if the system crashes immediately after.
Common mistakes
- Confusing isolation with atomicity - isolation is about concurrent transactions, atomicity is about individual transaction completeness.
- Not understanding that ACID properties often conflict with performance, requiring careful balance in real-world systems.
Sample answer
ACID properties ensure reliable database transactions. Atomicity means a transaction is all-or-nothing - like transferring money between accounts, either both the debit and credit succeed, or neither happens. Consistency ensures the database stays in a valid state - foreign key constraints are maintained, check constraints aren't violated.
Isolation prevents concurrent transactions from seeing each other's incomplete changes - if two people book the last airline seat simultaneously, only one succeeds. Durability guarantees that once I commit a transaction, it's permanently saved even if the server crashes seconds later. These properties work together to prevent data corruption in multi-user systems.
How to level up
- Discuss different isolation levels and their trade-offs between consistency and performance, like READ UNCOMMITTED vs SERIALIZABLE.
- Mention how NoSQL databases often relax some ACID properties for better performance and scalability.
- Explain how modern databases implement these properties using techniques like write-ahead logging and multi-version concurrency control.
Follow-up questions to expect
- Can you explain the different transaction isolation levels and when you'd use each?
- How do distributed databases maintain ACID properties across multiple servers?
- What happens to ACID properties in a database replication scenario?
What are the different transaction isolation levels in SQL?
What they're really asking
This tests your understanding of database concurrency control and data consistency. The interviewer wants to see if you can choose appropriate isolation levels for different business requirements and understand the trade-offs between consistency and performance.
How you'll be scored
Cannot name the isolation levels or confuses their behavior and the problems they prevent.
Names the four standard isolation levels and explains what phenomena each prevents like dirty reads and phantom reads.
Explains each level's trade-offs, provides realistic examples of when to use each, and understands the performance implications of stricter isolation.
How to structure your answer
- List the four standard isolation levels in order of strictness.
- Explain what phenomena each level prevents (dirty read, non-repeatable read, phantom read)
- Describe the concurrency trade-offs as isolation increases.
- Provide practical examples of when to choose each level.
- Mention performance and locking implications.
Key points to hit
- Read Uncommitted allows dirty reads but maximizes concurrency, Read Committed prevents dirty reads, Repeatable Read prevents non-repeatable reads, and Serializable prevents phantom reads.
- Higher isolation levels provide stronger consistency guarantees but reduce concurrency and can increase lock contention and deadlock risk.
- Read Committed is the default for most databases and works well for typical applications, while Serializable should be used sparingly due to performance impact.
- Choose isolation level based on whether your application can tolerate reading uncommitted data or needs perfect consistency for the specific transaction.
Common mistakes
- Confusing the phenomena each level prevents, especially mixing up non-repeatable reads and phantom reads.
- Not considering the performance trade-offs when recommending higher isolation levels, which can cause significant lock contention.
Sample answer
There are four standard isolation levels. Read Uncommitted allows dirty reads but gives maximum performance. Read Committed, which is usually the default, prevents dirty reads but allows non-repeatable reads. Repeatable Read ensures you get the same results if you read the same row twice in a transaction.
Serializable provides full isolation but can significantly impact performance. For most applications, I use Read Committed because it prevents seeing uncommitted changes while maintaining good concurrency. I only use Serializable for critical financial transactions where perfect consistency is required, and I'd use Read Uncommitted only for reporting queries where approximate data is acceptable.
How to level up
- Understand that some databases implement these levels differently, like SQL Server's Read Committed Snapshot Isolation that uses row versioning instead of locks.
- Consider using statement-level hints to change isolation for specific queries rather than entire transactions when you need mixed consistency requirements.
- Be aware that higher isolation levels can lead to more deadlocks, so you may need to implement retry logic in your application code.
Follow-up questions to expect
- What's the difference between a non-repeatable read and a phantom read?
- When might you choose Read Uncommitted isolation level in a real application?
- How would you handle deadlocks that occur more frequently at higher isolation levels?
What is database partitioning and sharding? When would you use each?
What they're really asking
This tests your understanding of horizontal scaling strategies for large databases. The interviewer wants to see if you can design systems that scale beyond single-server limits and understand the architectural trade-offs of distributed data storage.
How you'll be scored
Confuses partitioning with sharding or cannot explain when and why you would use these techniques.
Correctly distinguishes that partitioning splits tables within a database while sharding distributes data across multiple databases or servers.
Explains both techniques clearly, discusses partitioning strategies like range and hash, understands sharding trade-offs like cross-shard queries, and provides realistic use cases.
How to structure your answer
- Define partitioning as splitting tables within a single database instance.
- Define sharding as distributing data across multiple database instances.
- Explain different partitioning strategies (range, hash, list)
- Discuss the benefits and challenges of each approach.
- Provide examples of when to use partitioning versus sharding.
Key points to hit
- Partitioning splits large tables into smaller pieces within the same database to improve query performance and maintenance operations like backups.
- Sharding distributes data across multiple database servers to scale beyond single-server hardware limits but complicates queries that need data from multiple shards.
- Range partitioning works well for time-series data, while hash partitioning provides more even distribution but makes range queries harder.
- Sharding requires careful shard key selection to avoid hotspots and minimize cross-shard transactions that hurt performance.
Common mistakes
- Using the terms partitioning and sharding interchangeably when they solve different scaling problems at different levels.
- Not considering the complexity of cross-shard queries and transactions when recommending sharding as a solution.
Sample answer
Partitioning splits a large table into smaller pieces within the same database, like splitting a orders table by month so each partition contains one month's data. This improves query performance when you're searching recent orders and makes maintenance faster.
Sharding distributes data across multiple separate database servers, like putting East Coast customers on one server and West Coast on another. I'd use partitioning first when a single table becomes too large but the database server can still handle the load.
I'd only move to sharding when I need to scale beyond what one server can handle, because sharding makes cross-shard queries much more complex and requires application-level coordination.
How to level up
- Consider partition pruning in your queries to ensure the optimizer only scans relevant partitions, which requires WHERE clauses on the partition key.
- Design shard keys carefully to avoid hotspots where one shard gets disproportionate traffic, and consider consistent hashing for better distribution.
- Evaluate whether read replicas or vertical scaling might solve your problem before introducing the complexity of sharding.
Follow-up questions to expect
- How would you handle a query that needs data from multiple shards?
- What problems could arise if you choose a poor shard key for your data distribution?
- How would you migrate an existing single-database application to use sharding?
Easy Level (16)
Histogram of Tweets: count tweets per user in a given time period
What they're really asking
This tests your ability to write GROUP BY queries with date filtering for time-series analysis. The interviewer wants to see if you can handle date functions, aggregation, and result filtering in a single query commonly used for analytics dashboards.
How you'll be scored
Writes a query that doesn't properly filter by date range or incorrectly groups the results without counting tweets per user.
Produces a working query with GROUP BY user and COUNT, includes basic date filtering in WHERE clause.
Writes an efficient query with proper date filtering, considers edge cases like users with zero tweets, discusses indexing strategy for the date column.
How to structure your answer
- Write the basic SELECT with COUNT and GROUP BY user.
- Add WHERE clause for date range filtering.
- Consider if you need HAVING for additional filtering.
- Discuss performance considerations for date queries.
- Address potential edge cases in the requirements.
Key points to hit
- Use COUNT(*) or COUNT(tweet_id) with GROUP BY user_id to count tweets per user, ensuring you're counting rows correctly.
- Date filtering should use WHERE with range conditions like created_at BETWEEN or created_at >= AND created_at < to use indexes effectively.
- Consider whether the business wants users with zero tweets in the time period included in results, which would require a LEFT JOIN approach.
- Index the date column used for filtering to avoid full table scans on large tweet tables.
Common mistakes
- Using HAVING instead of WHERE for date filtering, which applies the filter after grouping and is less efficient.
- Forgetting to consider time zone handling if the application serves users across different time zones.
Sample answer
I'd write SELECT user_id, COUNT(*) as tweet_count FROM tweets WHERE created_at >= '2024-01-01' AND created_at < '2024-02-01' GROUP BY user_id ORDER BY tweet_count DESC. This counts tweets per user for January 2024. I use WHERE for the date filter because it runs before grouping and can use an index on created_at. I'd make sure there's an index on created_at for performance since filtering dates on large tables can be expensive. If the business needs to see users who didn't tweet during this period, I'd need to LEFT JOIN with a users table instead.
How to level up
- Consider using date truncation functions like DATE_TRUNC or DATE_FORMAT if you need to group by day, week, or month rather than just filtering.
- For very large tables, consider whether partitioning by date would improve query performance for this type of time-based analysis.
- Add a LIMIT clause if this is for a dashboard display to prevent accidentally returning millions of users and impacting application performance.
Follow-up questions to expect
- How would you modify this query to show daily tweet counts for each user over the time period?
- What if you needed to include users who didn't tweet at all during this period?
- How would you optimize this query if the tweets table had 100 million rows?
Data Science Skills: find candidates with all 3 required skills
What they're really asking
This tests conditional aggregation and GROUP BY logic with HAVING clauses. The interviewer wants to see if you understand how to filter groups based on aggregate conditions, not just individual rows.
How you'll be scored
Uses WHERE instead of HAVING or writes a query that doesn't properly check for all 3 skills.
Correctly uses GROUP BY with HAVING COUNT(*) = 3 to find candidates with all skills.
Writes the correct query, explains why HAVING is needed over WHERE, and discusses potential data quality issues like duplicate skills.
How to structure your answer
- Identify that you need to group by candidate to count their skills.
- Use HAVING to filter groups that have exactly 3 skills.
- Consider whether to use COUNT(*) or COUNT(DISTINCT skill)
- Explain the difference between WHERE and HAVING for this problem.
Key points to hit
- HAVING filters groups after aggregation, while WHERE filters individual rows before grouping.
- GROUP BY candidate_id creates one row per candidate with their skill count.
- COUNT(*) = 3 ensures the candidate has exactly all required skills.
- Consider using COUNT(DISTINCT skill) if duplicate skill entries are possible.
Common mistakes
- Using WHERE COUNT(*) = 3 which causes a syntax error because WHERE cannot use aggregate functions.
- Not grouping by candidate_id, which would give you a total count across all candidates.
Sample answer
I need to group candidates by their ID and count how many skills each has. SELECT candidate_id FROM candidate_skills WHERE skill IN ('Python', 'Tableau', 'PostgreSQL') GROUP BY candidate_id HAVING COUNT(*) = 3. I'm using HAVING instead of WHERE because I need to filter based on the count after grouping.
The query first filters to only the three required skills, groups by candidate, then keeps only candidates who have all three skills.
How to level up
- Consider using COUNT(DISTINCT skill) if the skills table might have duplicate entries for the same candidate.
- You could also solve this with window functions or EXISTS subqueries, but GROUP BY with HAVING is most efficient.
- Think about whether you want candidates with additional skills beyond the three required.
Follow-up questions to expect
- What if we wanted candidates with at least 2 of the 3 skills instead?
- How would you modify this to show candidate names along with their skill count?
- What's the execution order difference between WHERE and HAVING clauses?
Page With No Likes: find pages with zero likes
What they're really asking
This tests LEFT JOIN semantics and NULL handling. The interviewer wants to see if you understand how to find missing relationships between tables using outer joins.
How you'll be scored
Uses INNER JOIN or writes a query that misses pages with zero likes entirely.
Correctly uses LEFT JOIN with IS NULL to find pages without likes.
Writes the correct LEFT JOIN query, explains why LEFT JOIN preserves all pages, and mentions alternative approaches like NOT EXISTS.
How to structure your answer
- Use LEFT JOIN to preserve all pages even if they have no likes.
- Filter for NULL values in the likes table to find pages with no matches.
- Consider alternative approaches like NOT EXISTS.
- Explain why INNER JOIN would be wrong for this problem.
Key points to hit
- LEFT JOIN preserves all rows from the left table (pages) even when no matching rows exist in the right table (likes)
- WHERE likes.page_id IS NULL filters for pages that had no matching likes.
- INNER JOIN would only return pages that have at least one like, missing the answer entirely.
- NOT EXISTS with a subquery is an alternative that may perform better on large datasets.
Common mistakes
- Using INNER JOIN which only returns pages that have likes, completely missing the pages with zero likes.
- Forgetting the IS NULL condition after the LEFT JOIN, which would return all pages regardless of like count.
Sample answer
I need to use a LEFT JOIN to keep all pages, even those without likes. SELECT pages.page_id, pages.page_name FROM pages LEFT JOIN likes ON pages.page_id = likes.page_id WHERE likes.page_id IS NULL.
The LEFT JOIN ensures every page appears in the result set, and then I filter for cases where the likes table shows NULL, meaning no matching like records were found. An INNER JOIN would be wrong here because it would only show pages that have likes.
How to level up
- NOT EXISTS can be more efficient than LEFT JOIN with IS NULL on large datasets with proper indexing.
- Consider using COUNT(likes.page_id) = 0 with GROUP BY if you need additional aggregate information.
- Make sure your NULL check is on a non-nullable column from the likes table to avoid false positives.
Follow-up questions to expect
- How would you solve this same problem using NOT EXISTS instead of LEFT JOIN?
- What's the performance difference between LEFT JOIN with IS NULL versus NOT EXISTS?
- If we wanted pages with exactly one like, how would you modify this query?
Unfinished Parts: find parts that were not finished in manufacturing
What they're really asking
This tests basic WHERE clause filtering with NULL value handling. The interviewer wants to see if you understand how NULL values behave in SQL comparisons and filtering logic.
How you'll be scored
Uses equality comparison like finish_date = NULL which doesn't work in SQL.
Correctly uses WHERE finish_date IS NULL to find unfinished parts.
Writes the correct query with IS NULL, explains why equality operators don't work with NULL, and mentions three-valued logic.
How to structure your answer
- Use WHERE clause with IS NULL to check for missing finish dates.
- Explain why finish_date = NULL doesn't work.
- Consider if NULL truly means 'unfinished' in the business context.
- Mention that NULL comparisons use three-valued logic in SQL.
Key points to hit
- IS NULL is the only way to check for NULL values because NULL = NULL evaluates to unknown, not true.
- WHERE finish_date IS NULL finds all parts where the finish date was never set.
- NULL represents unknown or missing data, not zero or empty string.
- Three-valued logic in SQL means comparisons can be true, false, or unknown (NULL)
Common mistakes
- Using finish_date = NULL which always evaluates to unknown and returns no rows.
- Assuming NULL means the same thing as an empty string or zero value.
Sample answer
I need to find parts where the finish_date column is NULL, which indicates they haven't been completed. SELECT part_id, part_name FROM parts WHERE finish_date IS NULL. I have to use IS NULL instead of = NULL because in SQL, any comparison with NULL using equality operators returns unknown, not true or false.
NULL represents missing data, so these are parts that haven't had their manufacturing process completed yet.
How to level up
- Consider whether your business logic should also check for parts with future finish dates that might be incorrectly entered.
- You might want to add additional filters like checking if start_date exists to ensure these are actually in-progress parts.
- Think about whether NULL finish_date definitely means unfinished, or if there could be data quality issues.
Follow-up questions to expect
- What would happen if you used WHERE finish_date = NULL instead?
- How would you find parts that were finished today?
- What's the difference between NULL, empty string, and zero in SQL?
Laptop vs. Mobile Viewership: count views by device type
What they're really asking
This tests conditional aggregation using CASE statements within aggregate functions. The interviewer wants to see if you can count different categories within a single query rather than using separate queries.
How you'll be scored
Writes separate queries for each device type or uses WHERE clauses that filter out data entirely.
Uses SUM with CASE WHEN to count views by device type in a single query.
Writes the correct conditional aggregation query, explains why SUM(CASE WHEN) works for counting, and discusses the efficiency benefits over separate queries.
How to structure your answer
- Use SUM with CASE WHEN to count views conditionally.
- Create separate columns for laptop and mobile counts.
- Explain why this is better than separate queries or filtering.
- Consider if you need to GROUP BY any dimensions.
Key points to hit
- SUM(CASE WHEN device_type = 'laptop' THEN 1 ELSE 0 END) counts rows meeting the condition.
- Conditional aggregation lets you create multiple metrics in one query pass.
- CASE WHEN inside aggregate functions is more efficient than multiple queries or subqueries.
- Consider whether you need to GROUP BY date, user, or other dimensions for the analysis.
Common mistakes
- Using WHERE clauses that filter out one device type, making it impossible to count both in the same query.
- Forgetting the ELSE 0 in the CASE statement, which could lead to NULL values in the sum.
Sample answer
I need to count views by device type using conditional aggregation. SELECT SUM(CASE WHEN device_type = 'laptop' THEN 1 ELSE 0 END) as laptop_views, SUM(CASE WHEN device_type = 'mobile' THEN 1 ELSE 0 END) as mobile_views FROM page_views. The CASE WHEN inside SUM lets me count rows that meet each condition.
This is much more efficient than running two separate queries because it only scans the table once.
How to level up
- You can use COUNT instead of SUM by using COUNT(CASE WHEN device_type = 'laptop' THEN 1 END) without the ELSE clause.
- Consider adding GROUP BY date or user_id if you need to break down the counts by additional dimensions.
- This pattern scales well for multiple device types by adding more CASE WHEN conditions.
Follow-up questions to expect
- How would you modify this to show the percentage split between laptop and mobile?
- What if we wanted to group these counts by date to see trends over time?
- Can you explain the difference between using COUNT and SUM for conditional aggregation?
Average Post Hiatus: find average days between posts per user
What they're really asking
This tests window functions with LAG and date arithmetic. The interviewer wants to see if you understand how to access previous row values and calculate differences between sequential records per user.
How you'll be scored
Uses self-joins or subqueries instead of window functions, or doesn't properly partition by user.
Uses LAG window function correctly to get the previous post date and calculates date differences.
Writes the correct LAG query with proper partitioning and ordering, calculates date differences, and explains why window functions are optimal for this problem.
How to structure your answer
- Use LAG window function partitioned by user and ordered by post date.
- Calculate date difference between current and previous post.
- Use AVG to get the average hiatus days per user.
- Handle the first post per user which has no previous post.
Key points to hit
- LAG(post_date) OVER (PARTITION BY user_id ORDER BY post_date) gets the previous post date for each user.
- DATEDIFF or date subtraction calculates days between current and previous posts.
- PARTITION BY user_id ensures you only look at previous posts from the same user, not across all users.
- The first post for each user will have NULL for the previous post date.
Common mistakes
- Not partitioning by user_id, which would get the previous post from any user instead of the same user.
- Forgetting to handle NULL values from the first post per user when calculating averages.
Sample answer
I need to use a window function to get each user's previous post date, then calculate the average gap. SELECT user_id, AVG(DATEDIFF(post_date, LAG(post_date) OVER (PARTITION BY user_id ORDER BY post_date))) as avg_hiatus_days FROM posts GROUP BY user_id.
The LAG function gets the previous post date for each user, partitioned by user_id so it doesn't cross users, and ordered by post date chronologically. Then I calculate the date difference and average it per user.
How to level up
- Consider using WHERE LAG(...) IS NOT NULL to exclude the first post per user from the average calculation.
- You might want to add HAVING COUNT(*) > 1 to only include users with multiple posts.
- For very large datasets, this window function approach is much more efficient than self-joins.
Follow-up questions to expect
- How would you find the user with the longest average posting gap?
- What if we wanted to find users whose posting frequency is increasing over time?
- Can you explain why LAG is better than a self-join for this problem?
Teams Power Users: find top 2 users by message count per team
What they're really asking
This tests your ability to solve a "top N per group" problem using window functions. The interviewer wants to see if you can partition data by team and rank users within each partition.
How you'll be scored
Uses GROUP BY to get counts but cannot limit to top 2 per team, or returns the global top 2 instead.
Correctly uses ROW_NUMBER with PARTITION BY team to rank users and filters for the top 2.
Handles ties correctly by choosing between ROW_NUMBER, RANK, and DENSE_RANK based on requirements, and ensures the message count aggregation happens before the ranking.
How to structure your answer
- Aggregate message counts per user per team.
- Apply ROW_NUMBER partitioned by team ordered by count descending.
- Filter for row number less than or equal to 2.
- Decide how to handle ties.
Key points to hit
- First aggregate with GROUP BY to get message_count per user per team, then rank using a window function in a second step.
- ROW_NUMBER() OVER (PARTITION BY team_id ORDER BY message_count DESC) ranks users within each team.
- Filtering WHERE rn <= 2 gives exactly 2 users per team.
- If you need to include all tied users at position 2, use RANK instead of ROW_NUMBER.
Common mistakes
- Trying to apply LIMIT 2 globally instead of per group, which only returns the top 2 overall.
- Applying ROW_NUMBER directly on the raw messages table instead of first aggregating counts, which ranks individual messages instead of users.
Sample answer
I solve this in two steps: aggregate then rank. WITH user_counts AS (SELECT team_id, user_id, COUNT(*) AS message_count FROM messages GROUP BY team_id, user_id), ranked AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY team_id ORDER BY message_count DESC) AS rn FROM user_counts) SELECT team_id, user_id, message_count FROM ranked WHERE rn <= 2 ORDER BY team_id, rn. The first CTE counts messages per user per team. The second CTE ranks users within each team by their count. Filtering rn <= 2 gives me exactly 2 users per team. If the requirement says to include all users tied for second place, I would swap ROW_NUMBER for RANK, which assigns the same rank to tied values.
How to level up
- DENSE_RANK is useful when you want exactly 2 distinct rank positions, which could return more than 2 rows if there are ties.
- An index on messages(team_id, user_id) speeds up the GROUP BY aggregation significantly.
- For very large datasets, consider using LATERAL JOIN with LIMIT 2 per team, which can be faster than a full window function scan.
Follow-up questions to expect
- What is the difference between ROW_NUMBER, RANK, and DENSE_RANK for this problem?
- How would you modify this to find the bottom 2 users instead?
- How would you handle a team that has fewer than 2 users?
Average Review Ratings: avg stars per product per month
What they're really asking
This tests your ability to combine date extraction with GROUP BY aggregation. The interviewer wants to see if you can extract month from a date column and compute averages across two grouping dimensions.
How you'll be scored
Cannot extract month from a date or groups by only one dimension instead of both product and month.
Correctly uses DATE_TRUNC or EXTRACT with GROUP BY to compute average stars per product per month.
Handles date extraction with proper truncation, rounds the average for readability, and discusses how to fill in months with no reviews.
How to structure your answer
- Extract or truncate the date to month granularity.
- Group by both product and month.
- Calculate AVG on the star rating column.
- Order results meaningfully.
Key points to hit
- DATE_TRUNC('month', review_date) groups all dates within a month together, which is cleaner than using EXTRACT for year and month separately.
- GROUP BY product_id, DATE_TRUNC('month', review_date) creates one row per product per month.
- AVG(stars) returns a decimal, so ROUND(AVG(stars), 2) makes the output readable.
- Months with no reviews for a product will be missing from results. Use a cross join with a date series to fill gaps if needed.
Common mistakes
- Using EXTRACT(MONTH ...) without also extracting the year, which would combine January 2025 and January 2026 into the same group.
- Forgetting that AVG ignores NULL values, which could be correct or incorrect depending on whether NULL means "no rating" or "unrated"
Sample answer
I use DATE_TRUNC to group by month and AVG for the rating: SELECT product_id, DATE_TRUNC('month', review_date) AS review_month, ROUND(AVG(stars), 2) AS avg_rating, COUNT(*) AS review_count FROM reviews GROUP BY product_id, DATE_TRUNC('month', review_date) ORDER BY product_id, review_month.
DATE_TRUNC('month', review_date) converts any date to the first day of its month, so all reviews in March 2026 become 2026-03-01. I include COUNT(*) alongside the average so you can see how many reviews the average is based on.
A product with an average of 5.0 from one review is very different from 4.8 from 500 reviews. If I needed to show months with zero reviews, I would generate a date series and LEFT JOIN the reviews to it.
How to level up
- In MySQL, use DATE_FORMAT(review_date, '%%Y-%%m') instead of DATE_TRUNC which is not available.
- Add a HAVING COUNT(*) >= 5 filter if you want to exclude months with too few reviews for a meaningful average.
- Consider showing a running average with AVG(stars) OVER (PARTITION BY product_id ORDER BY review_month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) for a 3-month rolling average.
Follow-up questions to expect
- How would you fill in months where a product received no reviews?
- How would you calculate the weighted average if each review has a helpfulness score?
- How would you find products whose average rating is declining over time?
Well Paid Employees: find employees earning more than their manager
What they're really asking
This tests your ability to perform a self-join to compare rows within the same table. The interviewer wants to see if you can relate an employee to their manager and filter based on a comparison between the two.
How you'll be scored
Cannot set up the self-join or joins on the wrong column, comparing unrelated employees.
Correctly writes a self-join on manager_id and filters where employee salary exceeds manager salary.
Handles NULL manager_id for top-level employees, considers edge cases, and discusses alternative approaches.
How to structure your answer
- Identify the self-join relationship via manager_id.
- Join the employee table to itself to pair each employee with their manager.
- Filter where the employee salary is greater than the manager salary.
- Consider NULL handling for employees without managers.
Key points to hit
- The join condition is e.manager_id = m.id where e is the employee alias and m is the manager alias.
- INNER JOIN naturally excludes employees with no manager since NULL manager_id will not match any id.
- The WHERE clause compares e.salary > m.salary after the join pairs each employee with their manager.
- This is a classic self-join pattern where the same table plays two different roles in the query.
Common mistakes
- Joining on the wrong columns, like joining id to id instead of manager_id to id.
- Using LEFT JOIN without filtering out NULL managers, which would include top-level employees in the results incorrectly.
Sample answer
This is a straightforward self-join. I alias the employees table twice, once as the employee and once as the manager: SELECT e.name AS employee_name, e.salary AS employee_salary, m.name AS manager_name, m.salary AS manager_salary FROM employees e JOIN employees m ON e.manager_id = m.id WHERE e.salary > m.salary.
The JOIN connects each employee to their manager by matching manager_id to id. The WHERE clause then filters to only those cases where the employee earns more. The INNER JOIN automatically excludes the CEO or top-level employees who have NULL manager_id, which is correct since they have no manager to compare against.
If I wanted to include additional context, I could add e.salary - m.salary AS salary_difference to show how much more the employee earns.
How to level up
- On large employee tables, ensure there is an index on the id column (usually the primary key) since the self-join looks up managers by id.
- You could also solve this with a correlated subquery: WHERE salary > (SELECT salary FROM employees m WHERE m.id = e.manager_id)
- In real HR analytics, you might want to show this as a percentage: ROUND((e.salary - m.salary) * 100.0 / m.salary, 1) AS pct_above_manager.
Follow-up questions to expect
- How would you find employees earning more than the average salary of all people at their manager's level?
- What if an employee has multiple reporting lines and you need to compare against all of them?
- How would you extend this to find the entire chain of employees who earn more than every manager above them?
Final Account Balance: calculate running balance from transactions
What they're really asking
This tests your ability to combine conditional aggregation with SUM to compute a final balance from credit and debit transactions. The interviewer wants to see if you can handle different transaction types and produce a meaningful total.
How you'll be scored
Sums all amounts without distinguishing between credits and debits, producing an incorrect balance.
Uses CASE inside SUM to correctly add credits and subtract debits for the final balance.
Shows both the final balance per account and the running balance over time, handles multiple accounts with GROUP BY or PARTITION BY.
How to structure your answer
- Identify how transaction types affect the balance (credit adds, debit subtracts)
- Use CASE inside SUM to conditionally add or subtract.
- Group by account for the final balance.
- Optionally show running balance over time with a window function.
Key points to hit
- SUM(CASE WHEN type = 'credit' THEN amount ELSE -amount END) converts all transactions into a single net amount.
- GROUP BY account_id collapses all transactions for each account into one final balance.
- For running balance over time, use SUM(...) OVER (PARTITION BY account_id ORDER BY transaction_date) as a window function.
- If the table stores debits as negative numbers already, a simple SUM(amount) GROUP BY account_id is sufficient.
Common mistakes
- Summing amounts without accounting for transaction direction, which treats debits the same as credits.
- Assuming the data model stores negative amounts for debits when the table might use a separate type column instead.
Sample answer
For the final balance per account, I use conditional aggregation: SELECT account_id, SUM(CASE WHEN type = 'credit' THEN amount WHEN type = 'debit' THEN -amount ELSE 0 END) AS final_balance FROM transactions GROUP BY account_id. This turns each debit into a negative value and sums everything up.
If I also want to see the running balance over time, I use a window function: SELECT account_id, transaction_date, type, amount, SUM(CASE WHEN type = 'credit' THEN amount ELSE -amount END) OVER (PARTITION BY account_id ORDER BY transaction_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_balance FROM transactions ORDER BY account_id, transaction_date.
The window function computes a cumulative sum that grows or shrinks with each transaction.
How to level up
- If you need the balance as of a specific date, add WHERE transaction_date <= '2026-03-01' before the GROUP BY.
- For high-volume financial systems, consider maintaining a balance snapshot table updated by triggers to avoid recalculating from all historical transactions.
- Use DECIMAL or NUMERIC types for financial amounts, never FLOAT, to avoid floating-point rounding errors.
Follow-up questions to expect
- How would you calculate the balance as of a specific date?
- What data type would you use for monetary amounts and why?
- How would you find accounts that went negative at any point in time?
App Click-through Rate (CTR): calculate CTR from impressions and clicks
What they're really asking
This tests your ability to calculate a ratio from event data using conditional aggregation. The interviewer wants to see if you can count different event types from the same table and handle division safely.
How you'll be scored
Cannot separate impressions from clicks in the aggregation or divides incorrectly.
Correctly counts impressions and clicks using CASE or filtered aggregation and calculates the ratio.
Handles division by zero with NULLIF, casts to avoid integer division, rounds to a readable percentage, and groups by the appropriate dimension like app_id or date.
How to structure your answer
- Count impressions and clicks separately using conditional SUM or COUNT.
- Calculate CTR as clicks divided by impressions times 100.
- Handle division by zero.
- Cast to decimal to avoid integer division truncation.
Key points to hit
- CTR = (number of clicks / number of impressions) * 100, expressed as a percentage.
- Use SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) to count clicks from a mixed event table.
- NULLIF(impressions, 0) in the denominator converts zero to NULL, which makes the division return NULL instead of an error.
- Cast to DECIMAL or multiply by 100.0 (with decimal point) to avoid integer division truncating the result to 0.
Common mistakes
- Using integer division which truncates 100/300 to 0 instead of 0.33. Always cast one operand to DECIMAL or use 100.0.
- Not handling the case where a product has zero impressions, which causes a division by zero error.
Sample answer
I calculate CTR by counting clicks and impressions separately, then dividing: SELECT app_id, SUM(CASE WHEN event_type = 'impression' THEN 1 ELSE 0 END) AS impressions, SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) AS clicks, ROUND(SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) * 100.0 / NULLIF(SUM(CASE WHEN event_type = 'impression' THEN 1 ELSE 0 END), 0), 2) AS ctr_pct FROM events WHERE event_type IN ('impression', 'click') GROUP BY app_id ORDER BY ctr_pct DESC.
I multiply by 100.0 with a decimal point to force decimal division. NULLIF converts a zero impression count to NULL so the division returns NULL instead of crashing. ROUND to 2 decimal places makes the percentage readable.
How to level up
- If impressions and clicks are in separate tables, use a LEFT JOIN to ensure apps with impressions but no clicks show 0% instead of being excluded.
- For time-series CTR, add DATE_TRUNC('day', event_time) to the GROUP BY to see daily trends.
- Consider using FILTER (WHERE ...) syntax in PostgreSQL instead of CASE: COUNT(*) FILTER (WHERE event_type = 'click') which is more readable.
Follow-up questions to expect
- How would you calculate CTR per day for trend analysis?
- What if impressions and clicks are in different tables?
- How would you find apps whose CTR dropped significantly compared to the previous week?
Second Day Confirmation: users who confirmed on the day after signup
What they're really asking
This tests your ability to combine JOINs with date arithmetic to filter records based on temporal relationships. The interviewer wants to see if you understand how to correlate user actions across different days using date functions.
How you'll be scored
Uses incorrect date arithmetic or fails to properly join the tables, potentially counting users who confirmed on the wrong day.
Correctly joins tables and uses date arithmetic to find next-day confirmations with proper syntax.
Provides correct solution with date arithmetic, explains timezone considerations, and discusses index strategy for date-based queries.
How to structure your answer
- Identify the two tables needed: user signups and confirmations.
- Plan the JOIN condition linking users between tables.
- Apply date arithmetic to compare confirmation date to signup date + 1.
- Filter for exact next-day matches.
- Select the appropriate user identifiers.
Key points to hit
- Use DATEADD or DATE arithmetic to compare confirmation_date to signup_date + 1 day for exact matching.
- JOIN the tables on user_id to correlate signup and confirmation events for the same person.
- Consider timezone handling if dates are stored with time components to avoid missing confirmations.
- Index both date columns and user_id for efficient execution of date range queries.
Common mistakes
- Using DATEDIFF incorrectly or not accounting for time components when dates include timestamps.
- Forgetting to JOIN on user_id, which would create a cartesian product and incorrect results.
Sample answer
I need to join the users and confirmations tables on user_id, then filter where the confirmation happened exactly one day after signup. I'd write: SELECT u.user_id FROM users u JOIN confirmations c ON u.user_id = c.user_id WHERE DATE(c.confirmed_at) = DATE(u.signup_date) + INTERVAL 1 DAY.
This handles the date arithmetic properly and ensures we're only getting users who confirmed the day immediately following their signup.
How to level up
- Discuss partitioning strategies if this query runs frequently on large datasets with time-based data.
- Mention how you'd handle edge cases like users signing up near midnight in different timezones.
- Explain when you might denormalize by storing computed confirmation_lag to avoid repeated date arithmetic.
Follow-up questions to expect
- How would you modify this to find users who confirmed within 2-7 days of signup?
- What indexes would you add to optimize this query on a table with millions of users?
- How would you handle timezone differences between signup and confirmation events?
IBM db2 Product Analytics: count unique queries per employee
What they're really asking
This tests your understanding of COUNT DISTINCT with GROUP BY to eliminate duplicate counting while aggregating by categories. The interviewer wants to see if you know when to use DISTINCT in aggregations and how it affects performance.
How you'll be scored
Uses COUNT without DISTINCT, leading to incorrect results that count the same query multiple times per employee.
Correctly uses COUNT DISTINCT with GROUP BY to get unique query counts per employee.
Provides correct COUNT DISTINCT solution, explains the performance impact of DISTINCT, and suggests optimization strategies.
How to structure your answer
- Identify that you need unique queries per employee, not total executions.
- Use GROUP BY employee_id to create separate counts for each person.
- Apply COUNT DISTINCT on query_id to eliminate duplicate query executions.
- Include employee identifier in SELECT for meaningful results.
- Consider sorting results for presentation.
Key points to hit
- COUNT DISTINCT eliminates duplicate query_ids within each employee group, preventing overcounting repeated queries.
- GROUP BY employee_id creates separate aggregation buckets for each person's unique query count.
- DISTINCT operations require additional memory for deduplication and can impact performance on large datasets.
- Consider indexing on (employee_id, query_id) to optimize the GROUP BY and DISTINCT operations.
Common mistakes
- Using COUNT(*) or COUNT(query_id) without DISTINCT, which counts every execution rather than unique queries.
- Forgetting the GROUP BY clause, which would give a single count across all employees instead of per-employee counts.
Sample answer
I need to count unique queries per employee, so I'll use COUNT DISTINCT with GROUP BY. The query would be: SELECT employee_id, COUNT DISTINCT query_id as unique_queries FROM query_history GROUP BY employee_id ORDER BY unique_queries DESC.
This ensures that if an employee runs the same query multiple times, it only counts once in their total, giving us the true number of different queries each person has used.
How to level up
- For very large datasets, consider using approximate distinct counts like HyperLogLog if exact precision isn't required.
- Mention that you could add HAVING clauses to filter employees with query counts above or below certain thresholds.
- Discuss how you might partition the data by time period if this analysis needs to be run for different date ranges.
Follow-up questions to expect
- How would you modify this to show the time period when each employee was most active?
- What if you needed to exclude certain types of system queries from this count?
- How would you optimize this query if the query_history table had 100 million rows?
Cards Issued Difference: max minus min cards issued per card name
What they're really asking
This tests your ability to use aggregate functions with GROUP BY to find ranges within grouped data. The interviewer wants to see if you understand how MIN and MAX work within groups and can perform arithmetic on aggregate results.
How you'll be scored
Attempts to find difference without proper grouping or tries to use MIN/MAX incorrectly outside of GROUP BY context.
Correctly groups by card name and calculates MAX minus MIN for issued counts within each group.
Provides correct aggregate solution, explains why GROUP BY is necessary, and discusses potential edge cases like cards with only one issuance.
How to structure your answer
- Group the data by card_name to analyze each card type separately.
- Apply MAX function to find highest issued count per card.
- Apply MIN function to find lowest issued count per card.
- Subtract MIN from MAX to get the difference.
- Include card_name in SELECT to identify which difference belongs to which card.
Key points to hit
- GROUP BY card_name creates separate analysis buckets for each card type's issuance history.
- MAX and MIN operate within each group to find the range of issued counts for that specific card.
- Subtracting MIN from MAX gives the spread between highest and lowest issuance periods for each card.
- Cards with consistent issuance will have difference of 0, while volatile cards will show larger differences.
Common mistakes
- Forgetting GROUP BY and trying to calculate a single difference across all cards instead of per card type.
- Confusing the syntax by trying to nest the subtraction inside the aggregate functions rather than subtracting the aggregates.
Sample answer
I need to find the range of cards issued for each card name, so I'll group by card name and find the difference between maximum and minimum issuances. My query would be: SELECT card_name, MAX cards_issued - MIN cards_issued as difference FROM monthly_cards_issued GROUP BY card_name ORDER BY difference DESC.
This shows me which card types have the most volatile issuance patterns versus those with steady issuance numbers.
How to level up
- Consider adding a HAVING clause to filter out cards where the difference is zero if you only want to see volatile cards.
- Discuss how you might join with a card details table to add context like card category or launch date.
- Mention calculating coefficient of variation if you wanted to normalize the volatility by the average issuance.
Follow-up questions to expect
- How would you find the months when each card hit its maximum and minimum issuance?
- What if you wanted to exclude cards that were only issued in one month from this analysis?
- How would you modify this to show the difference as a percentage of the average issuance?
Compressed Mean: weighted average from frequency table
What they're really asking
This tests your understanding of weighted averages using SUM with multiplication and proper data type handling with CAST. The interviewer wants to see if you can implement statistical calculations and handle integer division precision issues.
How you'll be scored
Attempts simple average without using frequency weights or fails to handle integer division properly, giving incorrect results.
Correctly multiplies values by frequencies and divides by total frequency, with proper CAST for decimal precision.
Implements weighted average correctly with CAST, explains why CAST is necessary for precision, and discusses alternative approaches for large datasets.
How to structure your answer
- Calculate the numerator by summing value times frequency for each row.
- Calculate the denominator by summing all frequencies.
- Divide numerator by denominator for weighted average.
- Use CAST to ensure decimal precision rather than integer division.
- Consider rounding the final result to appropriate decimal places.
Key points to hit
- Multiply each value by its frequency before summing to weight each value by how often it occurs.
- Use CAST AS DECIMAL or FLOAT to prevent integer division truncation that would lose precision.
- The denominator should be SUM frequency, not COUNT rows, since frequencies represent actual data point counts.
- Weighted average differs from simple average because it accounts for how frequently each value appears in the original dataset.
Common mistakes
- Using simple AVG function instead of implementing weighted average with frequency multiplication.
- Forgetting CAST and losing precision due to integer division truncating decimal results.
Sample answer
I need to calculate a weighted average where each value is multiplied by how frequently it appears. The formula is sum of value times frequency divided by sum of frequencies. My query would be: SELECT CAST SUM value * frequency AS DECIMAL / SUM frequency as weighted_average FROM frequency_table.
I'm using CAST to ensure I get decimal precision instead of integer division, which would truncate my result and give an inaccurate average.
How to level up
- Consider using ROUND to control decimal places in the final result for cleaner presentation.
- Mention that for very large datasets, you might need to watch for overflow when multiplying values by frequencies.
- Discuss how this approach is more memory efficient than expanding the frequency table into individual rows.
Follow-up questions to expect
- How would you also calculate the weighted standard deviation from this same frequency table?
- What if some frequencies were zero or null - how would you handle those edge cases?
- How would you modify this to calculate weighted averages grouped by another category column?
Pharmacy Analytics Parts 1-3: drug profitability analysis
What they're really asking
This tests your ability to use ORDER BY with aggregations and TOP N filtering to rank business metrics. The interviewer wants to see if you can identify the most important records based on calculated profitability metrics.
How you'll be scored
Fails to properly calculate profit margin or doesn't use appropriate ordering and limiting to find top performers.
Correctly calculates profit metrics and uses ORDER BY with LIMIT or TOP to find highest-profit drugs.
Implements complete profitability analysis with proper ordering, discusses business logic for profit calculations, and suggests additional metrics for comprehensive analysis.
How to structure your answer
- Calculate profit margin or absolute profit for each drug using revenue minus cost.
- Use ORDER BY with calculated profit metric in descending order.
- Apply TOP N or LIMIT clause to get only the most profitable drugs.
- Include relevant drug identifiers and profit metrics in SELECT.
- Consider grouping if multiple records exist per drug.
Key points to hit
- ORDER BY profit DESC ensures highest-profit drugs appear first in the result set.
- Use LIMIT or TOP N to restrict results to only the most profitable drugs as requested.
- Calculate profit as total_sales minus cogs or similar cost metric, depending on available columns.
- Consider whether to rank by absolute profit dollars or profit margin percentage based on business needs.
Common mistakes
- Ordering by sales revenue instead of profit, which ignores cost differences between drugs.
- Forgetting to use LIMIT or TOP to restrict results, returning all drugs instead of just the top performers.
Sample answer
I need to find the most profitable drugs by calculating profit and ranking them. My approach would be: SELECT drug_name, total_sales - cogs as profit FROM pharmacy_sales ORDER BY total_sales - cogs DESC LIMIT 3.
This calculates profit for each drug, sorts from highest to lowest profit, and gives me the top 3 most profitable drugs. I'm using absolute profit rather than margin because the business typically cares more about total profit contribution than percentage margins.
How to level up
- Consider calculating both absolute profit and profit margin percentage to give management different perspectives on performance.
- Discuss how you might filter out drugs with very low sales volumes that might have high margins but low strategic importance.
- Mention partitioning results by drug category if the business wants top performers within each therapeutic area.
Follow-up questions to expect
- How would you identify drugs that have high sales volume but surprisingly low profit margins?
- What if you wanted to find the most profitable drugs within each pharmacy location?
- How would you modify this analysis to look at profit trends over time rather than just current totals?
Ready to put this into practice?
Try these questions in a mock interview →Still applying for jobs? Let Auto Apply do it
Medium Level (16)
User's Third Transaction: find each user's third purchase
What they're really asking
This tests window function mastery and filtering logic with ROW_NUMBER(). The interviewer wants to see if you understand partitioning data by user and can filter ranked results correctly without causing performance issues.
How you'll be scored
Uses a subquery with COUNT(*) or gets the logic wrong, missing users who don't have a third transaction.
Correctly uses ROW_NUMBER() with PARTITION BY and filters with WHERE rn = 3.
Correct window function solution plus discusses handling users with fewer than 3 transactions and mentions indexing strategy for user_id and purchase_date.
How to structure your answer
- Use ROW_NUMBER() window function partitioned by user.
- Order by transaction date within each partition.
- Filter results where row number equals 3.
- Handle edge case of users with fewer than 3 transactions.
- Consider performance implications of the window function.
Key points to hit
- ROW_NUMBER() PARTITION BY user_id ORDER BY purchase_date gives sequential ranking per user.
- Filter with WHERE rn = 3 in outer query since window functions can't be used directly in WHERE clause.
- Users with fewer than 3 transactions won't appear in results, which may or may not be desired behavior.
- Index on (user_id, purchase_date) will optimize the window function performance.
Common mistakes
- Trying to use window functions directly in WHERE clause instead of using a subquery or CTE.
- Using RANK() instead of ROW_NUMBER(), which could skip numbers if there are ties in purchase dates.
Sample answer
I'd use ROW_NUMBER() with PARTITION BY to rank each user's transactions. The query would be: WITH ranked_purchases AS (SELECT user_id, purchase_date, amount, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY purchase_date) as rn FROM purchases) SELECT user_id, purchase_date, amount FROM ranked_purchases WHERE rn = 3.
This partitions the data by user, orders each user's purchases chronologically, and assigns row numbers. Then I filter for row number 3 to get each user's third purchase.
One thing to note is that users with fewer than 3 purchases won't appear in the results, so we might want to consider if that's the intended behavior.
How to level up
- Discuss whether to use purchase_date alone or include purchase_id as a tiebreaker for consistent ordering.
- Consider if the business logic should handle same-day purchases differently.
- Mention partitioning strategy if this is a large table with time-based queries.
Follow-up questions to expect
- What if we wanted to show users with fewer than 3 transactions as well?
- How would you modify this to get the third transaction by amount instead of date?
- What indexes would you create to optimize this query on a table with millions of rows?
Second Highest Salary: find 2nd highest salary in a table
What they're really asking
This tests your understanding of ranking and subquery logic while handling the edge case where there might not be a second highest value. The interviewer wants to see if you consider duplicate salaries and null results.
How you'll be scored
Uses MAX() with a clunky subquery that breaks with duplicate salaries or returns incorrect results.
Uses DENSE_RANK() or proper subquery logic to find second highest, handling duplicates correctly.
Correct solution plus explains difference between RANK() and DENSE_RANK(), discusses null handling, and considers performance with large datasets.
How to structure your answer
- Choose between DENSE_RANK() window function or subquery approach.
- Handle duplicate salary values correctly.
- Account for case where second highest doesn't exist.
- Explain why your chosen method handles edge cases.
- Consider query performance implications.
Key points to hit
- DENSE_RANK() handles duplicate salaries better than RANK() because it doesn't skip rank numbers.
- Alternative subquery approach: find MAX(salary) WHERE salary < (SELECT MAX(salary) FROM table)
- Consider whether duplicate salaries at second highest should all be returned or just one row.
- Query returns NULL or no rows if there's only one distinct salary value in the table.
Common mistakes
- Using RANK() instead of DENSE_RANK(), which creates gaps in ranking when there are ties.
- Not considering the case where all employees have the same salary or there's only one employee.
Sample answer
I'd use DENSE_RANK() to handle this properly. The query would be: WITH salary_ranks AS (SELECT employee_id, salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM employees) SELECT DISTINCT salary FROM salary_ranks WHERE rank = 2.
I'm using DENSE_RANK() instead of RANK() because if multiple employees have the highest salary, RANK() would skip rank 2 entirely, but DENSE_RANK() keeps consecutive numbers. This approach returns all employees with the second highest salary amount. If there's no second highest salary, like when all employees earn the same amount, the query returns no rows.
How to level up
- Compare performance of window function vs subquery approach on large datasets.
- Discuss whether business wants all employees at second highest salary or just the salary amount.
- Consider adding LIMIT 1 if you only need to verify existence of second highest salary.
Follow-up questions to expect
- How would you modify this to return employee details, not just the salary amount?
- What if we wanted the Nth highest salary instead, where N is a parameter?
- Which approach would perform better on a table with 10 million employees?
Sending vs. Opening Snaps: time spent sending vs opening by age group
What they're really asking
This tests complex aggregation with conditional logic using CASE statements and percentage calculations. The interviewer wants to see if you can break down time spent by activity type and calculate meaningful ratios across different user segments.
How you'll be scored
Attempts separate queries for each metric or gets the CASE logic wrong, missing the percentage calculation.
Correctly uses CASE with SUM() to aggregate time by activity type and calculates basic percentages.
Clean CASE aggregation plus handles division by zero, discusses potential issues with age grouping, and considers how to validate the percentage calculations make sense.
How to structure your answer
- Use CASE statements within SUM() to separate sending vs opening time.
- Group by age ranges or individual ages as needed.
- Calculate percentages using the conditional sums.
- Handle potential division by zero scenarios.
- Validate that percentages make logical sense.
Key points to hit
- CASE WHEN activity_type = 'send' THEN time_spent ELSE 0 END within SUM() aggregates time by activity type.
- Calculate percentage as (sending_time / total_time) * 100, ensuring total_time is not zero.
- GROUP BY age or age ranges depending on desired granularity of the analysis.
- Consider using COALESCE or NULLIF to handle edge cases where users have zero total time.
Common mistakes
- Forgetting to handle division by zero when calculating percentages, which causes runtime errors.
- Not grouping ages into ranges when the question asks for age groups rather than individual ages.
Sample answer
I'd use conditional aggregation with CASE statements to break down time by activity type.
The query would be: SELECT age_group, SUM(CASE WHEN activity_type = 'send' THEN time_spent ELSE 0 END) as sending_time, SUM(CASE WHEN activity_type = 'open' THEN time_spent ELSE 0 END) as opening_time, ROUND(SUM(CASE WHEN activity_type = 'send' THEN time_spent ELSE 0 END) * 100.0 / NULLIF(SUM(time_spent), 0), 2) as sending_percentage FROM user_activities ua JOIN users u ON ua.user_id = u.user_id GROUP BY age_group.
I'm using CASE within SUM to conditionally aggregate time spent on each activity type, then calculating the percentage of time spent sending. NULLIF prevents division by zero errors if a user has no recorded activity time.
How to level up
- Consider whether age groups should be defined in the query using CASE or pre-calculated in the users table.
- Add validation to ensure sending_time + opening_time equals total_time as a data quality check.
- Think about whether to exclude users with very low total activity time from percentage calculations.
Follow-up questions to expect
- How would you modify this to show daily trends over the past month?
- What if we wanted to include other activity types like 'viewing stories' in the analysis?
- How would you handle users who have activity records but no age data?
Tweets' Rolling Averages: 3-day rolling avg of tweets per user
What they're really asking
This tests advanced window functions with frame specifications using ROWS BETWEEN. The interviewer wants to see if you understand how to define custom window frames for rolling calculations and handle edge cases at data boundaries.
How you'll be scored
Attempts to use simple GROUP BY or gets the window frame syntax wrong, not understanding rolling calculations.
Correctly uses window function with ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW or similar frame.
Proper rolling window syntax plus discusses handling of edge cases like users with less than 3 days of data and explains why this frame specification makes sense for business requirements.
How to structure your answer
- Use window function with proper PARTITION BY user and ORDER BY date.
- Define window frame with ROWS BETWEEN for exactly 3 days.
- Handle edge cases for users with insufficient data.
- Calculate running average using appropriate frame bounds.
- Consider performance implications of window frame calculations.
Key points to hit
- ROWS BETWEEN 2 PRECEDING AND CURRENT ROW creates a 3-day window (current day plus 2 previous)
- PARTITION BY user_id ensures rolling average is calculated separately for each user.
- ORDER BY tweet_date is crucial for proper chronological window framing.
- Users with fewer than 3 days will have averages based on available data, which may be intended behavior.
Common mistakes
- Using RANGE BETWEEN instead of ROWS BETWEEN, which behaves differently with duplicate dates.
- Forgetting that the first few rows for each user will have averages based on fewer than 3 days of data.
Sample answer
I'd use a window function with a custom frame to calculate the rolling average. The query would be: SELECT user_id, tweet_date, daily_tweets, AVG(daily_tweets) OVER (PARTITION BY user_id ORDER BY tweet_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as rolling_3day_avg FROM user_tweet_counts ORDER BY user_id, tweet_date.
The key here is ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, which creates a 3-day window including today and the previous 2 days. This gives each user their own rolling average that updates as we move through their timeline.
For the first couple days of each user's data, the average will be based on fewer than 3 days, which is usually the desired behavior for rolling metrics.
How to level up
- Consider whether business wants exactly 3 days of data required or if partial windows are acceptable for new users.
- Discuss performance implications of window functions on large time-series datasets and potential indexing strategies.
- Think about handling gaps in dates and whether missing days should affect the rolling calculation.
Follow-up questions to expect
- How would you modify this if we wanted to exclude the current day from the rolling average?
- What if we wanted a rolling average that requires exactly 3 days of data, showing null otherwise?
- How would you optimize this query for a table with millions of users and daily data over several years?
Highest-Grossing Items: top 2 products by revenue per category
What they're really asking
This tests window functions for ranking within partitions and aggregation logic. The interviewer wants to see if you can combine revenue calculations with proper ranking and handle ties between products appropriately.
How you'll be scored
Uses basic GROUP BY without proper ranking or gets the revenue calculation wrong, missing the per-category requirement.
Correctly calculates revenue by product and uses RANK() or ROW_NUMBER() partitioned by category to get top 2.
Proper ranking solution plus explains choice between RANK() vs DENSE_RANK() vs ROW_NUMBER() for handling tied revenue amounts and discusses index strategy for performance.
How to structure your answer
- Calculate total revenue per product (quantity * price typically)
- Use window function to rank products within each category.
- Choose appropriate ranking function based on tie-handling requirements.
- Filter to top 2 ranks per category.
- Consider performance optimization for large product catalogs.
Key points to hit
- Revenue calculation typically involves SUM(quantity * price) or similar aggregation grouped by product.
- RANK() OVER (PARTITION BY category ORDER BY revenue DESC) ranks products within each category.
- Choice between RANK(), DENSE_RANK(), or ROW_NUMBER() affects how tied revenues are handled.
- Filter with WHERE rank <= 2 to get top 2 products per category, accounting for potential ties.
Common mistakes
- Not partitioning by category, which would give overall top products instead of per-category top products.
- Using the wrong ranking function for ties without considering if business wants exactly 2 products or up to 2 revenue levels.
Sample answer
I'd calculate revenue per product first, then use a ranking window function within each category. The query would be: WITH product_revenue AS (SELECT product_id, category_id, SUM(quantity * unit_price) as total_revenue FROM sales GROUP BY product_id, category_id), ranked_products AS (SELECT product_id, category_id, total_revenue, RANK() OVER (PARTITION BY category_id ORDER BY total_revenue DESC) as revenue_rank FROM product_revenue) SELECT product_id, category_id, total_revenue FROM ranked_products WHERE revenue_rank <= 2. I'm using RANK() because if two products have the same revenue, they should both be considered tied for that position. This means some categories might return more than 2 products if there are ties, which is usually what business stakeholders want to see.
How to level up
- Discuss whether to use RANK() vs ROW_NUMBER() based on business requirements for handling tied revenue amounts.
- Consider joining back to product table to include product names and other descriptive fields.
- Think about time period filtering if this analysis should be for specific date ranges rather than all-time revenue.
Follow-up questions to expect
- How would you modify this to ensure exactly 2 products per category, even when there are ties?
- What if we wanted to include the percentage of category revenue each top product represents?
- How would you extend this to show month-over-month changes in the top products per category?
Top Three Salaries: top 3 earners per department
What they're really asking
This tests window function mastery and partitioning logic. The interviewer wants to see if you understand how DENSE_RANK handles ties correctly and can partition data appropriately to get top N within groups.
How you'll be scored
Uses basic GROUP BY or RANK instead of DENSE_RANK, creating incorrect results when salary ties exist.
Correct DENSE_RANK query but doesn't explain why DENSE_RANK over RANK or ROW_NUMBER.
Correct query with clear explanation of DENSE_RANK behavior with ties and discusses performance implications of window functions.
How to structure your answer
- Choose DENSE_RANK to handle salary ties properly.
- Partition by department to rank within each group.
- Order by salary descending within partitions.
- Filter results where rank <= 3.
- Consider indexing strategy for performance.
Key points to hit
- DENSE_RANK handles ties by giving the same rank to equal values without gaps in subsequent ranks.
- PARTITION BY creates separate ranking windows for each department.
- Window functions require ORDER BY within the OVER clause to define ranking criteria.
- Filtering window function results requires a subquery or CTE since you can't use WHERE with window functions directly.
Common mistakes
- Using RANK instead of DENSE_RANK creates rank gaps after ties, potentially showing fewer than 3 employees.
- Forgetting PARTITION BY ranks across all departments instead of within each department.
Sample answer
I'd use DENSE_RANK with PARTITION BY to solve this. SELECT employee_name, department, salary FROM (SELECT employee_name, department, salary, DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) as rank FROM employees) ranked WHERE rank <= 3. The key is DENSE_RANK handles ties correctly - if two people have the same salary, they both get rank 2, and the next person gets rank 3, not rank 4. This ensures we always get exactly 3 salary levels per department. For performance, I'd want an index on (department, salary DESC) to support the partitioning and ordering.
How to level up
- Discuss the query execution plan - window functions can be expensive on large datasets without proper indexing.
- Mention that DENSE_RANK vs RANK vs ROW_NUMBER choice depends on business requirements for handling ties.
- Consider whether the business wants exactly 3 people or 3 salary levels when ties exist.
Follow-up questions to expect
- What if we wanted the top 3 employees total across all departments instead of per department?
- How would you optimize this query for a table with millions of employees?
- What's the difference between using DENSE_RANK vs ROW_NUMBER for this problem?
Signup Activation Rate: percentage of signups that activated
What they're really asking
This tests LEFT JOIN understanding and conditional aggregation skills. The interviewer wants to see if you can preserve all signups while calculating percentages correctly, avoiding the pitfall of only counting activated users.
How you'll be scored
Uses INNER JOIN, which excludes non-activated signups and gives incorrect activation rates.
Correct LEFT JOIN with basic COUNT but doesn't explain why LEFT JOIN is crucial for accurate percentages.
Correct query with clear explanation of LEFT JOIN necessity and demonstrates understanding of NULL handling in aggregation.
How to structure your answer
- Use LEFT JOIN to preserve all signups.
- Apply conditional aggregation to count activated users.
- Calculate percentage using total signups as denominator.
- Handle NULL values from unmatched activations.
- Consider time window constraints if relevant.
Key points to hit
- LEFT JOIN ensures all signups are included in the denominator, even those without activations.
- COUNT with conditions or CASE statements counts only non-NULL matching records.
- The activation rate formula needs total signups as the base, not just activated signups.
- Percentage calculations should multiply by 100.0 to avoid integer division truncation.
Common mistakes
- Using INNER JOIN excludes non-activated signups, inflating the activation rate to 100%.
- Using COUNT(*) on the joined table double-counts signups and gives incorrect percentages.
Sample answer
I need to use LEFT JOIN to get accurate activation rates. SELECT (COUNT(a.user_id) * 100.0 / COUNT(s.user_id)) as activation_rate FROM signups s LEFT JOIN activations a ON s.user_id = a.user_id.
The LEFT JOIN is crucial because it preserves all signups in the result set - users who signed up but never activated will have NULL activation records. COUNT(a.user_id) only counts non-NULL values, so it gives me activated users, while COUNT(s.user_id) gives me all signups.
If I used INNER JOIN, I'd only see users who activated, making the rate artificially 100%.
How to level up
- Consider time window logic - should activations within 30 days of signup count, or any activation ever?
- Discuss whether the business wants activation rate by signup date or by time period.
- Mention potential issues with duplicate activations and how DISTINCT might be needed.
Follow-up questions to expect
- How would you modify this to show activation rates by signup month?
- What if users can activate multiple times - how would that affect your query?
- How would you add a time constraint so only activations within 7 days of signup count?
Spotify Streaming History: identify songs with increasing play counts
What they're really asking
This tests LAG window function knowledge and trend analysis logic. The interviewer wants to see if you can compare current values with previous values to detect patterns over time series data.
How you'll be scored
Attempts self-join or subquery approach that's complex and potentially incorrect for time series analysis.
Correct LAG usage but doesn't explain ordering requirements or handle edge cases like first record.
Correct LAG implementation with proper ordering, explains NULL handling for first records, and discusses performance considerations for large time series datasets.
How to structure your answer
- Use LAG to access previous play count value.
- Order by timestamp within each song partition.
- Compare current play count with lagged value.
- Filter for records where current > previous.
- Handle NULL values from LAG on first records.
Key points to hit
- LAG(play_count, 1) accesses the previous row's value within the ordered partition.
- PARTITION BY song_id ensures comparisons happen within each song's history, not across songs.
- ORDER BY timestamp is critical - LAG depends on row order to determine 'previous'
- LAG returns NULL for the first record in each partition since there's no previous value.
Common mistakes
- Forgetting PARTITION BY song_id compares play counts across different songs incorrectly.
- Not handling NULL values from LAG properly, which can cause comparison failures.
Sample answer
I'll use LAG to compare each play count with the previous one. SELECT song_id, timestamp, play_count FROM (SELECT song_id, timestamp, play_count, LAG(play_count, 1) OVER (PARTITION BY song_id ORDER BY timestamp) as prev_play_count FROM streaming_history) WITH prev WHERE play_count > prev_play_count. The LAG function looks back one row within each song's timeline, ordered by timestamp.
I partition by song_id so we're comparing within each song's history, not across different songs. The first record for each song will have NULL for prev_play_count, which naturally gets filtered out since NULL comparisons return false.
How to level up
- Consider using LEAD instead of LAG if you want to identify songs about to trend upward based on current patterns.
- For large datasets, ensure there's a compound index on (song_id, timestamp) to support the partitioning and ordering.
- Think about whether you want consecutive increases or just any increase from the previous measurement.
Follow-up questions to expect
- How would you modify this to find songs with three consecutive increases in play count?
- What if you wanted to calculate the percentage increase, not just identify increases?
- How would you handle cases where play counts might temporarily decrease due to data corrections?
Supercloud Customer: customers who bought from every product category
What they're really asking
This tests relational division concept and completeness checking. The interviewer wants to see if you understand how to verify that a customer has records matching ALL items in another set, not just some.
How you'll be scored
Uses simple GROUP BY without ensuring the customer bought from ALL categories, missing the completeness requirement.
Correct approach using HAVING COUNT = total categories but doesn't explain the relational division concept.
Correct query with clear explanation of why COUNT must equal total categories and demonstrates understanding of the mathematical completeness check.
How to structure your answer
- Count distinct categories per customer using GROUP BY.
- Count total available categories separately.
- Use HAVING to filter customers where counts match.
- Ensure DISTINCT is used to avoid double-counting.
- Consider performance implications of the approach.
Key points to hit
- HAVING COUNT(DISTINCT category) ensures we count each category only once per customer.
- The count must equal the total number of categories available, not just a high number.
- This is a relational division problem - finding entities that relate to ALL members of another set.
- GROUP BY customer creates one row per customer for the completeness check.
Common mistakes
- Using COUNT without DISTINCT double-counts categories if a customer bought multiple items from the same category.
- Hardcoding the total category count instead of calculating it dynamically, making the query brittle.
Sample answer
This is a relational division problem - I need customers who bought from every category. SELECT customer_id FROM purchases GROUP BY customer_id HAVING COUNT(DISTINCT category) = (SELECT COUNT(DISTINCT category) FROM products). The key insight is that COUNT(DISTINCT category) per customer must equal the total number of categories.
If there are 5 categories total, only customers with purchases from all 5 categories will have COUNT = 5. The DISTINCT is crucial because a customer might buy multiple products from the same category, and I don't want to double-count categories.
How to level up
- Consider using EXISTS with a NOT EXISTS subquery for better performance on large datasets with many categories.
- Think about whether the business rule requires active categories only or includes discontinued ones.
- For very large datasets, consider whether an index on (customer_id, category) would improve GROUP BY performance.
Follow-up questions to expect
- How would you modify this to find customers who bought from at least 80% of categories?
- What if you wanted to include the customer names and the count of categories they bought from?
- How would you solve this if you also needed to ensure minimum purchase amounts per category?
FAANG Stock Min-Max: min and max open prices per month
What they're really asking
This tests date manipulation and aggregation by time periods. The interviewer wants to see if you can group time series data by month and apply aggregate functions correctly to find extremes within each period.
How you'll be scored
Attempts to group by individual dates or uses incorrect date functions, failing to aggregate by month properly.
Correct date truncation and MIN/MAX aggregation but doesn't explain date function choice or formatting.
Correct query with explanation of date truncation approach, discusses timezone considerations, and mentions indexing strategy for time series data.
How to structure your answer
- Use date truncation to group by month-year.
- Apply MIN and MAX aggregation to open_price.
- Include stock symbol in grouping if multiple stocks.
- Format dates appropriately for readability.
- Consider timezone and trading day implications.
Key points to hit
- DATE_TRUNC or similar function groups all days within a month into the same bucket.
- MIN and MAX functions automatically handle finding extremes within each month group.
- GROUP BY must include the truncated date and any other dimensions like stock symbol.
- Date functions vary by database system - PostgreSQL uses DATE_TRUNC, MySQL uses DATE_FORMAT.
Common mistakes
- Grouping by full date instead of truncated month gives daily min/max instead of monthly.
- Forgetting to include stock symbol in GROUP BY when analyzing multiple stocks mixes results across companies.
Sample answer
I'll use date truncation to group by month and aggregate the prices. SELECT DATE_TRUNC('month', trade_date) as month, stock_symbol, MIN(open_price) as min_open, MAX(open_price) as max_open FROM stock_prices WHERE stock_symbol IN ('AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META') GROUP BY DATE_TRUNC('month', trade_date), stock_symbol ORDER BY month, stock_symbol.
The DATE_TRUNC function converts all dates within a month to the first day of that month, so all January 2024 dates become 2024-01-01. This creates monthly buckets for the MIN and MAX aggregation. I include stock_symbol in the GROUP BY so each company gets separate monthly calculations.
How to level up
- Consider whether you need trading days only or calendar months - weekends and holidays might affect the analysis.
- For large time series datasets, a compound index on (stock_symbol, trade_date) optimizes both filtering and grouping.
- Think about whether month-end vs month-start date representation affects downstream analysis or reporting.
Follow-up questions to expect
- How would you modify this to show the specific dates when the monthly min and max occurred?
- What if you wanted to calculate the monthly volatility (max - min) and rank months by volatility?
- How would you handle stock splits or dividend adjustments that affect price comparisons?
Best-Selling Product: identify top product by total revenue
What they're really asking
This tests aggregation logic and ranking techniques for sql questions for an interview. The interviewer wants to see if you can correctly group data, sum revenue, and identify the top performer without over-engineering the solution.
How you'll be scored
Uses a subquery or ranking window function when a simple GROUP BY with ORDER BY would suffice, or gets the aggregation logic wrong.
Correctly groups by product and sums revenue with proper ordering to get the top result.
Chooses the most efficient approach (GROUP BY with LIMIT vs window functions), explains why, and mentions how to handle ties.
How to structure your answer
- Clarify what constitutes 'revenue' (price * quantity or just sum of sales)
- Group data by product to aggregate sales.
- Calculate total revenue per product using SUM.
- Order by revenue descending and limit to top result.
- Consider how to handle ties between products.
Key points to hit
- GROUP BY is essential when aggregating data per product to avoid syntax errors.
- ORDER BY DESC with LIMIT 1 is more efficient than window functions for simple top-N queries.
- Revenue calculation depends on schema structure (single price column vs price * quantity)
- Handle ties explicitly if business rules require showing all products with maximum revenue.
Common mistakes
- Forgetting GROUP BY when using aggregate functions like SUM, which causes SQL errors.
- Using complex window functions like RANK() when simple ORDER BY with LIMIT accomplishes the same result more efficiently.
Sample answer
I'd start with SELECT product_name, SUM(price * quantity) as total_revenue FROM sales GROUP BY product_name ORDER BY total_revenue DESC LIMIT 1. This groups all sales by product, calculates the total revenue for each, and returns the highest one.
The key is making sure the revenue calculation matches your schema - if you already have a revenue column, you'd just SUM(revenue) instead. I'm using LIMIT 1 here assuming we want one product, but if there could be ties, we'd need to use RANK() in a window function instead.
How to level up
- Consider using WITH TIES in databases that support it to handle products with identical top revenue.
- For large datasets, ensure there's an index on the grouping column (product_name) to speed up aggregation.
- If this query runs frequently, consider materializing the results in a summary table with periodic updates.
Follow-up questions to expect
- How would you modify this to show the top 3 products instead of just the top 1?
- What if we wanted to see the best-selling product by month for the last year?
- How would you handle this query if the sales table had millions of rows?
User Shopping Sprees: find users with 3+ consecutive purchase days
What they're really asking
This tests window functions and consecutive sequence detection for sql query questions for interview. The interviewer wants to see if you understand LAG/LEAD functions and can identify patterns across ordered rows.
How you'll be scored
Attempts to solve with self-joins or doesn't understand how to detect consecutive dates properly.
Uses LAG or LEAD to compare adjacent dates but may miss the logic for detecting exactly 3+ consecutive days.
Implements a robust solution using window functions with proper grouping and consecutive day detection, explaining the row numbering technique.
How to structure your answer
- Use window functions to compare each purchase date with previous dates.
- Create groups of consecutive purchase days using date arithmetic.
- Count consecutive days per group to identify streaks.
- Filter for groups with 3 or more consecutive days.
- Return users who have qualifying streaks.
Key points to hit
- LAG function compares current row's date with the previous purchase date to detect gaps.
- Consecutive detection requires grouping by the difference between date and row number.
- Window functions need proper partitioning by user_id to avoid mixing users' data.
- Date arithmetic varies by database (DATE_ADD in MySQL, INTERVAL in PostgreSQL)
Common mistakes
- Forgetting to partition window functions by user_id, which would mix different users' purchase patterns.
- Incorrectly handling date gaps or not accounting for the fact that consecutive means exactly adjacent days.
Sample answer
I'd use a window function approach with LAG to detect consecutive sequences. First, I'd create a CTE that uses ROW_NUMBER() and LAG to identify where consecutive sequences break. Something like WITH consecutive_groups AS (SELECT user_id, purchase_date, purchase_date - INTERVAL ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY purchase_date) DAY as group_id FROM purchases).
Then I'd group by user_id and group_id, count the days in each group, and filter for counts >= 3. The key insight is that consecutive dates will have the same group_id when you subtract the row number.
How to level up
- Consider using DENSE_RANK instead of ROW_NUMBER if users can have multiple purchases on the same day.
- For performance on large datasets, ensure indexes exist on (user_id, purchase_date) for the window function ordering.
- Test edge cases like users with purchases on consecutive days spanning month boundaries.
Follow-up questions to expect
- How would you modify this to find the longest consecutive purchase streak per user?
- What if we wanted to allow one gap day and still consider it a 'spree' (like 3 purchases in 4 days)?
- How would this query perform differently if we had the purchase data partitioned by month?
Histogram of Users and Purchases: distribution of purchase counts
What they're really asking
This tests understanding of histogram creation and frequency distribution analysis for interview questions sql. The interviewer wants to see if you can count occurrences of counts using nested aggregation logic.
How you'll be scored
Confuses the two-level aggregation required or tries to solve with a single GROUP BY without understanding the histogram concept.
Correctly uses a subquery to first count purchases per user, then groups those counts to create the distribution.
Implements a clean two-step solution with proper subquery structure and explains why this requires nested aggregation rather than window functions.
How to structure your answer
- First, count total purchases per user using GROUP BY user_id.
- Then, treat those counts as data to be grouped and counted again.
- Use subquery or CTE to separate the two aggregation levels.
- Order results to show the distribution clearly.
- Verify the logic handles users with zero purchases if needed.
Key points to hit
- Histogram queries require two levels of aggregation that cannot be done in a single GROUP BY.
- The inner query groups by user_id to get purchase counts, the outer query groups by those counts.
- Subquery approach is cleaner than window functions for this type of frequency distribution.
- Consider whether users with zero purchases should be included in the histogram.
Common mistakes
- Attempting to solve with a single GROUP BY, which cannot create the two-level aggregation needed for histograms.
- Confusing the COUNT in the subquery (purchases per user) with the COUNT in the outer query (users per purchase count)
Sample answer
This is a classic histogram problem requiring two levels of aggregation. I'd write SELECT purchase_count, COUNT(*) as user_count FROM (SELECT user_id, COUNT(*) as purchase_count FROM purchases GROUP BY user_id) grouped_users GROUP BY purchase_count ORDER BY purchase_count.
The inner query counts how many purchases each user made, then the outer query counts how many users fall into each purchase count bucket. So if 5 users made exactly 3 purchases each, we'd see purchase_count=3, user_count=5 in our results.
How to level up
- Consider using WITH clause for readability when the subquery logic becomes complex.
- For users with zero purchases, you'd need a LEFT JOIN with the users table if that's required in the histogram.
- This pattern works for any frequency distribution - just change what you're counting in the inner query.
Follow-up questions to expect
- How would you include users who made zero purchases in this histogram?
- What if we wanted to create buckets (0-5 purchases, 6-10 purchases) instead of exact counts?
- How would you visualize this data if you were building a dashboard?
Odd and Even Measurements: separate odd vs even numbered measurements per day
What they're really asking
This tests window functions with conditional logic and row numbering for sql queries questions for interview. The interviewer wants to see if you can separate data streams based on calculated row positions within groups.
How you'll be scored
Doesn't understand how to use ROW_NUMBER() within date groups or confuses the odd/even logic.
Correctly uses ROW_NUMBER() partitioned by date and applies modulo logic to separate odd/even measurements.
Implements efficient window function solution with proper partitioning, explains the modulo operation clearly, and discusses how to handle the results.
How to structure your answer
- Use ROW_NUMBER() window function partitioned by measurement date.
- Apply modulo operation to determine odd vs even row numbers.
- Use conditional aggregation or CASE statements to separate the values.
- Group by date to get one row per day with both odd and even results.
- Consider how to handle days with only odd or even measurements.
Key points to hit
- ROW_NUMBER() must be partitioned by date and ordered by measurement time or ID for consistent numbering.
- Modulo operation (% 2) determines odd (remainder 1) vs even (remainder 0) positions.
- Conditional aggregation with CASE inside SUM or AVG functions separates the two streams.
- Window functions are more efficient than self-joins for this type of positional logic.
Common mistakes
- Forgetting to partition ROW_NUMBER() by date, which would number measurements across all days instead of restarting each day.
- Confusing modulo logic - ROW_NUMBER() % 2 = 1 for odd positions, = 0 for even positions.
Sample answer
I'd use ROW_NUMBER() with conditional aggregation to solve this.
The query would be SELECT measurement_date, AVG(CASE WHEN ROW_NUMBER() OVER (PARTITION BY measurement_date ORDER BY measurement_time) % 2 = 1 THEN measurement_value END) as odd_avg, AVG(CASE WHEN ROW_NUMBER() OVER (PARTITION BY measurement_date ORDER BY measurement_time) % 2 = 0 THEN measurement_value END) as even_avg FROM measurements GROUP BY measurement_date.
The ROW_NUMBER() restarts at 1 for each date, the modulo operation identifies odd vs even positions, and the CASE statements inside AVG only include the relevant measurements for each calculation.
How to level up
- Consider using NTILE(2) if you want to split measurements into two equal groups rather than strict odd/even positioning.
- For large datasets, ensure there's an index on (measurement_date, measurement_time) to optimize the window function ordering.
- Add NULL handling logic if some days might have no odd or even measurements.
Follow-up questions to expect
- How would you modify this to get the first and last measurement of each day instead?
- What if we wanted to compare every 3rd measurement instead of alternating odd/even?
- How would you handle this if measurements could have the same timestamp?
Swapped Food Delivery: detect swapped delivery orders
What they're really asking
This tests self-join logic and pair detection algorithms for interview questions from sql. The interviewer wants to see if you can identify rows where specific column values are swapped between related records.
How you'll be scored
Attempts basic joins without understanding the swap detection logic or how to avoid duplicate pair reporting.
Correctly identifies swapped pairs using self-join with proper swap conditions but may return duplicates.
Implements clean self-join with swap detection, eliminates duplicate pairs, and explains the join conditions clearly with consideration for edge cases.
How to structure your answer
- Self-join the delivery table to compare each order with all other orders.
- Set up join conditions where delivery addresses are swapped between orders.
- Add conditions to avoid duplicate pairs and self-matches.
- Filter by relevant time windows if orders must be from same period.
- Consider additional validation like same delivery driver or time proximity.
Key points to hit
- Self-join requires aliasing the same table twice (t1 and t2) to compare rows with each other.
- Swap detection means t1.customer_address = t2.delivery_address AND t1.delivery_address = t2.customer_address.
- Use t1.order_id < t2.order_id to eliminate duplicate pairs and self-matches.
- Consider time windows or other business rules to make swap detection more realistic.
Common mistakes
- Forgetting the condition t1.order_id < t2.order_id, which results in each swapped pair appearing twice in results.
- Not handling the case where an order might match multiple other orders if addresses are reused.
Sample answer
I'd use a self-join to compare each delivery order with every other order looking for address swaps. The query would be SELECT t1.order_id as order1, t2.order_id as order2, t1.customer_address, t1.delivery_address FROM deliveries t1 JOIN deliveries t2 ON t1.customer_address = t2.delivery_address AND t1.delivery_address = t2.customer_address AND t1.order_id < t2.order_id. This finds pairs where what should have been delivered to customer A went to customer B and vice versa. The order_id comparison prevents seeing the same pair twice and avoids matching an order with itself.
How to level up
- Add time-based constraints like ABS(t1.delivery_time - t2.delivery_time) < 60 minutes to find realistic swaps.
- Consider indexing on (customer_address, delivery_address) for better join performance on large delivery tables.
- Include driver_id in the join conditions since swaps likely happen with the same driver.
Follow-up questions to expect
- How would you modify this to find potential swaps that happened within the same hour?
- What if we wanted to detect partial swaps where only the street address was wrong but the city was correct?
- How would you report not just the swapped pairs but also suggest the correction needed?
Compressed Mode: find statistical mode from frequency distribution
What they're really asking
This tests advanced aggregation skills and statistical thinking. The interviewer wants to see if you can identify the most frequent value from a frequency table using SQL, which requires understanding GROUP BY with HAVING and tie-handling logic.
How you'll be scored
Uses basic MAX() without understanding that multiple values can have the same highest frequency, missing tie cases entirely.
Correctly finds the mode using subqueries or window functions but doesn't address what happens when multiple values tie for most frequent.
Provides a complete solution that handles ties properly, explains the approach clearly, and discusses performance implications of different methods.
How to structure your answer
- Clarify if ties should return all modes or pick one arbitrarily.
- Write query to find the maximum frequency first.
- Use that result to filter back to values with that frequency.
- Consider window function alternative for better performance.
- Test edge cases like all values having same frequency.
Key points to hit
- The mode requires finding ALL values that appear with maximum frequency, not just picking one winner.
- Window functions like RANK() OVER (ORDER BY frequency DESC) often perform better than correlated subqueries for this pattern.
- Always consider what happens when every value appears exactly once (no true mode exists)
- Dense_rank vs rank matters when there are frequency ties at non-mode levels.
Common mistakes
- Using LIMIT 1 or TOP 1 without handling the case where multiple values tie for highest frequency.
- Writing a correlated subquery when a window function would be more efficient and readable.
Sample answer
I'd start by finding the maximum frequency, then filter back to get all values with that frequency. Here's my approach: WITH freq_counts AS (SELECT value, COUNT(*) as frequency FROM data GROUP BY value), max_freq AS (SELECT MAX(frequency) as max_count FROM freq_counts) SELECT value FROM freq_counts WHERE frequency = (SELECT max_count FROM max_freq).
This handles ties properly by returning all modes. I could also use RANK() OVER (ORDER BY COUNT(*) DESC) = 1 which might perform better on large datasets since it avoids the separate subquery.
How to level up
- Consider using DENSE_RANK() instead of RANK() if you need consistent numbering when frequencies have gaps.
- For very large datasets, materializing the frequency counts first can significantly improve performance.
- Think about whether the business actually wants all ties returned or has a preference rule for breaking ties.
Follow-up questions to expect
- How would you modify this to find the top 3 most frequent values instead?
- What if the original data has NULLs - should they be included in mode calculation?
- How would you optimize this query if the source table had 100 million rows?
Window Function Deep Dive (11)
Summarize total sales revenue per product line using SUM() OVER(PARTITION BY)
What they're really asking
This tests window function comprehension and partitioning logic. The interviewer wants to see if you understand how PARTITION BY creates separate calculation groups and can aggregate across the entire partition efficiently.
How you'll be scored
Confuses window functions with GROUP BY or writes incorrect PARTITION BY syntax that doesn't compile.
Correctly uses SUM() OVER(PARTITION BY product_line) but explanation lacks clarity about how partitioning works.
Writes correct window function, explains partition behavior clearly, and discusses when to use window functions versus GROUP BY for business requirements.
How to structure your answer
- Identify that each row needs both individual sale info and total product line revenue.
- Write SUM(revenue) OVER(PARTITION BY product_line) to get totals.
- Explain that this adds total as a column without collapsing rows.
- Compare to GROUP BY approach and explain the difference.
- Consider performance implications with large datasets.
Key points to hit
- PARTITION BY creates separate calculation windows for each product line while keeping all original rows intact.
- Window functions let you show both detail-level and summary-level data in the same result set without joins.
- Unlike GROUP BY, window functions don't reduce the number of rows in your output.
- The partition boundary resets the calculation, so each product line gets its own independent sum.
Common mistakes
- Mixing window functions with GROUP BY in the same query level without understanding the execution order.
- Forgetting that window functions run after WHERE but before ORDER BY in query execution.
Sample answer
I'd use SELECT *, SUM(revenue) OVER(PARTITION BY product_line) as total_product_line_revenue FROM sales. This creates a separate partition for each product line and calculates the sum within that partition. Every row for Electronics would show the total Electronics revenue, every Clothing row would show total Clothing revenue, and so on.
The key advantage over GROUP BY is that I keep all the individual sale details while adding the summary information. This is perfect for reports where you need both transaction-level detail and category totals on the same row.
How to level up
- Add ORDER BY within the OVER clause if you need the partition processed in a specific sequence, even though it doesn't change SUM results.
- Consider performance: window functions can be expensive on very large partitions, so indexing on the partition column helps.
- You can partition by multiple columns using PARTITION BY product_line, region for more granular groupings.
Follow-up questions to expect
- How would you also include what percentage each individual sale represents of its product line total?
- What happens if you add ORDER BY within the OVER clause for a SUM function?
- How would you modify this to show rolling totals within each product line by date?
Calculate a running total using SUM() with OVER() and ORDER BY
What they're really asking
This tests understanding of window function frames and cumulative calculations. The interviewer wants to see if you know how ORDER BY creates a running calculation frame and can explain the difference between cumulative and total aggregation.
How you'll be scored
Omits ORDER BY in the window function or doesn't understand that ORDER BY creates a cumulative frame rather than just sorting output.
Correctly writes SUM() OVER(ORDER BY date) but explanation of how the running frame works is unclear or incomplete.
Provides correct syntax, clearly explains how the frame grows with each row, and discusses frame specifications like ROWS vs RANGE for optimization.
How to structure your answer
- Explain that ORDER BY in window function creates cumulative behavior.
- Write SUM(amount) OVER(ORDER BY date) for basic running total.
- Describe how each row includes all previous rows in calculation.
- Mention frame specification options for fine control.
- Address handling of duplicate dates or NULL values.
Key points to hit
- ORDER BY inside OVER() creates a cumulative frame that grows from first row to current row by default.
- Each row's running total includes its own value plus all previous values in the ordered sequence.
- Without ORDER BY, window functions calculate over the entire partition, but with ORDER BY they calculate incrementally.
- Frame specifications like ROWS UNBOUNDED PRECEDING make the cumulative behavior explicit and can improve clarity.
Common mistakes
- Forgetting ORDER BY in the OVER clause, which gives total sum on every row instead of running total.
- Not considering how duplicate values in ORDER BY column affect the frame boundaries.
Sample answer
I'd write SELECT date, amount, SUM(amount) OVER(ORDER BY date) as running_total FROM transactions. The ORDER BY inside the OVER clause is crucial because it tells SQL to calculate cumulatively. For the first row, running_total equals just that row's amount. For the second row, it's the sum of first and second rows.
For the third row, it's the sum of first, second, and third rows, and so on. This creates the running total effect. If I omitted ORDER BY, every row would show the grand total of all transactions instead of the progressive cumulative sum.
How to level up
- Use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to make the frame specification explicit and potentially improve performance.
- Consider partitioning as well: PARTITION BY customer_id ORDER BY date gives separate running totals per customer.
- Be aware that RANGE vs ROWS matters when your ORDER BY column has duplicates - RANGE includes ties, ROWS processes sequentially.
Follow-up questions to expect
- How would you calculate a running total that resets to zero each month?
- What's the difference between ROWS and RANGE in the frame specification for running totals?
- How would you create a running total that excludes the current row (only previous rows)?
Use NTILE() to divide rows into N equal groups (quartiles, deciles)
What they're really asking
This tests understanding of statistical distribution functions and data segmentation. The interviewer wants to see if you can use NTILE() to divide datasets into equal-sized buckets and understand the edge cases when row counts don't divide evenly.
How you'll be scored
Confuses NTILE with RANK or ROW_NUMBER, or doesn't understand that NTILE creates equal-sized groups rather than equal-value ranges.
Correctly uses NTILE(4) for quartiles but doesn't explain how ties are handled or what happens with uneven group sizes.
Uses NTILE correctly, explains the equal-sizing behavior clearly, discusses tie-handling, and mentions practical applications like performance analysis.
How to structure your answer
- Clarify that NTILE creates equal-sized groups, not equal-value ranges.
- Write NTILE(n) OVER(ORDER BY column) for the desired grouping.
- Explain how rows are distributed when total doesn't divide evenly by N.
- Describe tie-handling behavior within the same ORDER BY values.
- Give practical examples of when you'd use different N values.
Key points to hit
- NTILE(4) creates exactly 4 groups with roughly equal row counts, not groups based on value ranges.
- When row count doesn't divide evenly, earlier groups get the extra rows (if 100 rows into 3 groups: 34, 33, 33)
- ORDER BY is required because NTILE needs to know how to sequence rows before dividing them into buckets.
- Ties in the ORDER BY column get assigned to buckets sequentially, which might seem arbitrary but ensures equal sizing.
Common mistakes
- Thinking NTILE creates value-based ranges rather than count-based buckets (confusing with percentile ranges)
- Expecting tied values to always end up in the same NTILE group, when they're distributed to maintain equal bucket sizes.
Sample answer
I'd use SELECT *, NTILE(4) OVER(ORDER BY salary) as quartile FROM employees to create quartiles. NTILE divides all rows into exactly 4 equal-sized groups based on salary ranking. If I have 1000 employees, each quartile gets exactly 250 people. The lowest-paid 250 get quartile 1, next 250 get quartile 2, and so on.
If the total doesn't divide evenly, like 1002 employees, the first two quartiles would get 251 each and the last two get 250 each. This is different from value-based percentiles because it guarantees equal group sizes regardless of salary distribution.
How to level up
- Use multiple ORDER BY columns to get more consistent tie-breaking: ORDER BY salary, employee_id ensures reproducible results.
- NTILE is perfect for A/B testing when you need exactly equal-sized control groups regardless of data distribution.
- Consider performance: NTILE requires sorting the entire dataset, so proper indexing on ORDER BY columns is crucial for large tables.
Follow-up questions to expect
- How would you create quartiles within each department rather than across the entire company?
- What's the difference between NTILE(4) and creating custom quartiles based on actual salary value ranges?
- How would you find all employees who are in the top decile of their department?
Calculate average delay between user signup and their 2nd ride
What they're really asking
This tests time-based analysis and multi-event tracking patterns. The interviewer wants to see if you can join a table to itself to find sequences of events and calculate time differences between specific user actions.
How you'll be scored
Attempts simple date arithmetic without properly identifying each user's first and second rides, or uses incorrect join conditions.
Successfully identifies signup and second ride events but uses a complex approach with multiple CTEs when window functions would be cleaner.
Uses ROW_NUMBER() or similar ranking to identify the second ride efficiently, correctly calculates date differences, and handles edge cases like users with fewer than 2 rides.
How to structure your answer
- Identify need to rank rides by date for each user to find the second one.
- Use window function to assign ride numbers within each user.
- Filter for ride_number = 2 to get only second rides.
- Join back to user signup data or include signup date in original query.
- Calculate average date difference, handling users with insufficient rides.
Key points to hit
- ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY ride_date) efficiently identifies each user's ride sequence.
- Only users with at least 2 rides should be included in the average calculation to avoid skewing results.
- Date arithmetic varies by database (DATEDIFF, DATE_PART, or simple subtraction depending on SQL dialect)
- Consider whether to measure from signup date to second ride date, or from first ride to second ride based on business requirements.
Common mistakes
- Using RANK() instead of ROW_NUMBER() when you specifically want the second occurrence, not second-ranked value by date.
- Including users with only one ride in the calculation, which would either cause errors or skew the average incorrectly.
Sample answer
I'd start with a CTE to rank each user's rides: WITH ranked_rides AS (SELECT user_id, ride_date, signup_date, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY ride_date) as ride_number FROM rides JOIN users USING(user_id)). Then I'd filter for the second ride and calculate the average: SELECT AVG(ride_date - signup_date) as avg_delay FROM ranked_rides WHERE ride_number = 2.
This approach ensures I'm only looking at users who actually had a second ride, and I'm measuring from their signup date to when that second ride occurred. The window function makes it clean and efficient compared to self-joins.
How to level up
- Consider using LEAD() or LAG() window functions if you need to compare consecutive rides within the same query result.
- Add error handling for time zones if signup and ride timestamps might be in different zones.
- Think about whether weekend/holiday delays should be excluded from business metrics about user engagement timing.
Follow-up questions to expect
- How would you modify this to find the median time to second ride instead of average?
- What if you wanted to track the delay to the second ride for each cohort of users who signed up in the same month?
- How would you handle users who signed up but never took any rides in this analysis?
Identify repeated payments at same merchant with same card within 10 minutes
What they're really asking
This tests advanced window function mastery and time-based filtering logic. The interviewer wants to see if you understand how to partition data by multiple dimensions and filter within time windows using ROWS BETWEEN or range comparisons.
How you'll be scored
Uses basic JOINs or subqueries instead of window functions, or gets the time comparison logic wrong.
Correctly uses window functions with proper partitioning and identifies duplicates within the time window.
Demonstrates efficient window function usage, handles edge cases like timezone considerations, and discusses performance implications of the chosen approach.
How to structure your answer
- Clarify the definition of 'repeated payment' (exact amount match vs any payment)
- Design the window function with PARTITION BY merchant and card.
- Use LAG or LEAD to access previous payment timestamps.
- Apply time difference filtering to find payments within 10 minutes.
- Consider indexing strategy for optimal performance.
Key points to hit
- PARTITION BY both merchant_id and card_id to group related transactions together.
- LAG function retrieves the previous payment timestamp within each partition for comparison.
- Time difference calculation should account for the specific database's date arithmetic syntax.
- ORDER BY timestamp within the window function ensures chronological comparison.
Common mistakes
- Partitioning only by card_id without considering merchant_id, which would compare payments across different merchants.
- Using DATEDIFF incorrectly or forgetting that different databases handle time arithmetic differently.
Sample answer
I'd use a window function with LAG to compare each payment to the previous one at the same merchant with the same card. The query would partition by merchant_id and card_id, ordered by payment_timestamp. Then I'd use LAG to get the previous timestamp and filter where the time difference is less than 10 minutes.
This approach is efficient because it processes each partition sequentially rather than doing expensive self-joins across the entire payments table.
How to level up
- Consider using ROWS BETWEEN 1 PRECEDING AND CURRENT ROW to explicitly define the frame if you need to check multiple previous transactions.
- Add indexes on (merchant_id, card_id, payment_timestamp) to optimize the window function performance.
- Handle timezone conversions if payments can occur across different time zones.
Follow-up questions to expect
- How would you modify this query to detect suspicious patterns like 3 or more payments within 30 minutes?
- What indexing strategy would you use to optimize this query on a table with 100 million payment records?
- How would you handle the case where you need to check for duplicate amounts as well as timing?
Explain the FRAME clause (ROWS BETWEEN) in window functions with examples
What they're really asking
This tests deep understanding of window function frame specifications and how ROWS BETWEEN controls which rows are included in calculations. The interviewer wants to see if you understand the difference between logical and physical row boundaries.
How you'll be scored
Confuses ROWS with RANGE or gives vague explanations without concrete examples showing different frame behaviors.
Correctly explains ROWS BETWEEN syntax and provides a basic example showing how the frame changes.
Demonstrates mastery by showing multiple frame types, explains performance implications, and contrasts ROWS vs RANGE behavior with specific examples.
How to structure your answer
- Define what a frame is in window function context.
- Explain ROWS BETWEEN syntax and common frame specifications.
- Show concrete examples with different frame boundaries.
- Contrast ROWS vs RANGE behavior.
- Discuss performance considerations for different frame sizes.
Key points to hit
- ROWS BETWEEN defines a physical frame based on row positions relative to the current row.
- Common patterns include UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING, and UNBOUNDED FOLLOWING.
- The frame determines which subset of the partition's rows are included in aggregate calculations.
- ROWS uses physical row positions while RANGE uses logical value ranges based on the ORDER BY expression.
Common mistakes
- Confusing ROWS BETWEEN with RANGE BETWEEN, which behaves differently when there are duplicate values in the ORDER BY column.
- Forgetting that the frame resets for each partition and moves with each row in the result set.
Sample answer
The FRAME clause controls which rows within a partition are included in window function calculations. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means for each row, include the current row plus the 2 physical rows before it.
For example, calculating a 3-day moving average of sales would use SUM(sales) OVER (ORDER BY date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW).
The key difference from RANGE is that ROWS counts physical positions, so it always includes exactly 3 rows even if dates are duplicated, while RANGE would include all rows with dates within the specified range.
How to level up
- Use ROWS when you need exact row counts for calculations like moving averages, use RANGE when you need value-based windows.
- Consider memory usage with large frames, as databases need to maintain the frame data in memory.
- Test performance with different frame sizes, as very large frames can impact query execution time significantly.
Follow-up questions to expect
- How would RANGE BETWEEN 2 PRECEDING AND CURRENT ROW behave differently if you had duplicate dates in your ORDER BY clause?
- What happens to frame boundaries at partition edges, like the first and last rows?
- Can you show an example where using the wrong frame specification would give incorrect business results?
How do you optimize queries with multiple window functions on large datasets?
What they're really asking
This tests understanding of query performance optimization specifically for window functions at scale. The interviewer wants to see if you know how window functions impact memory usage, sorting costs, and can design efficient execution strategies.
How you'll be scored
Suggests generic optimization techniques without understanding window function-specific performance characteristics.
Mentions key concepts like reducing partitions or combining window functions but lacks depth in execution strategy.
Demonstrates comprehensive understanding of window function execution plans, memory management, and provides specific techniques like function consolidation and intelligent partitioning.
How to structure your answer
- Analyze the current query structure and identify bottlenecks.
- Combine multiple window functions with the same PARTITION BY and ORDER BY.
- Optimize partitioning strategy to reduce sort operations.
- Consider pre-aggregation or materialized views for repeated calculations.
- Design appropriate indexing to support window function execution.
Key points to hit
- Multiple window functions with identical PARTITION BY and ORDER BY clauses can share the same sort operation.
- Large partitions require more memory for frame processing and can cause spill-to-disk operations.
- Indexes that match the PARTITION BY columns followed by ORDER BY columns optimize sort performance.
- Consider breaking complex window calculations into CTEs to make query plans more predictable.
Common mistakes
- Creating separate window functions with the same partitioning when they could be combined in a single window specification.
- Not considering memory limits when processing very large partitions, which can cause performance degradation.
Sample answer
For queries with multiple window functions on large datasets, I focus on three key optimizations. First, I combine window functions that share the same PARTITION BY and ORDER BY into a single window specification to avoid redundant sorting. Second, I ensure there's a composite index on the partition columns followed by the ordering columns.
Third, if the dataset is extremely large, I consider whether some window calculations can be pre-computed in smaller batches or if partitioning can be redesigned to create more evenly distributed, smaller partitions that fit better in memory.
How to level up
- Monitor query execution plans to identify when window functions cause sort spills to disk, which dramatically impacts performance.
- Use EXPLAIN ANALYZE to measure actual memory usage and compare different partitioning strategies.
- Consider columnar storage or partitioned tables aligned with your window function's PARTITION BY clause for maximum efficiency.
Follow-up questions to expect
- How would you handle a scenario where your window function partitions are extremely uneven in size?
- What would you do if the query is still too slow after these optimizations?
- How do you decide between using window functions versus pre-aggregating data in ETL processes?
Find percentage of buyers who bought AirPods directly after purchasing an iPhone
What they're really asking
This tests sequential analysis using window functions and understanding of user journey analytics. The interviewer wants to see if you can identify purchase sequences and calculate conditional percentages based on ordered events.
How you'll be scored
Uses complex self-joins instead of window functions or fails to properly identify the sequential purchase pattern.
Correctly uses LAG or LEAD to identify iPhone-to-AirPods sequences and calculates the percentage.
Efficiently identifies the sequence with window functions, handles edge cases like multiple purchases, and discusses how to define 'directly after' in business terms.
How to structure your answer
- Define what 'directly after' means in business context.
- Use LAG to identify the previous purchase for each user.
- Filter for AirPods purchases where the previous purchase was iPhone.
- Calculate percentage of iPhone buyers who made this sequence.
- Handle edge cases like multiple iPhones or AirPods purchases.
Key points to hit
- LAG function partitioned by user_id and ordered by purchase_date retrieves the previous purchase.
- The calculation requires two distinct populations: iPhone buyers and iPhone buyers who subsequently bought AirPods.
- ROW_NUMBER might be needed to handle users with multiple purchases of the same product.
- Consider time window constraints for what constitutes 'directly after'
Common mistakes
- Calculating percentage based on total AirPods buyers instead of iPhone buyers who subsequently bought AirPods.
- Not handling users who bought multiple iPhones or AirPods, which could skew the sequential analysis.
Sample answer
I'd use LAG to track each user's previous purchase, partitioned by user_id and ordered by purchase_date. Then I'd identify AirPods purchases where LAG shows the previous product was iPhone. To get the percentage, I'd count distinct users who made this iPhone-to-AirPods sequence divided by distinct users who bought iPhones.
I'd also need to clarify whether 'directly after' means the very next purchase or within a specific time window, and how to handle users who bought multiple iPhones before getting AirPods.
How to level up
- Use ROW_NUMBER to identify first-time iPhone buyers if the business logic should exclude repeat iPhone purchases.
- Consider using conditional aggregation with CASE statements to calculate both numerator and denominator in a single pass.
- Add time-based filtering if 'directly after' has business meaning like 'within 30 days'
Follow-up questions to expect
- How would you modify this to find the most common product purchased after iPhone across all product categories?
- What if we wanted to track longer sequences like iPhone โ AirPods โ Apple Watch?
- How would you handle users who returned their iPhone before buying AirPods?
Display employee salary alongside department average using window function
What they're really asking
This tests basic window function syntax and understanding of how window functions differ from GROUP BY aggregations. The interviewer wants to see if you understand that window functions preserve individual rows while adding aggregate calculations.
How you'll be scored
Uses GROUP BY which loses individual employee rows, or writes incorrect window function syntax.
Correctly uses AVG() OVER() with proper PARTITION BY clause to show both individual and department averages.
Demonstrates clean window function syntax, explains why this approach preserves row-level detail, and mentions performance considerations.
How to structure your answer
- Identify the need to preserve individual employee rows.
- Use AVG() window function with PARTITION BY department.
- Show both employee salary and department average in SELECT clause.
- Explain why window function is preferred over JOIN with subquery.
- Consider ordering for consistent results.
Key points to hit
- Window function AVG() OVER (PARTITION BY department_id) calculates average within each department.
- Unlike GROUP BY, window functions preserve individual rows while adding aggregate information.
- No JOIN required, making the query simpler and often more performant than subquery approaches.
- PARTITION BY acts like GROUP BY but doesn't collapse rows into groups.
Common mistakes
- Using GROUP BY which would eliminate individual employee rows and only show department averages.
- Forgetting PARTITION BY clause, which would calculate average across all employees instead of by department.
Sample answer
I'd write SELECT employee_name, salary, AVG(salary) OVER (PARTITION BY department_id) as dept_avg FROM employees. This window function calculates the department average for each row without collapsing the individual employee records. The PARTITION BY clause groups employees by department for the average calculation, but unlike GROUP BY, every employee row remains in the result set.
This is much cleaner than joining the employee table to a subquery that calculates department averages.
How to level up
- Add ORDER BY employee_name for consistent result ordering since window functions don't guarantee row order.
- Consider adding salary ranking or percentiles using additional window functions in the same query.
- This pattern works well for variance analysis, showing how each employee compares to their department average.
Follow-up questions to expect
- How would you extend this to show the highest paid employee in each department alongside their salary?
- What if you wanted to show both department average and company-wide average for each employee?
- How would you modify this query to exclude the employee themselves from their department average calculation?
Identify best-selling item by revenue for each month
What they're really asking
This tests window function mastery and partitioning logic. The interviewer wants to see if you can group data by time periods, aggregate revenue correctly, and rank results within partitions without losing granular detail.
How you'll be scored
Uses basic GROUP BY without window functions, missing the 'per month' requirement or failing to identify the single best-selling item.
Correct window function with RANK() or ROW_NUMBER(), proper date extraction, but lacks discussion of tie-breaking or performance considerations.
Uses appropriate ranking function, explains partitioning strategy, discusses tie-handling with DENSE_RANK vs ROW_NUMBER, and mentions indexing on date columns.
How to structure your answer
- Extract month/year from date column for partitioning.
- Calculate revenue (quantity * price) at item level.
- Apply window function with PARTITION BY month.
- Filter to rank = 1 results.
- Consider tie-breaking strategy.
Key points to hit
- PARTITION BY DATE_TRUNC('month', order_date) groups data by calendar month while preserving item-level detail.
- ROW_NUMBER() picks one winner arbitrarily while RANK() can return multiple items tied for first place.
- Window functions avoid the grouping limitations of aggregate functions when you need both summary and detail data.
- Indexing on date columns significantly improves partition performance for time-based window operations.
Common mistakes
- Using RANK() when business rules require exactly one winner per month, creating multiple 'best' items during ties.
- Partitioning by individual dates instead of months, which would rank items per day rather than per month.
Sample answer
I'd use a window function to rank items by revenue within each month. First, I'd calculate revenue as quantity times price, then use ROW_NUMBER() OVER (PARTITION BY DATE_TRUNC('month', order_date) ORDER BY SUM(quantity * price) DESC) to rank items within each month partition.
I'd wrap this in a CTE and filter WHERE rn = 1 to get exactly one winner per month. ROW_NUMBER handles ties by picking one arbitrarily, which works if the business just needs a single winner.
How to level up
- Consider using DENSE_RANK() instead if business rules allow multiple tied winners, and discuss this trade-off explicitly.
- Mention that indexes on (date_column, item_id) can dramatically improve window function performance.
- Suggest materializing monthly aggregates if this query runs frequently, trading storage for query speed.
Follow-up questions to expect
- How would you modify this to show the top 3 items per month instead of just the best?
- What if we wanted to exclude items that were only sold once that month?
- How would you optimize this query if the orders table had 100 million rows?
Compare driver churn rates year-over-year, label as increase/decrease/no change
What they're really asking
This tests complex window functions with year-over-year analysis and conditional logic. The interviewer wants to see if you can compare across time periods, handle missing data gracefully, and implement business logic with CASE statements.
How you'll be scored
Attempts basic comparison without proper year-over-year window functions, or fails to handle the labeling logic correctly.
Uses LAG() or similar window function for year comparison with correct CASE statement labeling, but doesn't address edge cases.
Implements robust year-over-year comparison with LAG(), handles NULL values for first year data, discusses percentage vs absolute change thresholds, and considers data quality issues.
How to structure your answer
- Calculate annual churn rate by year.
- Use LAG() window function to get previous year's rate.
- Implement CASE logic for increase/decrease/no change classification.
- Handle NULL values for baseline year.
- Define threshold for 'no change' vs meaningful difference.
Key points to hit
- LAG(churn_rate, 1) OVER (ORDER BY year) retrieves the previous year's churn rate for comparison within the same result set.
- Define a meaningful threshold for 'no change' since exact equality is rare with percentage calculations.
- Handle the first year's NULL comparison gracefully, typically by labeling it as 'baseline' or excluding it from trending analysis.
- Consider whether to use percentage point differences or relative percentage changes for the comparison logic.
Common mistakes
- Using exact equality (=) for floating-point churn rates instead of a reasonable threshold range for 'no change'
- Forgetting to handle the NULL case when LAG() returns no previous year data for the earliest year.
Sample answer
I'd start by calculating annual churn rates, then use LAG(churn_rate, 1) OVER (ORDER BY year) to get each year's previous rate. Then I'd use CASE WHEN current_rate > previous_rate + 0.01 THEN 'increase' WHEN current_rate < previous_rate - 0.01 THEN 'decrease' ELSE 'no change' to classify the trend. I'm using a 1% threshold because exact equality isn't meaningful with calculated percentages. For the first year where LAG returns NULL, I'd label it as 'baseline' since there's no comparison point.
How to level up
- Discuss whether to use percentage point differences (5% to 7% = 2pp increase) versus relative changes (40% increase)
- Consider using LEAD() as well to create forward-looking trends or validate data consistency.
- Mention that this pattern works well for any time-series comparison, not just year-over-year analysis.
Follow-up questions to expect
- How would you modify this to show quarterly trends instead of annual?
- What if you wanted to flag years where the change was statistically significant?
- How would you handle missing data for certain years in the time series?
Ready to put this into practice?
Try these questions in a mock interview →Still applying for jobs? Let Auto Apply do it
Facebook (3)
Return total number of comments received per user in past 30 days
What they're really asking
This tests basic date filtering with relative dates and simple aggregation. The interviewer wants to see if you understand date arithmetic, can filter dynamically for 'last 30 days', and aggregate correctly without overcounting.
How you'll be scored
Hard-codes specific dates instead of using dynamic 30-day calculation, or fails to group by user properly.
Uses CURRENT_DATE - INTERVAL '30 days' with correct GROUP BY user_id and COUNT aggregation.
Implements dynamic date filtering, explains timezone considerations, discusses whether to include today or not, and mentions indexing strategy for date range queries.
How to structure your answer
- Filter comments to last 30 days using dynamic date calculation.
- Group by user_id to aggregate per user.
- Count total comments per user.
- Consider timezone and boundary conditions.
- Ensure proper indexing for date range performance.
Key points to hit
- Use CURRENT_DATE - INTERVAL '30 days' instead of hard-coding dates to make the query dynamically useful.
- GROUP BY user_id ensures each user appears once with their total comment count, preventing row duplication.
- Consider whether 'past 30 days' includes today or starts from yesterday, depending on business requirements.
- Date range queries benefit significantly from indexes on the date column, especially with large comment tables.
Common mistakes
- Hard-coding specific dates like '2024-01-01' instead of calculating relative to CURRENT_DATE.
- Forgetting GROUP BY user_id, which would return individual comment rows instead of aggregated counts per user.
Sample answer
I'd write SELECT user_id, COUNT(*) as comment_count FROM comments WHERE created_date >= CURRENT_DATE - INTERVAL '30 days' GROUP BY user_id. This filters to comments from the last 30 days using dynamic date calculation, then groups by user to get each person's total.
I'm using >= to include comments from exactly 30 days ago, but I'd confirm with the business whether they want the last 30 complete days or a rolling 30-day window including today.
How to level up
- Clarify timezone handling if users are global, since CURRENT_DATE uses server timezone but user activity might be in local time.
- Consider adding HAVING COUNT(*) > 0 if you want to exclude users with zero comments, though GROUP BY naturally excludes them.
- Mention that an index on (created_date, user_id) would optimize this query pattern for frequent execution.
Follow-up questions to expect
- How would you modify this to show users who haven't commented in the past 30 days?
- What if you wanted to include the user's name along with their comment count?
- How would you handle this query if the comments table had 50 million rows?
Calculate share/percentage of active users from the US with 'open' status
What they're really asking
This tests conditional filtering with multiple WHERE conditions and percentage calculations. The interviewer wants to see if you can combine filtering criteria correctly and calculate proportions using subqueries or window functions.
How you'll be scored
Attempts calculation but uses incorrect filtering logic or fails to compute the percentage properly.
Correctly filters for US users with 'open' status and calculates percentage using subquery or CTE for total active users.
Implements clean percentage calculation, discusses NULL handling in status fields, considers performance implications of multiple filters, and explains alternative approaches.
How to structure your answer
- Filter active users to establish the denominator.
- Apply additional filters for US location and 'open' status.
- Calculate percentage using filtered count divided by total active count.
- Handle potential division by zero or NULL values.
- Consider indexing strategy for multiple filter columns.
Key points to hit
- Use compound WHERE conditions (country = 'US' AND status = 'open') to apply multiple filters simultaneously.
- Calculate percentage as (filtered_count * 100.0 / total_active_count) to ensure floating-point division.
- Consider using a CTE or subquery to avoid repeating the 'active users' filter in both numerator and denominator.
- Handle edge cases like division by zero when there are no active users, returning NULL or 0 as appropriate.
Common mistakes
- Using integer division that truncates decimal places, losing precision in percentage calculations.
- Applying filters incorrectly with OR instead of AND, which would include users who are either US-based OR have open status.
Sample answer
I'd use a CTE to first identify all active users, then calculate the percentage.
WITH active_users AS (SELECT * FROM users WHERE is_active = true), filtered_users AS (SELECT COUNT(*) as us_open_count FROM active_users WHERE country = 'US' AND status = 'open'), total_count AS (SELECT COUNT(*) as total_active FROM active_users) SELECT (us_open_count * 100.0 / total_active) as percentage.
This ensures I'm calculating the share correctly by using the same base population for both numerator and denominator.
How to level up
- Consider using conditional aggregation like SUM(CASE WHEN country = 'US' AND status = 'open' THEN 1 ELSE 0 END) for a more concise single-query approach.
- Add ROUND() to control decimal places in the percentage result for cleaner presentation.
- Mention that composite indexes on (is_active, country, status) would optimize this multi-filter query.
Follow-up questions to expect
- How would you modify this to show percentages for all countries, not just the US?
- What if you wanted to calculate this percentage for each signup month?
- How would you handle this calculation if the status field could be NULL?
Compare total comments by country between Dec 2019 and Jan 2020, identify improved rankings
What they're really asking
This tests complex ranking functions with time-based comparisons and JOINs. The interviewer wants to see if you can rank data across different time periods, compare rankings between periods, and determine improvement direction correctly.
How you'll be scored
Attempts basic comparison without proper ranking functions or fails to correctly identify ranking improvements (lower rank number = better).
Uses DENSE_RANK() for both months with correct join logic, but doesn't clearly explain that ranking improvements mean lower numbers.
Implements proper ranking with DENSE_RANK(), joins time periods correctly, handles countries that appear in only one month, and clearly explains ranking direction and improvement logic.
How to structure your answer
- Aggregate comment counts by country for each target month.
- Apply DENSE_RANK() to rank countries within each month.
- JOIN the two monthly rankings on country.
- Compare rank positions to identify improvements.
- Handle countries that only appear in one time period.
Key points to hit
- DENSE_RANK() handles tied comment counts better than ROW_NUMBER() by giving equal ranks to countries with identical totals.
- Ranking improvement means a lower rank number (moving from rank 5 to rank 3 is an improvement, not a decline)
- Use FULL OUTER JOIN to capture countries that only commented in one of the two months, showing new entrants or complete dropoffs.
- Filter comments to exact month boundaries using WHERE DATE_TRUNC('month', comment_date) IN ('2019-12-01', '2020-01-01') for precision.
Common mistakes
- Confusing ranking direction by treating higher rank numbers as improvements when lower numbers actually indicate better performance.
- Using INNER JOIN which would exclude countries that only appeared in one month, missing important insights about new or departing countries.
Sample answer
I'd create CTEs for each month's rankings. First, aggregate comments by country for December 2019 and January 2020, then apply DENSE_RANK() ORDER BY comment_count DESC within each month. Next, I'd FULL OUTER JOIN the rankings on country name and compare rank positions.
An improvement means the January rank is lower than December rank, since rank 1 is better than rank 5. Countries appearing only in January are 'new entries' while those only in December 'dropped out' completely.
How to level up
- Consider using COALESCE() to treat NULL ranks (countries appearing in only one month) as a very high rank number for cleaner comparison logic.
- Add the actual comment counts alongside ranks to provide context about whether improvements came from absolute growth or relative changes.
- Discuss whether to use RANK() vs DENSE_RANK() based on how the business wants to handle tied countries.
Follow-up questions to expect
- How would you extend this to compare rankings across all months of a year?
- What if you wanted to identify countries that consistently improved their ranking over multiple consecutive months?
- How would you modify this to show the magnitude of ranking changes, not just direction?
Amazon (3)
Find total cost of each customer's orders (output customer id, name, total)
What they're really asking
This tests basic join operations and aggregation fundamentals. The interviewer wants to see if you understand how to combine tables correctly and perform group-level calculations without losing referential integrity.
How you'll be scored
Uses incorrect join type or aggregates without proper grouping, producing wrong results.
Writes a working query with INNER JOIN and proper GROUP BY but doesn't explain the logic.
Delivers correct query, explains why INNER JOIN is appropriate, and mentions potential NULL handling considerations.
How to structure your answer
- Identify the tables needed (customers and orders)
- Choose appropriate join type based on business requirement.
- Determine grouping columns (customer id, name)
- Apply aggregation function (SUM) to cost column.
- Consider edge cases like customers with no orders.
Key points to hit
- INNER JOIN excludes customers without orders, which matches the requirement for customers with order totals.
- GROUP BY must include all non-aggregated SELECT columns to avoid syntax errors.
- SUM handles NULL values by ignoring them, but COALESCE might be needed if orders table allows NULL costs.
- Customer name in GROUP BY assumes it's functionally dependent on customer ID.
Common mistakes
- Using LEFT JOIN when you only want customers who have made purchases, which would require additional NULL filtering.
- Forgetting to include customer name in GROUP BY clause, causing aggregation errors.
Sample answer
I'd use an INNER JOIN between customers and orders tables since we only want customers who have made purchases. The query would be: SELECT c.customer_id, c.name, SUM(o.cost) as total_cost FROM customers c INNER JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.customer_id, c.name.
The INNER JOIN automatically filters out customers without orders, and grouping by both ID and name lets us show the customer details while summing their order costs.
How to level up
- Consider adding ORDER BY total_cost DESC to make results more actionable for business users.
- If the orders table is large, ensure there's an index on customer_id for efficient join performance.
- Mention that you'd validate the data model to confirm customer names don't change over time before including in GROUP BY.
Follow-up questions to expect
- How would you modify this to include customers who haven't made any orders?
- What if we wanted to see the order count alongside total cost for each customer?
- How would you optimize this query if the orders table had millions of rows?
Identify returning users who made a second purchase within 1-7 days of first purchase
What they're really asking
This tests self-join concepts and date range filtering logic. The interviewer wants to see if you can compare rows within the same table and handle complex temporal conditions accurately.
How you'll be scored
Attempts to solve with subqueries or window functions instead of recognizing the self-join pattern, producing incorrect results.
Uses self-join correctly but has issues with the date range logic or doesn't handle edge cases properly.
Implements clean self-join with precise date filtering, explains the logic clearly, and considers performance implications.
How to structure your answer
- Recognize this requires comparing purchase dates within the same user.
- Set up self-join on users table aliased twice.
- Add date range condition between first and second purchase.
- Ensure second purchase is actually after the first.
- Consider indexing strategy for date range queries.
Key points to hit
- Self-join allows comparison of different rows for the same user without complex window functions.
- Date range condition needs both DATEDIFF or similar function and greater than comparison to ensure proper ordering.
- DISTINCT is crucial because one user might have multiple valid second purchases within the window.
- Index on (user_id, purchase_date) supports both the join condition and date filtering efficiently.
Common mistakes
- Using BETWEEN for date ranges without ensuring the second date is actually after the first, allowing same-day duplicates.
- Forgetting DISTINCT when a user has multiple purchases in the 1-7 day window, causing duplicate user results.
Sample answer
I need to compare purchase dates within each user, so I'll use a self-join. SELECT DISTINCT p1.user_id FROM purchases p1 JOIN purchases p2 ON p1.user_id = p2.user_id WHERE p2.purchase_date > p1.purchase_date AND p2.purchase_date <= p1.purchase_date + INTERVAL 7 DAY AND p2.purchase_date >= p1.purchase_date + INTERVAL 1 DAY. The self-join lets me compare different purchase records for the same user, and the date conditions ensure the second purchase falls exactly in the 1-7 day window after the first one.
How to level up
- Consider using ROW_NUMBER() to identify specifically the first and second purchases if business logic requires chronological ordering.
- For large datasets, partition the query by date ranges to avoid comparing every purchase against every other purchase.
- Add user registration date constraints to focus on genuinely new users rather than long-term customers.
Follow-up questions to expect
- How would you modify this to show the actual dates of both purchases for each returning user?
- What if we wanted to find users who made exactly their second purchase in this timeframe, not their second or later?
- How would you optimize this query for a table with millions of purchase records?
Determine which users made additional purchases due to marketing campaign success
What they're really asking
This tests complex conditional logic and attribution analysis. The interviewer wants to see if you can design queries that handle ambiguous business definitions and create measurable success criteria.
How you'll be scored
Provides vague approach without defining what constitutes 'additional purchases' or 'campaign success', missing the core analytical challenge.
Attempts to define success metrics but uses overly simple logic that doesn't account for user behavior complexity.
Clearly defines attribution windows and success criteria, handles multiple campaign exposures, and acknowledges statistical limitations.
How to structure your answer
- Define what constitutes a baseline vs additional purchase.
- Establish attribution window and campaign exposure criteria.
- Create comparison methodology (campaign users vs control group)
- Handle multiple campaign exposures and overlapping timeframes.
- Acknowledge limitations and suggest validation approaches.
Key points to hit
- Attribution requires establishing user purchase patterns before campaign exposure to define 'additional'
- Campaign success needs statistical comparison between exposed and non-exposed user cohorts, not just raw purchase counts.
- Multiple campaign touchpoints complicate attribution and require decision rules for first-touch vs last-touch.
- Time-based windows prevent infinite attribution while capturing campaign impact realistically.
Common mistakes
- Assuming all purchases after campaign exposure are incrementally caused by the campaign, ignoring natural user behavior.
- Not accounting for users exposed to multiple campaigns, leading to double-counting of campaign attribution.
Sample answer
This requires defining what 'additional' means statistically. I'd first establish each user's baseline purchase frequency from their pre-campaign history, then compare post-campaign behavior against that baseline. The query would need CTEs to calculate historical purchase rates, identify campaign exposure dates, and measure lift above expected behavior.
I'd use a control group of similar users not exposed to campaigns to validate that increases are actually incremental. The key challenge is defining the attribution window and handling users with multiple campaign touchpoints.
How to level up
- Implement cohort-based analysis comparing similar user segments rather than individual user comparisons to reduce noise.
- Use statistical tests like t-tests within your SQL results to validate that observed differences are statistically significant.
- Consider incrementality testing by temporarily reducing campaign spend for a subset of users to establish true causal impact.
Follow-up questions to expect
- How would you handle users who were exposed to multiple campaigns with overlapping time periods?
- What statistical methods would you use to validate that the observed lift is actually caused by the campaign?
- How would you adjust this analysis for seasonal businesses where purchase patterns naturally vary?
Ready to put this into practice?
Try these questions in a mock interview →Still applying for jobs? Let Auto Apply do it
Google (3)
Find total AdWords earnings for each business type
What they're really asking
This tests basic aggregation and grouping concepts. The interviewer wants to see if you understand how GROUP BY partitions data and how aggregate functions operate within those partitions.
How you'll be scored
Attempts to aggregate without proper GROUP BY or misunderstands which columns can appear in SELECT with aggregation.
Writes correct query with GROUP BY and SUM but doesn't explain the aggregation logic.
Delivers correct query, explains how GROUP BY creates partitions, and mentions potential data quality considerations.
How to structure your answer
- Identify the grouping column (business_type)
- Choose appropriate aggregate function (SUM for earnings)
- Write SELECT with grouped column and aggregated value.
- Consider whether to filter or sort results.
- Think about NULL handling in business_type column.
Key points to hit
- GROUP BY business_type creates separate partitions where SUM operates independently on each partition.
- Only business_type and aggregate functions can appear in SELECT since other columns would be ambiguous within groups.
- SUM automatically handles NULL earnings values by ignoring them, but consider COALESCE if zero is preferred over NULL.
- Results might benefit from ORDER BY to show highest-earning business types first.
Common mistakes
- Including non-aggregated columns in SELECT that aren't in GROUP BY, causing syntax errors or unexpected results.
- Forgetting that NULL values in business_type create a separate group, which might need special handling.
Sample answer
This is a straightforward aggregation query. I'd write SELECT business_type, SUM(adwords_earnings) as total_earnings FROM businesses GROUP BY business_type. The GROUP BY creates separate buckets for each business type, and SUM adds up all the AdWords earnings within each bucket.
I might add ORDER BY total_earnings DESC to see the most profitable business types first, and I'd check if there are any NULL business types that need special handling.
How to level up
- Consider adding COUNT(*) alongside SUM to show how many businesses contribute to each total for additional context.
- Use HAVING clause if you need to filter business types based on their total earnings rather than individual records.
- Think about whether to include business types with zero earnings or exclude them entirely based on business requirements.
Follow-up questions to expect
- How would you modify this to only show business types with total earnings above $10,000?
- What if we wanted to see the average earnings per business within each type as well?
- How would you handle the case where some businesses have NULL business_type values?
Find number of emails received by each user under each built-in email label (Promotion, Social, Shopping)
What they're really asking
This tests conditional aggregation with joins across multiple tables. The interviewer wants to see if you can combine table relationships with CASE logic to pivot data correctly.
How you'll be scored
Uses separate queries or subqueries instead of conditional aggregation, making the solution inefficient and complex.
Implements joins and CASE statements correctly but doesn't optimize the query structure or explain the logic clearly.
Uses efficient conditional aggregation with proper joins, explains the pivoting logic, and considers performance implications.
How to structure your answer
- Identify required tables (users, emails, labels)
- Plan join strategy to connect users with their emails and labels.
- Use CASE statements within COUNT to create separate columns for each label type.
- Group by user to aggregate email counts per user.
- Consider performance implications of multiple joins.
Key points to hit
- Conditional aggregation with CASE statements is more efficient than separate queries with UNION.
- JOIN strategy should account for whether all users should be shown or only users with emails.
- Each CASE WHEN creates a separate counter that only increments when the condition matches the specific label.
- Built-in labels likely come from a labels reference table, requiring proper foreign key joins.
Common mistakes
- Using multiple separate queries instead of conditional aggregation, creating unnecessary complexity and performance overhead.
- Incorrect join conditions that might double-count emails if the schema has many-to-many relationships between emails and labels.
Sample answer
I need to join users, emails, and labels tables, then use conditional aggregation to count emails by label type.
SELECT u.user_id, COUNT(CASE WHEN l.label_name = 'Promotion' THEN 1 END) as promotion_count, COUNT(CASE WHEN l.label_name = 'Social' THEN 1 END) as social_count, COUNT(CASE WHEN l.label_name = 'Shopping' THEN 1 END) as shopping_count FROM users u LEFT JOIN emails e ON u.user_id = e.user_id LEFT JOIN labels l ON e.email_id = l.email_id WHERE l.label_name IN ('Promotion', 'Social', 'Shopping') GROUP BY u.user_id.
The CASE statements create separate counters for each label type, which is much more efficient than running separate queries.
How to level up
- Consider using SUM(CASE WHEN condition THEN 1 ELSE 0 END) instead of COUNT(CASE WHEN) for more explicit null handling.
- Add indexes on the join columns (user_id, email_id) and filter columns (label_name) to optimize performance.
- If users can have emails with multiple labels, ensure your join strategy doesn't double-count emails inappropriately.
Follow-up questions to expect
- How would you modify this to include users who haven't received any emails in these categories?
- What if we wanted to see the percentage breakdown of each label type per user instead of raw counts?
- How would you optimize this query if the emails table contained millions of records?
Rank users by email activity with specific ordering and tiebreaker requirements
What they're really asking
This tests window function mastery and ranking logic. The interviewer wants to see if you can handle complex ordering requirements with multiple criteria and understand how window functions partition and order data.
How you'll be scored
Uses basic ORDER BY or subqueries instead of window functions, or gets the ranking logic wrong.
Correctly uses RANK() or ROW_NUMBER() with proper partitioning and ordering.
Chooses the right ranking function, handles ties appropriately, and discusses performance implications of window functions.
How to structure your answer
- Clarify the ranking requirements and tie-breaking rules.
- Choose between RANK(), DENSE_RANK(), or ROW_NUMBER() based on tie handling.
- Write the window function with correct PARTITION BY and ORDER BY.
- Test the logic with edge cases.
- Consider performance and indexing strategy.
Key points to hit
- RANK() leaves gaps after ties while DENSE_RANK() doesn't, and ROW_NUMBER() assigns unique numbers even for ties.
- Window functions process after WHERE but before ORDER BY in the execution sequence.
- Partitioning in window functions creates separate ranking sequences for each partition.
- Index on partitioning and ordering columns significantly improves window function performance.
Common mistakes
- Confusing RANK() vs DENSE_RANK() vs ROW_NUMBER() for tie handling.
- Forgetting that window functions can't be used in WHERE clauses directly.
Sample answer
I'd use RANK() OVER (PARTITION BY user_type ORDER BY email_count DESC, last_activity_date DESC) to rank users by email activity. The PARTITION BY creates separate rankings for different user types, ORDER BY email_count DESC puts highest activity first, and last_activity_date DESC breaks ties by most recent activity.
RANK() is appropriate here because if two users tie for second place, the next user should be ranked fourth, not third. I'd ensure we have a composite index on user_type, email_count, and last_activity_date for optimal performance.
How to level up
- Consider using PERCENT_RANK() if you need relative rankings as percentiles.
- Window functions with PARTITION BY can often replace correlated subqueries with better performance.
- Use ROWS vs RANGE carefully in window frames when you need running totals or moving averages.
Follow-up questions to expect
- How would you modify this to show only the top 3 users per partition?
- What's the difference between ROWS and RANGE in window function frames?
- How would you optimize the query if the table had millions of rows?
Advanced SQL Concepts (18)
What is PL/SQL and how does it differ from standard SQL?
What they're really asking
This tests knowledge of Oracle's procedural extension to SQL and understanding of when declarative SQL isn't sufficient. The interviewer wants to see if you understand the boundary between SQL and procedural programming.
How you'll be scored
Vague explanation or confuses PL/SQL with other database languages like T-SQL or stored procedures in general.
Correctly identifies PL/SQL as Oracle's procedural extension with basic features like variables and loops.
Explains Oracle-specific PL/SQL features, discusses when to use procedural vs declarative approaches, and mentions performance implications.
How to structure your answer
- Define PL/SQL as Oracle's procedural language extension.
- Contrast declarative SQL with procedural capabilities.
- Explain key PL/SQL features like blocks, variables, and control structures.
- Discuss when PL/SQL is appropriate vs pure SQL.
- Mention performance and maintainability considerations.
Key points to hit
- PL/SQL adds variables, conditional logic, loops, and exception handling to Oracle SQL.
- Standard SQL is declarative (what you want) while PL/SQL is procedural (how to get it)
- PL/SQL blocks have declaration, execution, and exception sections with specific syntax.
- Use PL/SQL for complex business logic that can't be expressed efficiently in declarative SQL.
Common mistakes
- Confusing PL/SQL with T-SQL or generic stored procedure concepts.
- Not mentioning that PL/SQL is Oracle-specific.
Sample answer
PL/SQL is Oracle's procedural language extension that adds programming constructs like variables, IF-THEN logic, loops, and exception handling to standard SQL. While SQL is declarative and tells the database what you want, PL/SQL is procedural and lets you specify how to process data step by step.
For example, you might use PL/SQL for complex data validation that requires multiple conditional checks, or batch processing that needs to loop through records with custom logic. The key difference is that standard SQL operates on sets of data declaratively, while PL/SQL can process data row by row with programmatic control flow.
How to level up
- PL/SQL can often be replaced by advanced SQL features like CASE, window functions, or recursive CTEs for better performance.
- Consider PL/SQL's compilation and caching benefits for frequently executed complex procedures.
- Use bulk operations like FORALL and BULK COLLECT in PL/SQL to minimize context switching between SQL and PL/SQL engines.
Follow-up questions to expect
- When would you choose PL/SQL over pure SQL for a data processing task?
- How does PL/SQL compilation and execution differ from interpreted SQL?
- What are the equivalent procedural languages in SQL Server or PostgreSQL?
What is a recursive stored procedure? When would you use one?
What they're really asking
This tests understanding of advanced procedural programming in databases and recursive algorithm implementation. The interviewer wants to see if you can identify appropriate use cases for recursion and understand the risks.
How you'll be scored
Cannot explain recursion clearly or gives inappropriate use cases where iteration would be better.
Correctly explains recursive procedures and gives valid use cases like hierarchical data traversal.
Explains recursion with termination conditions, discusses stack overflow risks, and compares recursive procedures to recursive CTEs.
How to structure your answer
- Define recursive stored procedures with base and recursive cases.
- Explain the call stack mechanism.
- Provide concrete use cases like hierarchical data or tree traversal.
- Discuss termination conditions and infinite loop prevention.
- Compare with alternatives like recursive CTEs or iterative approaches.
Key points to hit
- Recursive procedures call themselves with different parameters until reaching a base case.
- Common use cases include organizational hierarchies, bill of materials, and graph traversal.
- Always include proper termination conditions to prevent stack overflow.
- Modern databases often prefer recursive CTEs over recursive procedures for hierarchical queries.
Common mistakes
- Not mentioning termination conditions or stack overflow risks.
- Suggesting recursion for problems better solved iteratively.
Sample answer
A recursive stored procedure calls itself with modified parameters until it reaches a base case that stops the recursion. I'd use one for traversing hierarchical data like an organizational chart where you need to find all employees under a manager.
The procedure would take a manager ID, process that level, then call itself for each direct report until it reaches employees with no subordinates. The key is ensuring proper termination conditions to avoid infinite loops and stack overflow.
However, I'd often prefer recursive CTEs for hierarchical queries since they're more efficient and easier to maintain than recursive procedures.
How to level up
- Consider tail recursion optimization if your database supports it to reduce stack usage.
- Use iteration with a stack data structure instead of recursion for deep hierarchies to avoid stack overflow.
- Recursive CTEs often perform better than recursive procedures because they're optimized by the query planner.
Follow-up questions to expect
- How would you prevent infinite loops in a recursive procedure?
- When would you choose a recursive CTE over a recursive stored procedure?
- What's the maximum recursion depth in your database system?
Explain the difference between @@IDENTITY, SCOPE_IDENTITY(), and IDENT_CURRENT
What they're really asking
This tests deep knowledge of SQL Server identity value functions and their scope differences. The interviewer wants to see if you understand transaction isolation and identity value reliability in concurrent environments.
How you'll be scored
Doesn't know the difference or incorrectly explains the scope and behavior of these functions.
Correctly explains that they return identity values with different scopes and timing.
Explains scope differences, concurrent access behavior, and when each function is appropriate for reliable identity retrieval.
How to structure your answer
- Define what each function returns.
- Explain the scope differences (connection vs session vs table)
- Discuss timing of when values are captured.
- Address concurrent access and reliability issues.
- Recommend which function to use in different scenarios.
Key points to hit
- @@IDENTITY returns the last identity value from any table in the current session.
- SCOPE_IDENTITY() returns the last identity value from the current scope (procedure/batch)
- IDENT_CURRENT returns the last identity value for a specific table regardless of session.
- SCOPE_IDENTITY() is safest for getting your own insert's identity value in concurrent environments.
Common mistakes
- Not understanding that @@IDENTITY can be affected by triggers that insert into other identity tables.
- Using IDENT_CURRENT when you need your own session's identity value.
Sample answer
These three functions return identity values with different scopes. @@IDENTITY returns the last identity value generated in the current session from any table, which can be problematic if triggers insert into other identity tables. SCOPE_IDENTITY() returns the last identity value generated in the current scope, making it safe from trigger interference.
IDENT_CURRENT takes a table name and returns the last identity value for that specific table regardless of session or scope. For reliability, I use SCOPE_IDENTITY() after my own inserts because it's not affected by other sessions or triggers, while IDENT_CURRENT is useful for checking the current state of a table's identity column.
How to level up
- Always use SCOPE_IDENTITY() instead of @@IDENTITY after INSERT statements to avoid trigger interference.
- IDENT_CURRENT is useful for monitoring or administrative queries but not for getting your own insert's identity value.
- Consider using OUTPUT clause with INSERT statements as a more explicit alternative to identity functions.
Follow-up questions to expect
- What happens to these functions if your INSERT statement fails?
- How would you handle identity values in a multi-user environment?
- What's the difference between these functions and using OUTPUT clause?
What is a fill factor in an index? When does a page split occur?
What they're really asking
This tests advanced indexing knowledge and understanding of storage internals. The interviewer wants to see if you can optimize index maintenance and understand the trade-offs between storage efficiency and performance.
How you'll be scored
Doesn't understand fill factor concept or when page splits occur.
Correctly explains fill factor as reserved space and basic page split concepts.
Explains fill factor optimization strategy, discusses page split impact on performance, and knows how to tune fill factor for different workloads.
How to structure your answer
- Define fill factor as percentage of page space used.
- Explain the relationship between fill factor and free space.
- Describe when and why page splits occur.
- Discuss the performance impact of page splits.
- Provide guidance on choosing appropriate fill factor values.
Key points to hit
- Fill factor determines what percentage of each index page is filled during index creation or rebuild.
- Page splits occur when a new row can't fit on the appropriate page due to insufficient free space.
- Lower fill factor reduces page splits but increases storage requirements and potentially more page reads.
- Choose fill factor based on insert/update patterns: high for read-heavy tables, lower for write-heavy tables.
Common mistakes
- Thinking fill factor applies during normal operations rather than just during index creation/rebuild.
- Not understanding that page splits cause performance degradation through fragmentation.
Sample answer
Fill factor specifies what percentage of each index page should be filled when the index is created or rebuilt, leaving the rest as free space for future inserts.
A page split occurs when SQL Server tries to insert a row into a page that doesn't have enough free space, forcing it to split the page and move some data to a new page. This causes fragmentation and extra I/O.
For a table with frequent inserts, I might use a fill factor of 80% to leave room for growth and reduce page splits. For read-only tables, I'd use 100% to maximize storage efficiency since page splits aren't a concern.
How to level up
- Monitor fragmentation levels with sys.dm_db_index_physical_stats to determine if your fill factor needs adjustment.
- Consider different fill factors for clustered vs non-clustered indexes based on their update patterns.
- Remember that fill factor only applies during index maintenance operations, not during normal INSERT/UPDATE operations.
Follow-up questions to expect
- How would you determine the optimal fill factor for a specific table?
- What's the relationship between fill factor and index fragmentation?
- How do you monitor and resolve page split issues in production?
What is RAID and how does it relate to database performance?
What they're really asking
This tests infrastructure knowledge and how hardware affects database performance. The interviewer wants to see if you understand how storage systems impact query speed and can discuss database administration beyond just writing queries.
How you'll be scored
Confuses RAID with database concepts or gives vague answers about 'making things faster.'
Correctly explains RAID levels and mentions performance benefits without specific database context.
Explains RAID types, discusses specific database performance implications like read/write patterns, and mentions when different RAID levels are appropriate for different database workloads.
How to structure your answer
- Define RAID as hardware-level disk redundancy and performance.
- Explain key RAID levels (0, 1, 5, 10) and their characteristics.
- Connect each RAID type to specific database performance scenarios.
- Discuss trade-offs between performance, redundancy, and cost.
Key points to hit
- RAID 0 offers high performance but no redundancy, suitable for temp databases or heavy read workloads with backup strategies.
- RAID 1 provides mirroring for critical data like transaction logs where write performance and redundancy matter most.
- RAID 10 combines performance and redundancy, ideal for high-transaction databases where both read and write speed are critical.
- Different database components (data files, logs, tempdb) benefit from different RAID configurations based on their I/O patterns.
Common mistakes
- Treating RAID as purely a performance tool without considering the redundancy and reliability aspects that are crucial for database systems.
- Not connecting RAID choices to specific database workload patterns like OLTP versus OLAP systems.
Sample answer
RAID stands for Redundant Array of Independent Disks and it's crucial for database performance because databases are heavily I/O dependent. RAID 0 stripes data across disks for maximum speed but offers no redundancy, so I'd use it for tempdb or read-only databases.
RAID 1 mirrors data for redundancy and is perfect for transaction logs since log writes are sequential and we need guaranteed durability. RAID 10 combines striping and mirroring, giving us both performance and protection, which makes it ideal for main data files in high-transaction systems.
The key is matching the RAID level to the I/O pattern and criticality of each database component.
How to level up
- Discuss how SSD versus HDD changes RAID considerations, as SSDs reduce the performance gap between RAID levels.
- Mention cloud storage options like AWS EBS and how they provide RAID-like benefits without managing physical hardware.
Follow-up questions to expect
- How would you monitor disk performance to identify when RAID configuration might be causing bottlenecks?
- What's the difference between hardware RAID and software RAID for database servers?
- How does database file placement across RAID arrays affect backup and recovery strategies?
What are the different ways of moving data between databases in SQL Server?
What they're really asking
This tests knowledge of data integration and ETL processes in SQL Server environments. The interviewer wants to see if you understand enterprise data movement patterns and can choose appropriate tools for different scenarios.
How you'll be scored
Only mentions basic methods like backup/restore or gives generic answers without SQL Server specifics.
Lists several methods like SSIS, linked servers, and bulk operations with basic explanations.
Explains multiple approaches with specific use cases, discusses performance implications, and mentions when to use each method based on data volume and business requirements.
How to structure your answer
- Categorize methods by use case (one-time migration, ongoing sync, real-time)
- Explain native SQL Server tools and their strengths.
- Discuss third-party and custom solutions.
- Compare performance and complexity trade-offs.
Key points to hit
- SSIS (SQL Server Integration Services) provides comprehensive ETL with data transformation capabilities for complex migrations.
- Linked servers enable real-time cross-database queries but can create performance bottlenecks for large data sets.
- Bulk operations like BCP and BULK INSERT offer high-speed data transfer for large volumes without transformation needs.
- Replication and Always On availability groups provide ongoing data synchronization for distributed systems.
Common mistakes
- Recommending linked servers for large data transfers without considering network latency and locking issues.
- Not considering transaction log growth and recovery model implications when moving large amounts of data.
Sample answer
There are several approaches depending on your needs. For one-time migrations with data transformation, I'd use SSIS because it handles complex mappings and data cleansing. For ongoing synchronization, replication works well for distributing data to multiple locations.
Linked servers are great for real-time queries across databases but I avoid them for large data transfers due to performance issues. For high-volume raw data movement, BCP utility or BULK INSERT are fastest since they bypass transaction log overhead.
I also consider backup/restore for complete database copies and Always On for disaster recovery scenarios where you need both high availability and readable secondaries.
How to level up
- Discuss change data capture (CDC) for incremental data movement to reduce transfer volumes.
- Mention Azure Data Factory for cloud-based data integration scenarios.
Follow-up questions to expect
- How would you handle schema differences when moving data between databases with different structures?
- What are the security considerations when setting up linked servers between databases?
- How do you monitor and troubleshoot performance issues during large data transfers?
What is BCP (Bulk Copy Program) utility in SQL Server?
What they're really asking
This tests knowledge of SQL Server's bulk data import capabilities and command-line tools. The interviewer wants to see if you understand high-performance data loading scenarios and can work outside of just T-SQL queries.
How you'll be scored
Vague understanding of BCP as a 'bulk copy tool' without specific syntax or use cases.
Correctly explains BCP as a command-line utility for bulk operations with basic syntax examples.
Demonstrates detailed BCP knowledge including format files, performance considerations, and when to choose BCP over alternatives like BULK INSERT or SSIS.
How to structure your answer
- Define BCP as SQL Server's command-line bulk copy utility.
- Explain key operations (in, out, queryout, format)
- Discuss format files and data type handling.
- Compare performance characteristics and use cases.
Key points to hit
- BCP operates outside SQL Server's transaction log in certain modes, making it extremely fast for large data imports.
- Format files allow precise control over column mapping and data type conversion during import/export operations.
- BCP supports both character and native data formats, with native format providing better performance for SQL Server to SQL Server transfers.
- The utility can export query results directly using queryout, making it flexible for complex data extraction scenarios.
Common mistakes
- Not understanding that BCP bypasses constraints and triggers by default, which can lead to data integrity issues if not handled properly.
- Forgetting that BCP requires specific file permissions and SQL Server authentication considerations.
Sample answer
BCP is SQL Server's command-line bulk copy utility designed for high-performance data import and export. It's particularly powerful because it can operate in minimally logged mode, bypassing much of the transaction log overhead that slows down regular INSERT statements.
I use 'bcp in' to import data from files, 'bcp out' to export entire tables, and 'bcp queryout' to export custom query results. Format files are crucial for handling column mapping and data type conversions.
For example, when importing CSV files with different column orders, I create a format file to map the file structure to the table structure. BCP is my go-to tool when I need to move millions of rows quickly, though I have to be careful about constraints and triggers since they're disabled by default.
How to level up
- Use the -h hint options like TABLOCK for even better performance during large imports.
- Consider using BCP with partitioned tables by importing to staging tables first, then switching partitions for near-instantaneous large data loads.
Follow-up questions to expect
- How would you handle error logging and recovery when a BCP operation fails partway through a large import?
- What's the difference between BCP and BULK INSERT, and when would you choose one over the other?
- How do you secure BCP operations when dealing with sensitive data in production environments?
How can you raise custom errors from a stored procedure?
What they're really asking
This tests knowledge of custom error handling in stored procedures and application integration. The interviewer wants to see if you can create robust database code that provides meaningful feedback to calling applications.
How you'll be scored
Only mentions RAISERROR or THROW without proper syntax or understanding of error severity levels.
Demonstrates correct RAISERROR or THROW syntax with basic error message customization.
Shows comprehensive error handling including custom error messages, severity levels, state codes, and integration with TRY-CATCH blocks for proper error propagation.
How to structure your answer
- Explain RAISERROR and THROW statements with syntax differences.
- Discuss error severity levels and state codes.
- Show integration with TRY-CATCH for comprehensive error handling.
- Demonstrate custom error message creation and logging.
Key points to hit
- THROW statement (SQL Server 2012+) is preferred over RAISERROR because it preserves the original error's stack trace and line numbers.
- Custom error messages can be stored in sys.messages using sp_addmessage for consistent error handling across procedures.
- Error severity levels from 11-16 can be caught by TRY-CATCH blocks, while levels 17+ terminate connections.
- State codes (0-255) allow you to differentiate between different occurrences of the same error message.
Common mistakes
- Using severity levels incorrectly, especially setting them too high (17+) which terminates the connection unexpectedly.
- Not including proper error context like procedure name and input parameters when raising custom errors.
Sample answer
I prefer using THROW over RAISERROR in modern SQL Server because it maintains better error context. For custom errors, I use THROW with formatted messages like 'THROW 50001, ''Customer ID '' + CAST(@CustomerID AS VARCHAR) + '' not found'', 1'. I also create reusable custom messages with sp_addmessage for consistent error handling across procedures.
In my stored procedures, I wrap business logic in TRY-CATCH blocks and use THROW in the CATCH block to re-raise errors with additional context. For example, I might catch a constraint violation and throw a more user-friendly message like 'Cannot delete customer with active orders' instead of exposing the raw constraint error.
I always include relevant parameter values in error messages to help with debugging.
How to level up
- Create a centralized error logging procedure that captures error details, user context, and procedure parameters for better debugging.
- Use structured error handling patterns with consistent error number ranges for different types of business rule violations.
Follow-up questions to expect
- How do you handle error propagation when you have nested stored procedure calls?
- What's your strategy for logging errors while still allowing the calling application to handle them appropriately?
- How do you test error handling scenarios in your stored procedures to ensure they behave correctly under failure conditions?
If we have multiple AFTER triggers on a table, how do we define the sequence?
What they're really asking
This tests advanced trigger knowledge and understanding of SQL Server's trigger execution architecture. The interviewer wants to see if you can manage complex trigger scenarios where execution order matters for business logic.
How you'll be scored
Doesn't know that trigger order can be controlled or thinks triggers fire randomly.
Mentions sp_settriggerorder but lacks detail about the limitations and use cases.
Explains sp_settriggerorder with its three options (First, Last, None), discusses the limitation of only controlling first and last triggers, and suggests design alternatives when complex ordering is needed.
How to structure your answer
- Explain that multiple AFTER triggers fire in undefined order by default.
- Introduce sp_settriggerorder as the solution for controlling execution sequence.
- Detail the three order options and their limitations.
- Suggest best practices for trigger design when order matters.
Key points to hit
- By default, multiple AFTER triggers on the same table fire in undefined order, which can cause inconsistent results.
- sp_settriggerorder allows you to designate one trigger as 'First' and one as 'Last', but middle triggers still fire in random order.
- The procedure requires specifying the trigger name, table name, order type ('First', 'Last', or 'None'), and trigger event (INSERT, UPDATE, DELETE)
- Best practice is to minimize dependencies between triggers or consolidate related logic into a single trigger when execution order is critical.
Common mistakes
- Assuming you can control the exact order of all triggers when you can only control the first and last positions.
- Creating complex trigger dependencies that make the database logic difficult to maintain and debug.
Sample answer
By default, multiple AFTER triggers fire in undefined order, which can cause problems when triggers depend on each other's results. SQL Server provides sp_settriggerorder to control this. I can designate one trigger as 'First' and another as 'Last' using syntax like 'EXEC sp_settriggerorder @triggername = 'AuditTrigger', @order = 'First', @stmttype = 'INSERT', @namespace = 'MyTable'.
However, this only controls the first and last positions. If I have more than two triggers, the middle ones still fire randomly. When I encounter scenarios requiring complex trigger ordering, I usually redesign to consolidate related logic into fewer triggers or use stored procedures with explicit sequencing instead of relying on multiple interdependent triggers.
How to level up
- Consider using a single comprehensive trigger with conditional logic blocks rather than multiple ordered triggers for better maintainability.
- Document trigger dependencies clearly and consider using naming conventions that indicate execution order requirements.
Follow-up questions to expect
- What happens to trigger execution order when you have both AFTER and INSTEAD OF triggers on the same table?
- How would you debug issues when multiple triggers are interfering with each other's logic?
- What are the performance implications of having many triggers on a frequently updated table?
What is collation and what are the different types of collation sensitivity?
What they're really asking
This tests database administration and character handling knowledge. The interviewer wants to see if you understand how collation affects sorting, comparison operations, and query performance in multi-language environments.
How you'll be scored
Gives a vague definition without mentioning specific sensitivity types or their impact on queries.
Defines collation correctly and names the main sensitivity types (case, accent, kana, width).
Explains collation with examples of how different sensitivities affect WHERE clauses and ORDER BY, plus mentions performance implications.
How to structure your answer
- Define collation as rules for character comparison and sorting.
- List the four main sensitivity types with examples.
- Explain how collation affects query behavior.
- Mention database-level vs column-level collation settings.
Key points to hit
- Collation determines how strings are compared, sorted, and matched in WHERE clauses and JOIN conditions.
- Case sensitivity affects whether 'Smith' equals 'smith' in comparisons.
- Accent sensitivity determines if 'cafรฉ' matches 'cafe' in searches.
- Different collations can impact index usage and query performance.
Common mistakes
- Confusing collation with character encoding (UTF-8, ASCII)
- Not understanding that collation mismatches between columns can prevent index usage.
Sample answer
Collation defines the rules for comparing and sorting character data in a database. There are four main types of sensitivity: case sensitivity determines whether 'John' equals 'john', accent sensitivity controls if 'cafรฉ' matches 'cafe', kana sensitivity affects Japanese characters, and width sensitivity handles full-width vs half-width characters.
For example, with a case-insensitive collation, a WHERE clause filtering for 'smith' would match both 'Smith' and 'SMITH'. Collation is set at the database level by default but can be overridden at the column level, and mismatched collations between joined columns can force table scans instead of using indexes.
How to level up
- Know that COLLATE can be used in queries to override column collation for specific operations.
- Understand that binary collations provide fastest performance but lose linguistic sorting rules.
Follow-up questions to expect
- How would you handle a query that needs to join tables with different collations?
- What performance impact would you expect from changing a column's collation?
- How would you design collation strategy for a multi-language application?
How do you alter a table to make an existing column an identity column?
What they're really asking
This tests advanced DDL knowledge and understanding of identity column constraints. The interviewer wants to see if you know the limitations and syntax for modifying existing table structures with auto-increment behavior.
How you'll be scored
Suggests using ALTER COLUMN which doesn't work for adding identity properties to existing columns.
Knows you can't directly alter an existing column to add identity and mentions recreating the table.
Explains the complete process including backup, new table creation, data migration, constraint recreation, and mentions the newer ALTER TABLE ADD IDENTITY syntax where available.
How to structure your answer
- State that direct alteration isn't possible in most SQL databases.
- Outline the table recreation approach with backup steps.
- Mention newer database-specific solutions where available.
- Address transaction safety and downtime considerations.
Key points to hit
- Most databases don't allow direct conversion of existing columns to identity columns using ALTER COLUMN.
- The standard approach requires creating a new table with identity column and migrating data.
- SQL Server 2012+ supports ALTER TABLE table_name ALTER COLUMN column_name ADD GENERATED ALWAYS AS IDENTITY.
- Always backup data and test the migration process before production changes.
Common mistakes
- Trying to use ALTER COLUMN to add identity properties directly.
- Forgetting to recreate foreign key constraints and indexes after table recreation.
Sample answer
You cannot directly alter an existing column to become an identity column in most databases. The traditional approach is to create a new table with the identity column defined, copy data from the old table using INSERT INTO new_table SELECT * FROM old_table, then drop the old table and rename the new one.
However, SQL Server 2012 and later supports ALTER TABLE employees ALTER COLUMN emp_id ADD GENERATED ALWAYS AS IDENTITY. For the manual approach, you need to backup data first, recreate all constraints and indexes, and plan for application downtime during the migration.
How to level up
- Consider using a transaction with proper rollback strategy for the migration process.
- Test identity seed and increment values match your application's expectations after migration.
Follow-up questions to expect
- How would you handle foreign key references during this table recreation process?
- What would you do if the existing column has duplicate values?
- How would you minimize downtime for this operation on a production system?
How do you fetch alternate (odd/even numbered) records from a table?
What they're really asking
This tests window function knowledge and row numbering techniques. The interviewer wants to see if you understand ROW_NUMBER() and modulo operations for pattern-based data retrieval.
How you'll be scored
Uses inefficient approaches like cursors or multiple queries without understanding row numbering concepts.
Uses ROW_NUMBER() with modulo operation correctly but doesn't explain the logic clearly.
Demonstrates ROW_NUMBER() with CTE, explains modulo logic clearly, and mentions performance considerations for large datasets.
How to structure your answer
- Use ROW_NUMBER() window function to assign sequential numbers.
- Apply modulo operation to identify odd/even patterns.
- Wrap in CTE or subquery for clean filtering.
- Mention ordering considerations for consistent results.
Key points to hit
- ROW_NUMBER() assigns sequential integers starting from 1 to each row.
- Modulo operator (%) returns remainder: even rows have ROW_NUMBER() % 2 = 0, odd rows = 1.
- ORDER BY in the window function determines which rows are considered odd/even.
- CTE makes the query more readable than inline subqueries.
Common mistakes
- Forgetting to specify ORDER BY in ROW_NUMBER(), making results non-deterministic.
- Confusing the modulo logic (thinking odd rows are % 2 = 0)
Sample answer
I'd use ROW_NUMBER() with a modulo operation. First, I create a CTE with WITH numbered_rows AS (SELECT *, ROW_NUMBER() OVER (ORDER BY id) as row_num FROM employees), then SELECT * FROM numbered_rows WHERE row_num % 2 = 1 for odd rows or row_num % 2 = 0 for even rows.
The key is that ROW_NUMBER() assigns 1, 2, 3, etc., so odd-numbered rows have remainder 1 when divided by 2, and even-numbered rows have remainder 0. The ORDER BY clause in the window function is crucial because it determines which records get which row numbers.
How to level up
- Consider the business meaning of 'alternate' records since physical storage order may not match logical order.
- For very large tables, this approach scans all data, so consider if pagination with OFFSET/FETCH is more appropriate.
Follow-up questions to expect
- How would you modify this to get every third record instead of alternating?
- What happens if you don't specify ORDER BY in the ROW_NUMBER() function?
- How would you optimize this query for a table with millions of rows?
How do you fetch common records from two tables without using JOIN?
What they're really asking
This tests set operation knowledge and understanding of INTERSECT vs JOIN performance characteristics. The interviewer wants to see if you know multiple approaches for finding matching data and their trade-offs.
How you'll be scored
Only knows one method or suggests inefficient approaches like nested loops without set operations.
Uses INTERSECT correctly but doesn't explain when it's preferable to JOIN or mention performance implications.
Demonstrates INTERSECT, EXISTS, and IN approaches, explains when each is optimal, and discusses duplicate handling differences.
How to structure your answer
- Use INTERSECT for exact row matching between tables.
- Alternative with EXISTS for more control over matching criteria.
- Mention IN operator as another option with limitations.
- Compare performance and duplicate handling of each approach.
Key points to hit
- INTERSECT returns rows that exist in both result sets, automatically removing duplicates.
- EXISTS with correlated subquery gives more control over matching conditions and can be faster.
- IN operator works for single-column comparisons but has issues with NULL values.
- INTERSECT requires identical column count and compatible data types between queries.
Common mistakes
- Using IN with columns that might contain NULL values, which can produce unexpected results.
- Not understanding that INTERSECT compares entire rows, not just key columns.
Sample answer
I'd use INTERSECT to find common records: SELECT column1, column2 FROM table1 INTERSECT SELECT column1, column2 FROM table2. This returns rows that exist in both tables and automatically removes duplicates.
Alternatively, I could use EXISTS: SELECT * FROM table1 WHERE EXISTS (SELECT 1 FROM table2 WHERE table1.id = table2.id), which gives more control over the matching criteria.
A third option is IN: SELECT * FROM table1 WHERE id IN (SELECT id FROM table2), but this only works for single-column comparisons and can have issues with NULL values. INTERSECT is cleanest when you want exact row matches across all columns.
How to level up
- EXISTS often performs better than IN for large datasets because it stops at the first match.
- Consider using INTERSECT ALL if you need to preserve duplicate records in the result.
Follow-up questions to expect
- What would happen if one of the tables has NULL values in the comparison columns?
- How would you find records that exist in table1 but not in table2?
- Which approach would perform better on tables with millions of rows?
What is the difference between local and global temporary tables (# vs ##)?
What they're really asking
This tests session management and temporary object scope knowledge. The interviewer wants to see if you understand the visibility and lifecycle differences between local and global temp tables in SQL Server.
How you'll be scored
Knows they're both temporary but can't explain scope or naming differences clearly.
Correctly explains that # is session-scoped and ## is global, mentions automatic cleanup.
Details complete lifecycle including when each is created/dropped, visibility across sessions, and use cases for each type.
How to structure your answer
- Define scope differences: local (#) is session-specific, global (##) is server-wide.
- Explain visibility and access rules for each type.
- Describe cleanup behavior and lifecycle management.
- Mention use cases where each type is appropriate.
Key points to hit
- Local temp tables (#) are visible only to the session that created them and automatically drop when the session ends.
- Global temp tables (##) are visible to all sessions and drop when the last session referencing them disconnects.
- Local temp tables can have name collisions across sessions (SQL Server handles this internally)
- Global temp tables must have unique names across the entire server instance.
Common mistakes
- Thinking global temp tables persist forever without any cleanup mechanism.
- Not understanding that multiple sessions can create local temp tables with the same name.
Sample answer
Local temporary tables use single hash (#temp_table) and are only visible to the session that created them. They automatically drop when the session ends or you explicitly drop them. Global temporary tables use double hash (##global_temp) and are visible to all sessions on the server. They persist until the last session referencing them disconnects.
For example, if I create #customer_data in my session, other users can't see it, but if I create ##shared_lookup, any session can access it. Local temp tables are perfect for storing intermediate results in stored procedures, while global temp tables work for sharing reference data across multiple concurrent sessions.
How to level up
- Global temp tables can create blocking issues if multiple processes try to create the same named table.
- Consider table variables (@table) for small datasets as an alternative to local temp tables for better performance.
Follow-up questions to expect
- What happens if two different sessions create local temp tables with the same name?
- How would you share data between sessions without using global temp tables?
- When would you choose a table variable over a local temporary table?
What is the difference between user-defined functions and stored procedures?
What they're really asking
This tests your understanding of database architecture and deployment patterns. The interviewer wants to see if you know when to use functions versus procedures and understand the trade-offs for performance and maintainability.
How you'll be scored
Lists basic differences without understanding when to use each or mentions incorrect limitations.
Correctly identifies key differences like return values and usage in queries but lacks practical application knowledge.
Explains differences clearly, discusses performance implications, and provides specific use cases for each approach.
How to structure your answer
- Define what each construct does at a high level.
- Compare key technical differences (return values, usage context, parameters)
- Discuss performance characteristics and query plan impact.
- Provide specific use cases for when to choose each.
Key points to hit
- Functions must return a value and can be used in SELECT statements, while stored procedures can have multiple OUT parameters but cannot be used directly in queries.
- Stored procedures can contain transaction control (COMMIT/ROLLBACK) while functions cannot modify database state in most systems.
- Functions are compiled and cached differently, often leading to better reusability but potential performance overhead in complex queries.
- Choose functions for calculations and transformations that need to be reused in queries, procedures for business logic workflows.
Common mistakes
- Confusing which construct can be used in SELECT statements or claiming both have identical performance characteristics.
- Not mentioning that functions typically cannot perform DML operations or manage transactions.
Sample answer
The main difference is that user-defined functions must return a value and can be used directly in SELECT statements and WHERE clauses, while stored procedures execute as standalone units and return results through OUT parameters or result sets.
Functions are great for reusable calculations like tax computations that you need in multiple queries, while procedures work better for complex business workflows that might involve multiple steps and transaction management.
Performance-wise, functions get compiled and cached but can create overhead if they're called row-by-row in large result sets, whereas procedures give you more control over execution flow and can manage their own transactions.
How to level up
- Discuss inline table-valued functions versus multi-statement functions and their performance differences.
- Mention how function determinism affects query optimization and caching strategies.
- Explain when function calls in WHERE clauses can prevent index usage.
Follow-up questions to expect
- Can you write a function that would be problematic for performance and explain why?
- How would you convert a slow scalar function into a more efficient approach?
- What happens to query plans when you use functions with side effects?
What are scalar functions vs table-valued functions?
What they're really asking
This tests your knowledge of function return types and their impact on query performance. The interviewer wants to see if you understand how different function types integrate with the query optimizer.
How you'll be scored
Confuses the types or provides incorrect examples of when to use each.
Correctly identifies that scalar returns single values while table-valued returns rows but misses performance implications.
Explains both types clearly with examples and discusses how each affects query execution plans and optimization.
How to structure your answer
- Define scalar functions and their single-value return behavior.
- Explain table-valued functions and their result set nature.
- Compare how each integrates with queries and joins.
- Discuss performance characteristics and optimization differences.
Key points to hit
- Scalar functions return a single value and can be used anywhere an expression is valid, including SELECT lists and WHERE clauses.
- Table-valued functions return a result set and can be used in FROM clauses like tables, enabling joins and complex queries.
- Inline table-valued functions often perform better because the optimizer can integrate their logic into the main query plan.
- Multi-statement table-valued functions create temporary result sets and may prevent certain optimizations like predicate pushdown.
Common mistakes
- Thinking table-valued functions can only return one column or not understanding that they can participate in joins.
- Not recognizing that scalar functions called for each row can create performance bottlenecks.
Sample answer
Scalar functions return a single value like a number or string, so you can use them in SELECT lists or WHERE conditions, similar to built-in functions like LEN() or GETDATE(). Table-valued functions return a set of rows and columns, so they go in your FROM clause and can be joined with other tables.
For example, I'd use a scalar function to calculate shipping costs based on weight and distance, but a table-valued function to return all orders for a customer within a date range.
The key performance difference is that inline table-valued functions let the optimizer merge their logic with your main query, while scalar functions often execute once per row which can be expensive on large datasets.
How to level up
- Explain the difference between inline and multi-statement table-valued functions in terms of query plan integration.
- Discuss how table-valued functions can accept parameters that affect their result sets.
- Mention when replacing scalar functions with JOINs to derived tables improves performance.
Follow-up questions to expect
- How would you optimize a query that calls a scalar function for every row in a million-row table?
- Can you show me when you'd use a table-valued function instead of a view?
- What are the security implications of different function types?
What is DBCC and what are its commonly used commands?
What they're really asking
This tests your knowledge of SQL Server administrative commands and database maintenance. The interviewer wants to see if you have production database experience and understand low-level database operations.
How you'll be scored
Doesn't know what DBCC stands for or provides incorrect command examples.
Knows DBCC is for database consistency checks and names a few commands but lacks practical usage knowledge.
Explains DBCC purpose clearly, provides specific commands with use cases, and discusses when you'd run them in production.
How to structure your answer
- Define what DBCC stands for and its general purpose.
- List the most commonly used DBCC commands with brief explanations.
- Explain when and why you'd use these commands in production.
- Mention any precautions or performance considerations.
Key points to hit
- DBCC stands for Database Console Commands and provides administrative utilities for checking database integrity and performance.
- DBCC CHECKDB validates the logical and physical integrity of all objects in a database and should be run regularly.
- DBCC SHOWCONTIG and DBCC INDEXDEFRAG help identify and resolve index fragmentation issues.
- Commands like DBCC FREEPROCCACHE and DBCC DROPCLEANBUFFERS are useful for testing but dangerous in production.
Common mistakes
- Confusing DBCC with DDL commands or not understanding that some DBCC commands can impact production performance.
- Recommending DBCC DROPCLEANBUFFERS or DBCC FREEPROCCACHE for production use without understanding the consequences.
Sample answer
DBCC stands for Database Console Commands, which are SQL Server utilities for database administration and troubleshooting. The most important one is DBCC CHECKDB, which validates your database integrity and should be part of regular maintenance schedules. DBCC SHOWCONTIG helps identify index fragmentation, while DBCC INDEXDEFRAG can fix fragmentation issues.
For performance testing, DBCC FREEPROCCACHE clears the plan cache and DBCC DROPCLEANBUFFERS clears the buffer pool, but you'd never run these in production because they'd kill performance. I've used DBCC CHECKDB weekly in maintenance windows and DBCC SHOWCONTIG to diagnose slow queries that turned out to be caused by heavily fragmented indexes.
How to level up
- Discuss the difference between DBCC CHECKDB, CHECKALLOC, and CHECKTABLE for targeted integrity checks.
- Explain how DBCC commands can be resource-intensive and need to be scheduled during maintenance windows.
- Mention DBCC SQLPERF for monitoring transaction log space usage.
Follow-up questions to expect
- How would you schedule DBCC CHECKDB for a 24/7 production system?
- What would you do if DBCC CHECKDB found corruption in a critical table?
- How do you balance the need for integrity checks with system performance?
What is a composite index with 3 columns? Will it be used if you only provide 2 columns in WHERE?
What they're really asking
This tests your understanding of composite index mechanics and the leftmost prefix rule. The interviewer wants to see if you can design effective indexing strategies and predict index usage patterns.
How you'll be scored
Doesn't understand composite indexes or incorrectly claims the index won't be used at all.
Knows about the leftmost prefix rule but can't explain partial index usage or optimization implications.
Explains leftmost prefix rule clearly, discusses partial index scans, and covers query plan implications with specific examples.
How to structure your answer
- Define what a composite index with 3 columns looks like structurally.
- Explain the leftmost prefix rule and how it determines index usage.
- Describe what happens when only 2 columns are provided in WHERE clause.
- Discuss query plan implications and optimization strategies.
Key points to hit
- A composite index on columns (A, B, C) is physically ordered first by A, then by B within each A value, then by C within each A,B combination.
- The leftmost prefix rule means the index can be used for queries filtering on (A), (A,B), or (A,B,C) but not (B,C) or (C) alone.
- If you provide only the first 2 columns in WHERE, the index will be used efficiently for those columns, effectively like having an index on (A,B)
- Column order in composite indexes should prioritize equality conditions first, then range conditions, based on query patterns and selectivity.
Common mistakes
- Thinking the index won't be used at all if you don't provide all 3 columns, or believing column order doesn't matter in composite indexes.
- Not understanding that range conditions on earlier columns prevent later columns from being used effectively in the index.
Sample answer
A composite index on 3 columns, let's say CREATE INDEX IX_Orders ON Orders(CustomerID, OrderDate, Status), creates a structure sorted first by CustomerID, then OrderDate within each customer, then Status.
Due to the leftmost prefix rule, this index will definitely be used if I query with just the first 2 columns like WHERE CustomerID = 123 AND OrderDate >= '2024-01-01'. The database can efficiently seek to CustomerID 123 and then scan through the OrderDate range within that customer's data.
It's essentially like having a separate index on (CustomerID, OrderDate). The third column Status won't help with filtering, but it could still provide covering benefits if Status is in the SELECT list.
How to level up
- Discuss how range conditions on middle columns can prevent later columns from being used effectively in the WHERE clause.
- Explain covering indexes and how including extra columns can eliminate key lookups even if they're not in WHERE.
- Mention how query hints like FORCESEEK can sometimes make the optimizer use partial composite indexes differently.
Follow-up questions to expect
- How would you decide the optimal column order for a composite index?
- What's the difference between a composite index and multiple single-column indexes for the same query?
- How does index intersection work and when might SQL Server use multiple indexes instead of one composite?
Ready to put this into practice?
Try these questions in a mock interview →Still applying for jobs? Let Auto Apply do it
Advanced Practical Challenges (10)
Return the top 3 creators in the US for the last full week, with total minutes and week-over-week comparison
What they're really asking
This tests your ability to combine advanced SQL concepts including CTEs, window functions, and date manipulation to solve a complex analytical problem. The interviewer wants to see if you can write maintainable queries for real-world reporting scenarios.
How you'll be scored
Attempts basic aggregation but fails to handle date truncation, week-over-week comparison, or ranking correctly.
Gets the basic ranking and aggregation right but struggles with the week-over-week comparison or has inefficient query structure.
Produces a clean CTE-based solution with proper date handling, accurate ranking, and efficient week-over-week comparison using window functions.
How to structure your answer
- Use date functions to identify the last full week boundary.
- Create CTEs to aggregate data by creator and week with proper filtering.
- Apply DENSE_RANK() to get top 3 creators by total minutes.
- Use LAG() window function to calculate week-over-week comparison.
- Handle edge cases like new creators with no previous week data.
Key points to hit
- Use DATEADD and DATEPART to calculate week boundaries, ensuring you get complete weeks rather than partial data.
- DENSE_RANK() handles ties better than ROW_NUMBER() for 'top 3' requirements where multiple creators might have the same total.
- LAG() with PARTITION BY creator ORDER BY week enables clean week-over-week calculations without self-joins.
- CTEs make the query readable by separating date logic, aggregation, ranking, and comparison steps.
Common mistakes
- Using ROW_NUMBER() instead of DENSE_RANK() which could exclude tied creators from the top 3.
- Incorrectly calculating week boundaries or not handling the 'last full week' requirement properly.
Sample answer
I'll start with a CTE to define the last full week, then aggregate by creator and week. Here's my approach: WITH WeekBounds AS (SELECT DATEADD(week, DATEDIFF(week, 0, GETDATE()) - 1, 0) AS LastWeekStart), CreatorWeekly AS (SELECT creator_id, DATEADD(week, DATEDIFF(week, 0, created_date), 0) as week_start, SUM(duration_minutes) as total_minutes FROM content WHERE country = 'US' AND created_date >= DATEADD(week, -2, (SELECT LastWeekStart FROM WeekBounds)) GROUP BY creator_id, DATEADD(week, DATEDIFF(week, 0, created_date), 0)), RankedCreators AS (SELECT creator_id, total_minutes, LAG(total_minutes) OVER (PARTITION BY creator_id ORDER BY week_start) as prev_week_minutes, DENSE_RANK() OVER (ORDER BY total_minutes DESC) as rank FROM CreatorWeekly WHERE week_start = (SELECT LastWeekStart FROM WeekBounds)) SELECT creator_id, total_minutes, prev_week_minutes, total_minutes - ISNULL(prev_week_minutes, 0) as wow_change FROM RankedCreators WHERE rank <= 3. This handles new creators gracefully and uses DENSE_RANK to ensure we get exactly 3 creators even with ties.
How to level up
- Consider partitioning strategies if this query runs on very large datasets, potentially pre-aggregating by week.
- Add error handling for edge cases like the first week of data where no previous week exists.
- Use query hints or indexed views if this becomes a frequently-run report with consistent date patterns.
Follow-up questions to expect
- How would you modify this query to handle different time zones for creators in different regions?
- What indexing strategy would you recommend to make this query perform well on a table with billions of rows?
- How would you extend this to show month-over-month comparisons instead of week-over-week?
Find all employees whose DOB is between 01/01/1960 and 31/12/1975, grouped by gender
What they're really asking
This tests your ability to combine date filtering with grouping functions. The interviewer wants to see if you understand date range filtering syntax and can properly aggregate data by categorical columns.
How you'll be scored
Gets the date format wrong or uses HAVING instead of WHERE for the date filter.
Writes a working query with correct DATE filtering and GROUP BY syntax.
Includes proper date formatting, mentions potential index on DOB for performance, and discusses NULL handling for gender column.
How to structure your answer
- Filter records using WHERE with date range.
- Group the filtered results by gender.
- Apply COUNT aggregate function.
- Consider date format and NULL handling.
- Mention performance implications.
Key points to hit
- Use WHERE clause for row-level filtering before grouping to reduce data early.
- Date literals need proper formatting (YYYY-MM-DD) or DATE() function depending on database.
- GROUP BY comes after WHERE in execution order, so filtering happens first.
- COUNT(*) counts all rows including NULLs, COUNT(column) excludes NULLs.
Common mistakes
- Using HAVING for date filtering instead of WHERE, which processes after grouping and hurts performance.
- Incorrect date format causing type conversion errors or wrong results.
Sample answer
I'd write SELECT gender, COUNT(*) FROM employees WHERE dob BETWEEN '1960-01-01' AND '1975-12-31' GROUP BY gender. This filters employees first by the date range, then groups by gender and counts each group. I'm using BETWEEN for readability and standard date format. If performance matters, an index on dob would help since we're filtering on it.
How to level up
- Consider adding ORDER BY gender for consistent result ordering.
- Discuss whether NULL gender values should be included or filtered out based on business requirements.
- Mention that BETWEEN is inclusive on both ends, so consider if end date should be '1975-12-31 23:59:59' for datetime columns.
Follow-up questions to expect
- What if some employees have NULL gender values?
- How would you optimize this query for a table with millions of records?
- Rewrite this using explicit date comparisons instead of BETWEEN.
Find employees whose name contains "Joe" regardless of case (JOE, Joe, joe)
What they're really asking
This tests your knowledge of case-insensitive string matching and SQL string functions. The interviewer wants to see if you understand different approaches to pattern matching and their performance implications.
How you'll be scored
Only shows one approach or gets the LIKE pattern syntax wrong.
Demonstrates UPPER/LOWER with LIKE or uses ILIKE if available.
Shows multiple approaches, discusses database-specific options, and mentions collation or index considerations.
How to structure your answer
- Choose case-insensitive approach.
- Apply string function to column.
- Use LIKE with wildcard patterns.
- Consider database-specific alternatives.
- Mention performance impact.
Key points to hit
- UPPER() or LOWER() functions make comparisons case-insensitive by normalizing case.
- LIKE uses % wildcards for pattern matching, so %joe% finds 'joe' anywhere in the name.
- Some databases offer ILIKE for case-insensitive matching without functions.
- Function on column prevents index usage unless there's a functional index.
Common mistakes
- Forgetting wildcards in LIKE pattern, which would only match exact strings.
- Not considering that functions on columns in WHERE clauses prevent standard index usage.
Sample answer
I'd use SELECT * FROM employees WHERE LOWER(name) LIKE '%joe%'. The LOWER function converts the name to lowercase, then LIKE with % wildcards finds 'joe' anywhere in the string. This catches JOE, Joe, joe, or even Joseph.
Some databases like PostgreSQL also support ILIKE which is case-insensitive by default, so I could write name ILIKE '%joe%' there.
How to level up
- Create a functional index on LOWER(name) if this type of search is frequent.
- Consider full-text search capabilities for more complex name matching requirements.
- Some databases support case-insensitive collations that make functions unnecessary.
Follow-up questions to expect
- How would you optimize this for better performance on a large table?
- What if you needed to find names that start with 'Joe' instead?
- How does this approach handle international characters and accents?
Create an empty table with the same schema as an existing table
What they're really asking
This tests whether you know the CREATE TABLE AS SELECT pattern and the WHERE 1=0 trick to copy structure without data. The interviewer wants to see if you understand schema copying techniques.
How you'll be scored
Suggests manually recreating the table structure or doesn't know the WHERE 1=0 pattern.
Uses CREATE TABLE AS SELECT with WHERE 1=0 correctly.
Explains why WHERE 1=0 works, mentions what gets copied vs what doesn't, and knows alternative approaches.
How to structure your answer
- Use CREATE TABLE AS SELECT syntax.
- Add WHERE 1=0 to exclude all rows.
- Explain why this copies structure only.
- Mention what constraints transfer.
- Consider alternative approaches.
Key points to hit
- CREATE TABLE AS SELECT copies both structure and data by default.
- WHERE 1=0 is always false, so no rows are selected but column structure remains.
- This approach copies column names, types, and nullability but not constraints like primary keys or foreign keys.
- Some databases have LIKE or specific structure-only syntax as alternatives.
Common mistakes
- Assuming all constraints and indexes transfer with this method.
- Not realizing that WHERE 1=0 is the key to getting structure without data.
Sample answer
I'd use CREATE TABLE new_table AS SELECT * FROM existing_table WHERE 1=0. The WHERE 1=0 condition is always false, so no rows get selected, but the SELECT * defines all the columns. This creates new_table with the same column names, data types, and null constraints as existing_table.
However, it won't copy primary keys, foreign keys, or indexes, so those would need to be added separately if needed.
How to level up
- Some databases support CREATE TABLE LIKE syntax which preserves more constraints.
- Consider using LIMIT 0 instead of WHERE 1=0 in databases where it's more explicit.
- Always verify what constraints and defaults transfer in your specific database system.
Follow-up questions to expect
- How would you also copy the primary key and indexes?
- What's the difference between this approach and CREATE TABLE LIKE?
- How would you copy just specific columns, not all columns?
Write a query where students' marks are greater than the average marks of all students
What they're really asking
This tests your understanding of subqueries and aggregate functions across different scopes. The interviewer wants to see if you can compare individual records against calculated aggregates.
How you'll be scored
Tries to use AVG() in the same query scope as individual student records without proper subquery structure.
Uses a subquery to calculate average and compares individual marks against it.
Explains why subquery is necessary, mentions query execution order, and considers performance implications of subquery evaluation.
How to structure your answer
- Calculate average marks in subquery.
- Compare each student's marks against the average.
- Use proper comparison operator.
- Consider subquery execution.
- Verify logic handles edge cases.
Key points to hit
- Subquery calculates single aggregate value that can be compared to individual rows.
- Main query filters students WHERE marks > (subquery result)
- Subquery executes once and returns scalar value for comparison.
- Cannot mix individual student data with overall average in same SELECT without subquery.
Common mistakes
- Trying to use AVG(marks) directly in WHERE clause alongside individual student columns.
- Using correlated subquery when simple subquery is sufficient and more efficient.
Sample answer
I'd write SELECT * FROM students WHERE marks > (SELECT AVG(marks) FROM students). The subquery calculates the overall average of all student marks first, returning a single number. Then the main query compares each individual student's marks against that average. The subquery only runs once, making this efficient. This finds all students performing above average.
How to level up
- Consider using window functions like AVG() OVER() if you also need to display the average in results.
- For large tables, ensure the marks column is indexed since it's used for both calculation and filtering.
- Think about NULL handling if some students have NULL marks.
Follow-up questions to expect
- How would you also show each student's marks compared to the average?
- What if you wanted students scoring in the top 25% instead of above average?
- How would this change if you wanted above-average students by class, not overall?
Find all employees who are also managers (self-referencing hierarchy)
What they're really asking
This tests your understanding of self-joins and hierarchical relationships in databases. The interviewer wants to see if you can navigate parent-child relationships within the same table.
How you'll be scored
Doesn't understand that manager information is in the same table or tries to use separate tables.
Uses self-join or EXISTS correctly to find employees who are also managers.
Shows multiple approaches, explains the hierarchy concept, discusses NULL handling for top-level managers, and considers performance.
How to structure your answer
- Identify the self-referencing relationship.
- Choose between self-join or EXISTS approach.
- Handle the logic for employees who are managers.
- Consider NULL values for top-level employees.
- Verify the query logic.
Key points to hit
- Self-referencing means employee table has manager_id pointing to another employee_id in same table.
- EXISTS checks if an employee's ID appears as someone else's manager_id.
- Self-join creates two instances of the same table with different aliases.
- Top-level managers typically have NULL manager_id values.
Common mistakes
- Confusing the direction of the relationship between employee and manager IDs.
- Not handling the case where top-level executives have NULL manager_id values.
Sample answer
I'd use SELECT * FROM employees e WHERE EXISTS (SELECT 1 FROM employees m WHERE m.manager_id = e.employee_id). This finds employees whose ID appears as a manager_id for someone else, meaning they manage other people. The EXISTS is efficient because it stops at the first match.
Alternatively, I could self-join with SELECT DISTINCT e.* FROM employees e INNER JOIN employees m ON e.employee_id = m.manager_id.
How to level up
- Consider indexing manager_id column since it's used for joins in hierarchical queries.
- Use DISTINCT with self-join approach to avoid duplicate rows when someone manages multiple people.
- Think about whether you want to include managers at different levels or just direct managers.
Follow-up questions to expect
- How would you find all employees who report to a specific manager, including indirect reports?
- What if you wanted to show each manager along with their direct report count?
- How would you handle the case where the hierarchy has multiple levels?
Find candidates who have ALL required skills (not just some)
What they're really asking
This tests relational division and set completeness logic. The interviewer wants to see if you understand how to use GROUP BY and HAVING to verify that one set completely contains another set, which is crucial for business rules like 'all requirements must be met.'
How you'll be scored
Uses EXISTS or multiple JOINs that don't actually verify completeness, or writes a query that returns candidates with ANY skills rather than ALL required skills.
Correctly uses GROUP BY candidate and HAVING COUNT to match the total number of required skills, with proper JOIN logic.
Demonstrates the relational division pattern with clear explanation, discusses why COUNT works for set completeness, and mentions edge cases like duplicate skills or NULL handling.
How to structure your answer
- Identify this as a relational division problem (finding records that match ALL items in a set)
- JOIN candidates to their skills, then to required skills to filter valid matches.
- GROUP BY candidate to collapse their skills into one row per candidate.
- Use HAVING COUNT to verify they have exactly the number of required skills.
- Consider edge cases like duplicate skills or candidates with extra skills.
Key points to hit
- Relational division requires GROUP BY on the 'many' side and HAVING COUNT to verify set completeness.
- The HAVING clause must count DISTINCT skills to handle potential duplicates in the data.
- JOIN order matters: candidate_skills JOIN required_skills ensures you only count skills that are actually required.
- This pattern works because GROUP BY collapses all of a candidate's required skills into one row, then COUNT verifies completeness.
Common mistakes
- Using COUNT without DISTINCT when the underlying data might have duplicate skill records per candidate.
- Forgetting to JOIN to required_skills table, which would count ALL candidate skills instead of only required ones.
Sample answer
I need to find candidates who have every required skill, which is a relational division problem. I'll SELECT c.candidate_id FROM candidates c JOIN candidate_skills cs ON c.id = cs.candidate_id JOIN required_skills rs ON cs.skill_id = rs.skill_id GROUP BY c.candidate_id HAVING COUNT(DISTINCT rs.skill_id) = (SELECT COUNT(*) FROM required_skills).
The key insight is that GROUP BY collapses each candidate's skills into one row, then HAVING COUNT verifies they have exactly the right number of required skills. I use DISTINCT in the COUNT to handle any duplicate skill records, and the subquery gives me the total number of skills each candidate must have.
How to level up
- Consider using a CTE to pre-calculate the required skills count if this query runs frequently, making the logic more readable.
- For very large datasets, ensure there's a composite index on (candidate_id, skill_id) in the candidate_skills table to optimize the JOIN and GROUP BY.
- If candidates can have skills beyond the required set, this query naturally handles that by only counting required skills through the JOIN condition.
Follow-up questions to expect
- How would you modify this to find candidates missing exactly one required skill?
- What if we wanted to rank candidates by how many required skills they have?
- How would the query change if skills had proficiency levels and we needed minimum proficiency?
Detect users with 3+ consecutive days of activity (streak detection)
What they're really asking
This tests window functions for sequential pattern detection and date arithmetic. The interviewer wants to see if you can identify streaks in time-series data using ROW_NUMBER partitioning and date difference logic, which is common in user engagement analytics.
How you'll be scored
Attempts to solve with self-JOINs or cursor-like logic, or writes a query that doesn't actually detect consecutive sequences.
Uses window functions like LAG/LEAD or ROW_NUMBER with date arithmetic to identify consecutive days, but may miss edge cases.
Demonstrates the ROW_NUMBER date difference technique to create streak groups, explains why this method works reliably, and discusses performance implications for large datasets.
How to structure your answer
- Recognize this as a gaps and islands problem requiring streak detection.
- Use ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY activity_date) to number consecutive days.
- Calculate the difference between activity_date and the row number to create streak groups.
- GROUP BY user and streak group, then filter for groups with 3+ days.
- Consider timezone handling and what constitutes 'consecutive days'
Key points to hit
- The ROW_NUMBER date difference technique works because consecutive dates will have the same difference value when you subtract the row number.
- PARTITION BY user_id in the window function ensures each user's streaks are calculated independently.
- Using DATE arithmetic (activity_date - ROW_NUMBER()) creates consistent group identifiers for each streak period.
- Filter with HAVING COUNT(*) >= 3 after grouping to find only users with streaks of 3 or more days.
Common mistakes
- Using LAG/LEAD without proper logic to handle the transition between streaks, which can miss or incorrectly merge separate streaks.
- Forgetting to handle the case where a user might have multiple separate 3-day streaks in the dataset.
Sample answer
This is a classic gaps and islands problem for detecting consecutive sequences. I'll use WITH streak_groups AS (SELECT user_id, activity_date, activity_date - ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY activity_date) AS streak_group FROM user_activity) SELECT user_id FROM streak_groups GROUP BY user_id, streak_group HAVING COUNT(*) >= 3.
The magic happens in the ROW_NUMBER date arithmetic: consecutive dates will have identical values when you subtract their row number, creating natural groupings for each streak. Then I group by user and streak group to count days per streak, filtering for 3+ day streaks.
How to level up
- For timestamp data instead of dates, convert to DATE first to ensure you're measuring calendar days rather than 24-hour periods.
- Consider adding the actual streak start and end dates to the SELECT if the business needs to know when these engagement periods occurred.
- Index on (user_id, activity_date) will optimize both the window function ordering and the final grouping operations.
Follow-up questions to expect
- How would you modify this to return the longest streak per user instead of just users with 3+ day streaks?
- What if we wanted to find users with streaks that include weekends vs only weekdays?
- How would you handle time zones if users are global and activity_date is stored in UTC?
Calculate 3-day rolling average of a metric per user
What they're really asking
This tests window functions with frame specifications for moving calculations. The interviewer wants to see if you understand ROWS BETWEEN syntax for defining rolling windows and can partition data correctly for per-user calculations, which is essential for time-series analytics.
How you'll be scored
Attempts self-JOINs or subqueries instead of window functions, or writes a window function without proper frame specification that doesn't actually calculate a rolling average.
Uses window functions with correct PARTITION BY user and frame specification, but may not explain why ROWS BETWEEN is necessary or handle edge cases.
Demonstrates proper window function syntax with frame bounds, explains the difference between ROWS and RANGE, discusses handling of insufficient data periods, and mentions performance considerations.
How to structure your answer
- Identify this as a moving window calculation requiring window functions.
- Set up PARTITION BY user_id to calculate rolling averages independently per user.
- Use ROWS BETWEEN 2 PRECEDING AND CURRENT ROW to define the 3-day window.
- Apply AVG() as the window function to calculate the rolling average.
- Consider how to handle users with fewer than 3 days of data.
Key points to hit
- ROWS BETWEEN 2 PRECEDING AND CURRENT ROW creates exactly a 3-row window (current + 2 previous = 3 days)
- PARTITION BY user_id ensures each user's rolling average is calculated independently without mixing users' data.
- Window functions preserve all original rows while adding calculated columns, unlike GROUP BY which reduces rows.
- The frame specification is crucial: without ROWS BETWEEN, the default frame would include all rows from partition start to current row.
Common mistakes
- Using RANGE instead of ROWS, which can give unexpected results when there are duplicate dates or gaps in the time series.
- Forgetting the frame specification entirely, which defaults to RANGE UNBETWEEN UNBOUNDED PRECEDING AND CURRENT ROW instead of the desired 3-day window.
Sample answer
I'll use a window function with a frame specification: SELECT user_id, metric_date, metric_value, AVG(metric_value) OVER (PARTITION BY user_id ORDER BY metric_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as rolling_3day_avg FROM user_metrics ORDER BY user_id, metric_date.
The PARTITION BY user_id keeps each user's calculations separate, while ROWS BETWEEN 2 PRECEDING AND CURRENT ROW creates exactly a 3-row sliding window.
For the first two days per user, this will calculate the average of available data, so day 1 gets a 1-day average and day 2 gets a 2-day average before we get true 3-day averages from day 3 onward.
How to level up
- If you need exactly 3 days of data before showing results, add a WHERE clause filtering for ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY metric_date) >= 3.
- Consider using RANGE BETWEEN if your data has gaps and you want calendar-based windows rather than row-based windows.
- An index on (user_id, metric_date) will optimize the window function's partitioning and ordering operations.
Follow-up questions to expect
- How would you modify this to calculate both 3-day and 7-day rolling averages in the same query?
- What if you wanted to exclude weekends from the rolling average calculation?
- How would you handle NULL values in the metric_value column within the rolling average?
Identify customers who purchased from EVERY product category (division query)
What they're really asking
This tests relational division for universal quantification in SQL. The interviewer wants to see if you can solve 'for all' problems using GROUP BY and HAVING COUNT, demonstrating understanding of how to verify complete set membership across related entities.
How you'll be scored
Uses multiple EXISTS subqueries or attempts complex JOINs that don't actually verify the customer purchased from ALL categories, often returning customers who bought from ANY category.
Correctly applies the GROUP BY customer, HAVING COUNT pattern to match total category count, with proper JOIN logic to connect purchases to categories.
Explains the relational division approach clearly, discusses why COUNT works for universal quantification, mentions potential issues like empty categories or multiple purchases per category, and suggests indexing strategies.
How to structure your answer
- Recognize this as relational division: finding customers where their purchase categories equal ALL available categories.
- JOIN customers through purchases to product categories to get customer-category pairs.
- GROUP BY customer_id to consolidate each customer's category purchases.
- Use HAVING COUNT(DISTINCT category_id) = total number of categories to verify completeness.
- Handle edge cases like categories with no products or customers with multiple purchases per category.
Key points to hit
- Relational division uses GROUP BY on the entity being tested and HAVING COUNT to verify they match ALL items in the reference set.
- DISTINCT in COUNT handles cases where customers made multiple purchases within the same category.
- The total category count can be a subquery or hardcoded constant, depending on whether categories change frequently.
- This approach naturally handles customers who purchased from additional categories beyond the required set.
Common mistakes
- Forgetting DISTINCT in the COUNT, which would overcount customers who made multiple purchases in the same category.
- Not properly joining through the product table to get categories, instead trying to compare purchases directly to categories.
Sample answer
This is another relational division problem where I need to verify customers purchased from ALL categories. I'll write SELECT c.customer_id FROM customers c JOIN purchases p ON c.customer_id = p.customer_id JOIN products pr ON p.product_id = pr.product_id GROUP BY c.customer_id HAVING COUNT(DISTINCT pr.category_id) = (SELECT COUNT(*) FROM categories).
The key insight is that GROUP BY customer_id collapses all their purchases into one row per customer, then HAVING COUNT(DISTINCT category_id) verifies they hit every category. I use DISTINCT because a customer might buy multiple products from the same category, and I only want to count each category once per customer.
How to level up
- Consider adding a WHERE clause to filter by date range if you want customers who purchased from all categories within a specific time period.
- For better performance on large datasets, ensure there are indexes on the JOIN columns: (customer_id) on purchases and (product_id) on purchases and products.
- If categories can be empty (no products), you might want to modify the query to only consider categories that actually have purchasable products.
Follow-up questions to expect
- How would you modify this to find customers who purchased from at least 80% of all categories?
- What if we wanted to see which specific categories each qualifying customer purchased from?
- How would you extend this to find customers who purchased from all categories within the last 6 months?
Frequently Asked Questions
What SQL topics are most important for interviews?
How do SQL interview questions differ for data analysts versus engineers?
Should I learn a specific SQL dialect for interviews?
How should I practice writing SQL queries for interviews?
What are window functions and why are they important for interviews?
How can I practice SQL interview questions?
Do I need to know database design for SQL interviews?
Stop Preparing in Your Head. Start Practicing Out Loud.
Drop your resume, add a job description, and get a mock interview like the real thing.
Start Free Mock Interview →Still applying for jobs? Let Auto Apply do it for you.