The Complete Guide to Mastering Subquery SQL Interview Questions

Today, we’ll look at the 30 most important SQL query interview questions and ideas that you need to know before your SQL coding interview.

Last summer we published the ultimate guide to the SQL Interview Questions You Must Prepare. In it, we covered all the SQL areas that are, from our experience, required by the interviewers. These, along with coding, include theoretical knowledge about SQL and databases.

Now we will concentrate only on coding skills. It’s kind of like a follow-up to the ultimate guide we talked about above, but this one is only about writing SQL queries.

This one skill will be broken down into six separate technical ideas that will be used to solve 30 business problems.

Starting with the simplest questions, we’ll add one idea to the ones that came before it. Finally, we’ll look at the most difficult questions that include most or all of the ideas at once. With five questions in each category, this means covering 30 SQL query interview questions.

Subqueries are one of the most powerful yet tricky concepts in SQL. As an aspiring database professional you can expect subquery questions to feature prominently in technical interviews.

In this comprehensive guide, I’ll walk you through everything you need to know to tackle subquery SQL interview questions and impress interviewers with your mastery of this complex SQL feature.

What are Subqueries in SQL?

A subquery is an SQL query nested within another SQL query It allows you to perform operations on data sets retrieved by the outer query.

Subqueries enable you to

  • Simplify complex SQL operations by breaking them into smaller, more manageable components
  • Retrieve data from multiple tables in a single command
  • Filter and manipulate data dynamically based on values calculated by another query

With subqueries, you can achieve in one line of code what would otherwise require multiple steps of logic across queries. This power and flexibility makes subqueries an indispensable tool for any SQL developer.

Now let’s look at some common subquery interview questions and how to tackle them like a pro!

Top Subquery SQL Interview Questions and Answers

Q1. Explain the Difference Between Subqueries and Joins

Answer: The key difference is that subqueries allow you to perform multi-step operations in a single query, while joins combine data from multiple tables in one go.

Subqueries are best for:

  • Filtering or calculating values needed for the outer query
  • Complex logic across queries
  • Queries involving unlinked data

Joins are better when:

  • Direct relationships exist between tables
  • You want to retrieve data from multiple tables simultaneously
  • Performance is critical
  • Subqueries simplify complex, multi-step SQL operations
  • Joins efficiently combine directly related data

Q2. When Would Subqueries be More Efficient Than Joins?

Answer: Subqueries can outperform joins when:

  • You need to filter or manipulate data before joining it. For example, calculating averages or finding top customers.

  • Tables lack direct relationships. Subqueries can retrieve data from unrelated tables.

  • You want to avoid joining large tables just to filter a few rows. Subqueries can operate on subsets.

  • Query logic involves multi-step calculations or aggregations. Subqueries modularize operations.

So subqueries shine for complex logic, unlinked data, or when operating on subsets before joining.

Q3. Explain Correlated vs Non-Correlated Subqueries

Answer:

  • Non-correlated subqueries execute once before the outer query. They are self-contained and don’t depend on the outer query.

  • Correlated subqueries execute once for each row processed by the outer query. They reference values from the outer query’s rows.

For example, a non-correlated subquery calculates average salary just once:

sql

SELECT name FROM employeesWHERE salary > (SELECT AVG(salary) FROM employees)

A correlated subquery recalculates the average for each employee:

sql

SELECT nameFROM employees outerWHERE salary > (SELECT AVG(salary)                FROM employees inner               WHERE inner.dept = outer.dept)

So correlated subqueries rerun for every row, making them slower on large data sets.

Q4. How Can You Improve Subquery Performance?

Answer: Optimization strategies include:

  • Switch to joins where possible as they are faster

  • Use EXISTS over IN for existence checks

  • Avoid correlated subqueries which require row-by-row processing

  • Break complex subqueries into smaller, simpler components

  • Ensure tables have optimal indexes, especially on join/where columns

  • Check execution plans to identify inefficient operations

  • Monitor server load to rule out external factors

