Introduction to SQL Subqueries
Quick Answer
SQL subqueries are queries nested inside another SQL query. They allow you to perform complex data retrieval by embedding one query within another, enabling filtering, comparison, and aggregation based on dynamic results.
Learning Objectives
- Understand what a subquery is and why it is useful.
- Identify different types of subqueries in SQL.
- Write basic SQL queries using subqueries for filtering and comparison.
Introduction
SQL subqueries are a powerful feature that allows you to embed one query inside another. This enables you to perform operations that depend on the results of another query.
Understanding subqueries is essential for writing efficient and readable SQL code, especially when dealing with complex data retrieval scenarios.
Think of subqueries as queries within queries, unlocking powerful data insights.
What is a Subquery?
A subquery is a SQL query nested inside another SQL query. It is enclosed in parentheses and can return a single value, a list of values, or a table.
Subqueries allow you to use the result of one query as input for another, enabling dynamic and flexible data retrieval.
- Can be placed in SELECT, FROM, WHERE, or HAVING clauses.
- Executed first before the outer query.
- Helps in filtering, comparison, and aggregation based on dynamic data.
Types of Subqueries
Subqueries come in different types depending on their usage and the kind of result they return.
- Scalar Subquery: Returns a single value.
- Row Subquery: Returns a single row with one or more columns.
- Table Subquery: Returns multiple rows and columns.
- Correlated Subquery: References columns from the outer query and is evaluated repeatedly.
- Non-correlated Subquery: Independent of the outer query and evaluated once.
Using Subqueries in SQL
Subqueries can be used in various parts of an SQL statement to enhance query capabilities.
- In the WHERE clause to filter rows based on another query's results.
- In the FROM clause to create a derived table for further querying.
- In the SELECT clause to compute values dynamically.
Example: Subquery in WHERE Clause
This example finds employees who work in departments located in 'New York'.
Example: Subquery in FROM Clause
This example uses a subquery to calculate average salaries per department and then selects departments with average salary above a threshold.
Practical Example
This query selects employees who belong to departments located in New York by using a subquery in the WHERE clause.
This query calculates average salaries per department using a subquery in the FROM clause and filters departments with average salary above 70000.
Examples
SELECT employee_name
FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
WHERE location = 'New York'
);This query selects employees who belong to departments located in New York by using a subquery in the WHERE clause.
SELECT department_id, avg_salary
FROM (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) AS dept_avg
WHERE avg_salary > 70000;This query calculates average salaries per department using a subquery in the FROM clause and filters departments with average salary above 70000.
Best Practices
- Use subqueries to simplify complex queries by breaking them into smaller parts.
- Avoid unnecessary subqueries that can be replaced with JOINs for better performance.
- Use correlated subqueries carefully as they can impact query performance.
- Test subqueries independently to ensure correctness before embedding them.
Common Mistakes
- Using subqueries that return multiple rows where a single value is expected.
- Overusing correlated subqueries leading to slow query execution.
- Not aliasing subqueries in the FROM clause, causing syntax errors.
- Ignoring alternative approaches like JOINs when appropriate.
Hands-on Exercise
Write a Subquery to Find High Salary Employees
Write an SQL query to find employees whose salary is above the average salary of all employees using a subquery.
Expected output: List of employees earning more than the average salary.
Hint: Use a subquery in the WHERE clause to calculate the average salary.
Use a Subquery in the FROM Clause
Write a query that uses a subquery in the FROM clause to find departments with more than 5 employees.
Expected output: Departments having more than 5 employees.
Hint: Count employees per department in the subquery, then filter in the outer query.
Interview Questions
What is a subquery in SQL?
InterviewA subquery is a query nested inside another SQL query, used to perform operations that depend on the results of the inner query.
What is the difference between correlated and non-correlated subqueries?
InterviewA correlated subquery references columns from the outer query and is evaluated for each row, while a non-correlated subquery is independent and evaluated once.
Where can subqueries be used in SQL statements?
InterviewSubqueries can be used in SELECT, FROM, WHERE, and HAVING clauses.
MCQ Quiz
1. What is the best first step when learning Introduction to Subqueries?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Introduction to Subqueries?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. SQL subqueries are queries nested inside another SQL query.
B. Introduction to Subqueries never needs examples
C. Introduction to Subqueries is unrelated to practical work
D. Introduction to Subqueries should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- Subqueries are queries nested inside other queries to perform complex data retrieval.
- They can be used in SELECT, FROM, WHERE, and HAVING clauses.
- Subqueries help break down complex queries into manageable parts.
- SQL subqueries are queries nested inside another SQL query.
- They allow you to perform complex data retrieval by embedding one query within another, enabling filtering, comparison, and aggregation based on dynamic results.
Summary
SQL subqueries allow you to embed one query inside another to perform complex data retrieval tasks.
They can be used in various clauses like WHERE, FROM, and SELECT to filter, compare, or compute values dynamically.
Understanding subquery types and best practices helps write efficient and readable SQL queries.
Frequently Asked Questions
Can subqueries return multiple rows?
Yes, subqueries can return multiple rows, especially when used in the FROM clause or with operators like IN.
Are subqueries always the best solution?
Not always. Sometimes JOINs or other SQL constructs can perform better and be more readable than subqueries.
What is a correlated subquery?
A correlated subquery is a subquery that references columns from the outer query and is executed once per row of the outer query.





