To master SQL queries asked in interview questions, you must focus on three core areas: joining multiple tables, aggregating data with filters, and using window functions to perform complex calculations across sets of rows. Success in a technical interview requires not just the ability to write code that runs, but the ability to explain the time and space complexity of your query and why you chose a specific join or filter over another. This guide provides a structured approach to preparing for these assessments, moving from basic data retrieval to advanced analytical queries.
What You'll Need
- A SQL environment for practice (such as PostgreSQL, MySQL, or SQL Server).
- A sample dataset (like the Northwind or Employee database) to run queries against.
- A basic understanding of relational database concepts, such as Primary Keys and Foreign Keys.
- A whiteboard or digital notepad to sketch out logic before writing code.
Step-by-Step
-
Master the Basic Selection and Filtering: Start by practicing the fundamental
SELECT,FROM, andWHEREclauses. Interviewers often start with a "warm-up" question to see if you understand basic filtering. Practice using operators likeLIKEfor pattern matching,INfor multiple values, andBETWEENfor ranges. For example, be comfortable writing a query that finds all employees hired between two dates whose names start with a specific letter. -
Perfect Your Join Logic: Joins are the most frequently tested area of SQL interviews. You must be able to explain the difference between an
INNER JOIN,LEFT JOIN,RIGHT JOIN, andFULL OUTER JOIN. Practice scenarios where you need to find "missing" data—for instance, finding customers who have never placed an order. This typically requires aLEFT JOINwhere the right table's primary keyIS NULL. Ensure you understand how to join more than two tables in a single query and how to handle ambiguous column names using aliases. -
Implement Aggregations and Grouping: Learn to use
COUNT(),SUM(),AVG(),MIN(), andMAX()in conjunction withGROUP BY. A critical distinction to master is the difference betweenWHEREandHAVING. Remember thatWHEREfilters rows before aggregation, whileHAVINGfilters the results after theGROUP BYhas been applied. Practice a query that finds departments with an average salary higher than a specific threshold; this will force you to use bothGROUP BYandHAVING. -
Learn Window Functions for Advanced Analytics: Modern SQL interviews almost always include window functions. Focus on
ROW_NUMBER(),RANK(),DENSE_RANK(), andLEAD/LAG. These allow you to perform calculations across a set of table rows that are related to the current row. For example, practice the "Nth highest salary" problem. While this can be done withOFFSET, usingDENSE_RANK()within a Common Table Expression (CTE) is the professional standard because it handles ties correctly. -
Utilize Common Table Expressions (CTEs) and Subqueries: When a query becomes too complex for a single block, use a CTE (the
WITHclause) to break the logic into readable steps. Interviewers value readability and maintainability. Practice converting a nested subquery into a CTE to see how it improves the flow of the logic. Be prepared to discuss when a subquery might be more efficient than a join, though in most modern optimizers, the difference is negligible. -
Handle Nulls and Data Cleaning: Real-world data is messy. Practice using
COALESCE()to provide default values for nulls andCASE WHENstatements to create conditional logic within your results. A common interview question involves transforming a column of codes (e.g., 'M', 'F', 'O') into readable labels ('Male', 'Female', 'Other') using aCASEstatement. -
Optimize for Performance: Once you have a working query, the interviewer will often ask, "How would you make this faster?" Study the impact of indexing on query performance. Understand that avoiding
SELECT *and reducing the use of wildcards at the beginning of aLIKEpattern (which prevents index usage) are key optimization strategies. Be able to explain how an Execution Plan helps identify bottlenecks like table scans.
Common Mistakes
One of the most frequent errors is confusing RANK() and DENSE_RANK(). RANK() leaves gaps in the sequence if there are ties (e.g., 1, 2, 2, 4), whereas DENSE_RANK() does not (e.g., 1, 2, 2, 3). Using the wrong one in a "Top N" query can lead to incorrect results. Another common mistake is forgetting to include non-aggregated columns in the GROUP BY clause, which will cause an error in most SQL dialects like PostgreSQL and SQL Server.
Many candidates also struggle with the logic of NOT IN when the subquery returns a NULL value. In SQL, if a subquery used with NOT IN returns even one NULL, the entire expression evaluates to unknown, and no rows are returned. The safer alternative is to use NOT EXISTS, which handles nulls more predictably. Finally, avoid over-complicating the query; if a simple INNER JOIN works, do not use a complex subquery just to appear more advanced.
Tips
Always talk through your thought process. The interviewer is more interested in how you approach the problem than the exact syntax. If you forget the specific name of a function, describe what the function should do (e.g., "I would use a function here to truncate the date to the first of the month"). This shows you have the conceptual knowledge even if you have a momentary syntax lapse.
Before writing any code, clarify the requirements. Ask questions like: "Are there duplicate records in this table?", "Can the salary column contain null values?", or "Should I include employees who haven't been assigned to a department?" Clarifying these edge cases prevents you from writing a query that fails on a technicality and demonstrates your attention to detail.
Practice writing queries on a whiteboard or in a plain text editor without auto-complete. In many interviews, you won't have the luxury of an IDE that highlights your errors. This forces you to be more intentional with your syntax and helps you memorize the structure of complex clauses like window functions and CTEs.
Troubleshooting
If your query is returning more rows than expected, the first thing to check is your JOIN conditions. You may have a "many-to-many" relationship that is causing a Cartesian product, or you might be using a LEFT JOIN where an INNER JOIN was required. Check if you have joined on all necessary keys (composite keys) rather than just a single ID.
If your query is returning no results when you expect some, check for NULL values in your WHERE clause. Remember that column = NULL will never be true; you must use column IS NULL. Also, verify that your join keys have matching data types and that there are no trailing spaces in the string columns that might be preventing matches.
When you encounter a syntax error, read the error message carefully. Most SQL engines tell you exactly where the error is (e.g., "Error at line 4, position 12"). If the error is related to grouping, ensure every column in your SELECT list is either wrapped in an aggregate function or listed in the GROUP BY clause. If the query is running too slowly, try breaking it into smaller CTEs to isolate which part of the logic is causing the performance hit.
Frequently Asked Questions
What is the difference between WHERE and HAVING?
WHERE is used to filter individual rows before any grouping occurs. HAVING is used to filter groups created by the GROUP BY clause based on an aggregate condition.
When should I use a CTE instead of a subquery?
Use a CTE when the logic is complex, when you need to reference the same temporary result set multiple times in a query, or when you want to improve the readability of the code for other developers.
What is a self-join and when is it used?
A self-join is when a table is joined with itself. It is commonly used for hierarchical data, such as an employee table where one column contains the employee ID and another contains the manager's ID, who is also an employee in the same table.
How do I find the second highest value in a column?
The most robust way is using DENSE_RANK() in a CTE to rank values in descending order and then selecting the row where the rank equals 2. This ensures that if there are multiple people tied for the highest salary, you still get the actual second-highest value.
What is the difference between UNION and UNION ALL?
UNION combines the result sets of two queries and removes duplicate rows, which requires an internal sorting operation. UNION ALL combines the results but keeps all duplicates, making it significantly faster.
How does an index speed up a query?
An index creates a sorted pointer system (usually a B-Tree) that allows the database engine to find specific rows without scanning every single page of the table, similar to how an index at the back of a book helps you find a topic quickly.