Q5. When Would You Use a Subquery in SELECT vs WHERE?

Answer:

In SELECT: When you want to return a calculated value or aggregate result:

sql

SELECT name,        (SELECT AVG(salary) FROM employees) AS avg_salary FROM employees

In WHERE: To filter rows based on a condition using a subquery:

sql

SELECT nameFROM employeesWHERE salary > (SELECT AVG(salary) FROM employees) 

So:

  • SELECT to return calculated columns
  • WHERE to filter rows

This distinguishes their uses cases clearly.

Q6. Can You Provide an Example of a Subquery in INSERT, UPDATE, DELETE?

Answer:

INSERT: Insert records using a subquery:

sql

INSERT INTO managers (name, dept)SELECT name, dept FROM employeesWHERE level = 'Manager'

UPDATE: Update values based on a subquery condition:

sql

UPDATE employees SET salary = salary * 1.1WHERE dept IN (SELECT dept                FROM departments                WHERE headcount < 10)

DELETE: Delete rows not meeting subquery criteria:

sql

DELETE FROM order_items WHERE order_id NOT IN (SELECT id FROM orders WHERE year > 2020)

The key is using subquery results in the WHERE clause to determine inserts, updates, and deletes.

Q7. How Do You Handle a Subquery Returning NULL?

Answer: To handle NULL results from a subquery:

  • Use IS NULL to check if the subquery result is NULL

  • Use COALESCE to replace NULL with a default value

For example:

sql

SELECT COALESCE(  (SELECT col FROM tab WHERE cond),   0))

Properly handling NULLs avoids unexpected query behavior.

Q8. Write a Subquery to Find the Nth Highest Salary

Answer: We can find the Nth highest salary using ORDER BY and OFFSET in a subquery:

sql

SELECT salaryFROM employeesORDER BY salary DESCOFFSET n-1 ROWS FETCH FIRST 1 ROW ONLY

Where n is the Nth highest salary we want.

The OFFSET skips the first n-1 rows, while FETCH FIRST 1 row ONLY returns the Nth row – giving us the Nth highest salary cleanly in a subquery.

Q9. Explain Different Types of Subqueries

Answer: The main subquery types are:

  • Single-row – Returns one column value from the inner SELECT

  • Multiple-row – Returns multiple rows using IN, ANY, or ALL

  • Correlated – Dependent on and executed once per outer query row

  • Non-correlated – Self-contained, execute once before outer query

  • Nested – A subquery within another subquery

Understanding the subtype determines how you can use the subquery result in the outer query.

Q10. When Would You Use Subqueries in HAVING vs WHERE?

Answer:

WHERE filters rows before aggregation.

HAVING filters aggregated results.

For example:

sql

SELECT year, SUM(revenue) AS total_revenueFROM financeWHERE revenue > 1000 -- Filter before groupingGROUP BY yearHAVING total_revenue > 1000000 -- Filter after aggregation

So use:

  • WHERE to filter raw rows before aggregation
  • HAVING to filter based on aggregated results

This illustrates the difference in their filter contexts.

Putting it All Together

Mastering subquery SQL interview questions requires understanding:

  • How subqueries differ from joins
  • Various subquery types and use cases
  • Performance optimization strategies
  • Techniques to handle NULLs and duplicates
  • Using subqueries across INSERT, UPDATE, DELETE, SELECT
  • Filtering context of WHERE vs HAVING

I hope these examples and explanations have equipped you to handle any subquery question thrown your way. Use this guide to gain confidence and stand out in your next technical interview!

SQL Query Interview Question #20: Common Friends Friend

This is a hard question by Google, but give it a try.

Find the number of a users friends friend who are also the users friend. Output the user id along with the count. Table : google_friends_network.

Link to the question: https://platform.stratascratch.com/coding/9821-common-friends-friend

To solve this question, again use the CTE. This time, it will consist of two SELECT statements and you’ll merge their results using the UNION. That way, you get users and their friends, which is something we did in one of the questions above.

Once you write the CTE, use the COUNT() function to find the number of friends. This will be a bit more complex query that will use subquery in the FROM clause. There will be three references to the CTE in the subquery. This means that the CTE will be self-joined and then grouped by user ID.

Here’s what you get if the solution is correct.

All required columns and the first 5 rows of the solution are shown

user_id n_friends
0 5
1 4
2 2
3 2
5 3

subquery sql interview questions

There are some useful functions in the SQL window that come in handy when you need to see both grouped and ungrouped data at the same time. They share some similarities with the aggregate functions. However, the SQL aggregate functions lose the individual rows while the window functions don’t.

SQL Query Interview Question #26: Combine the First and Last Names of Workers

When working with text data, one of the most common things you may be asked to do is join two or more table columns together. Here’s what exactly Amazon wants you to do.

Combine the first and last names of workers with a space in-between in a column full_name.Table : worker

Link to the question: https://platform.stratascratch.com/coding/9834-combine-the-first-and-last-names-of-workers

The table at your disposal is worker.

worker_id first_name last_name salary joining_date department
1 Monika Arora 100000 2014-02-20 HR
2 Niharika Verma 80000 2014-06-11 Admin
3 Vishal Singhal 300000 2014-02-20 HR
4 Amitah Singh 500000 2014-02-20 Admin
5 Vivek Bhati 500000 2014-06-11 Admin

You see they want you to put the employee’s first and last name in one column. Here’s how you do it:

Select the employee’s first name, then follow it up with two vertical lines ||. What follows after that will be concatenated with the first name. We put the blank space between single quotation marks because we want it to come after the first name. After that again comes the sign for concatenation, and then the employee’s last name.

This will give their names in the new column full_name.

All required columns and the first 5 rows of the solution are shown

full_name
Monika Arora
Niharika Verma
Vishal Singhal
Amitah Singh
Vivek Bhati

SQL Interview Question # 10 – What is a Sub Query?

FAQ

What is subquery in SQL interview questions?

A subquery is a query that is embedded within another query. It retrieves data used in the main query as a filter or a condition. Syntax: SELECT column1, column2 FROM table1 WHERE column3 IN (SELECT column3 FROM table2 WHERE condition);

What is subquery in SQL with examples?

Subqueries (also known as inner queries or nested queries) are a tool for performing operations in multiple steps. For example, if you wanted to take the sums of several columns, then average all of those values, you’d need to do each aggregation in a distinct step.

What is the best practice for subqueries in SQL?

The best practice is to avoid unnecessary subqueries that can make your query harder to read, debug, or optimize. For example, instead of using a subquery to filter data based on a maximum or minimum value, you can use a join with a GROUP BY and a HAVING clause.

What interview questions are related to joins and subqueries in SQL?

Here are 50 interview questions related to Joins and Subqueries in SQL: 1. What is an SQL JOIN, and why is it important in database queries? Answer: An SQL JOIN is used to combine rows from two or more tables based on a related column between them. It’s crucial for retrieving data from multiple tables. 2.

What is a subquery in a SQL interview?

In the dynamic realm of SQL databases, subqueries remain a cornerstone for complex data retrieval and manipulation. As you step into the interview spotlight, showcasing your mastery of subqueries can be a game-changer.

How to use a subquery in SQL?

In order to use a subquery, there are a couple of syntactical rules that need to be followed: Example SQL interview question using a nested subquery Suppose you are given the following table showing company sales: Table: sales_info

Should I test subqueries before integrating them into larger queries?

Always test subqueries separately before integrating them into larger queries to ensure accuracy. Prepare for your next SQL interview with our comprehensive guide on Subquery interview questions and answers. Enhance your knowledge and boost your confidence in tackling SQL subqueries.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *