SQL Subquery - A Comprehensive Guide - DataCamp
SQL Subquery - A Comprehensive Guide - DataCamp
Allan Ouko
Data Science Technical Writer
TO P I C S
SQL
Data Analysis
Data Engineering
SQL subqueries are a powerful tool in database management, allowing for more complex
and efficient data retrieval. This guide will walk you through the fundamentals of SQL
subqueries, offering insights into their practical applications and advanced techniques.
Whether you're a beginner or an experienced professional, mastering subqueries can
significantly enhance your SQL skills.
For those new to SQL, consider starting with our Intermediate SQL course to build a strong
foundation. Also, I find the SQL Basics Cheat Sheet, which you can download, is a helpful
reference because it has all the most common SQL functions. Finally, I want to say that
subqueries are a common SQL interview question, so if you are preparing for an interview,
you've come to the right place for a review.
A SQL subquery is a query nested within another SQL query, used to perform operations
that require multiple steps or complex logic. The role of subqueries in SQL include the
following:
Buy Now
Filtering records based on data from related tables.
Conditionally selecting rows without requiring explicit joins or external code logic.
It sounds like a lot, but it will make sense as we explore these things in the tutorial.
Types of subqueries
It might surprise you to learn that there are different types of subqueries. The different types
are grouped based on and suited to different kinds of data retrieval needs. You can choose
from the following subqueries depending on the operation you want to perform:
[Link] 1/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
Scalar subqueries
Scalar subqueries return a single value, such as one row and one column. They are often
used where a single value is expected, such as in calculations, comparisons, or assignments
in SELECT or WHERE clauses.
In the example below, the scalar subquery (SELECT AVG(salary) FROM employees) returns
a single value, the average salary, and compares it to each employee's salary.
Column subqueries
Column subqueries return a single column but multiple rows. These subqueries are often
used with operators like IN or ANY , where the outer query compares values from multiple
rows.
For example, the subquery below returns a list of department IDs for departments located in
New York, which the main query then uses to filter employees in those departments.
Row subqueries
Row subqueries return a single row containing multiple columns. These subqueries are
typically used with comparison operators that can compare a row of data, such as the = or
IN operators, when multiple values are expected.
The following subquery retrieves a manager's department and job title, and the outer query
finds employees with matching values.
Table subqueries, or derived tables, return a complete table of multiple rows and columns.
These are commonly used in the FROM clause as a temporary table within a query.
For example, the subquery below creates a derived table of average salaries by department,
which is then used in the outer query to find departments with an average salary above a
specified threshold.
[Link] 2/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
(SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY depa
WHERE dept_avg.avg_salary > 50000;
-- Selects the main column to retrieve from the main table to query
SELECT column_name
FROM table_name
-- Applies a condition to filter rows based on the subquery result
WHERE column_name operator
-- Subquery retrieves data for comparison in the WHERE clause
(SELECT column_name FROM table_name WHERE condition);
Execution order
The execution order for subqueries depends on whether they are correlated or non-
correlated.
Non-correlated subqueries
Non-correlated subqueries are independent of the outer query and execute first. The
subquery's result is then passed to the outer query. Non-correlated subqueries are
commonly used for scalar or column-level calculations and filters.
The subquery (SELECT AVG(salary) FROM employees) runs first and calculates the
average salary.
The outer query then retrieves employees whose salary is greater than this average.
I recommend taking DataCamp’s Introduction to SQL Server course to learn more about
grouping and data aggregation, and joining tables.
Correlated subqueries
Correlated subqueries depend on the outer query for some of their data, so they are re-
evaluated for each row processed by the outer query.
[Link] 3/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
The outer query then compares each employee’s salary with the department’s
average salary and includes only those who earn more.
Filtering data
Subqueries are useful when filtering data based on dynamic conditions, especially when
filtering requires comparing values across multiple tables or performing calculations.
The following subquery retrieves the category_id of "Product A," and the main query finds
all products in that category.
Data aggregation
Subqueries are also used for data aggregation, especially when generating summary
statistics or insights for reporting and analysis. The subquery (SELECT department_id,
AVG(sales) AS avg_sales FROM sales GROUP BY department_id) calculates the average
sales per department. The outer query then filters departments with an average sales above
50,000.
Index Relevant Columns: To speed up data retrieval, ensure that columns used in
WHERE and JOIN clauses and comparison operations are indexed.
Limit the Use of Correlated Subqueries: Where possible, use JOIN operations or CTEs
instead of correlated subqueries, as they can often process data faster by using set
operations rather than row-by-row processing.
[Link] 4/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
Limit the Number of Columns in Subqueries: Select only the columns you need in
subqueries to minimize data retrieval, reduce memory usage, and allow the database
to optimize execution.
Use EXISTS instead of IN: If a subquery returns a large dataset, using EXISTS rather
than IN can improve performance. The EXISTS operator will stop query processing
when it finds a matching row, while the IN operator continues to evaluate the entire
subquery result.
Use Meaningful Aliases: Clearly name your tables and subqueries to improve
readability.
Try out our SQL Server Developer career track, which will equip you with the skills to write,
troubleshoot, and optimize your queries using SQL Server.
Recursive subqueries
Recursive subqueries (also known as recursive common table expressions or CTEs) allow you
to retrieve hierarchical data, such as organizational structures, product categories, or graph-
based relationships, where each item in the data is linked to another.
UNION ALL
-- Recursive Query: Find employees who report to those in the previous level
SELECT e.employee_id, e.manager_id, e.employee_name, [Link] + 1
FROM employees e
INNER JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id
)
SELECT * FROM EmployeeHierarchy;
[Link] 5/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
What I call the Anchor Query selects the top-level manager (where manager_id is
NULL ).
The Recursive Query joins employees with the CTE itself ( EmployeeHierarchy ),
finding employees who report to each previously retrieved employee.
The recursion continues until no more employees are reporting to the ones found.
Subqueries can be used to refine the dataset that window functions act on, making them
useful for ranking, cumulative totals, and moving averages. Suppose you want to rank
products by sales within each region. You can use a subquery to select the relevant data
and then apply a window function for ranking.
Combining subqueries with CASE statements can help you apply complex conditions based
on dynamic calculations. The following query classifies products as “High”, “Medium”, or
“Low” performers based on their sales relative to the average sales for their category.
You can also calculate conditional aggregates using subqueries within aggregate functions.
Suppose you want to calculate the total revenue generated only by active customers. In the
example below, the subquery retrieves all active customers. The main query then filters
orders to include only those placed by active customers, calculating the total revenue from
this group.
[Link] 6/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
Industry-specific examples
Subqueries can offer useful solutions in finance, healthcare, and retail industries. Here are
some ideas:
Risk Assessment for Loan Approvals (Finance): I picture banks juggling metrics like
debt-to-income ratios and credit scores. By nesting these metrics in subqueries,
analysts can make better sense of complicated financial metrics. Maybe, a subquery
can calculate the average loan amount for customers within specific income
brackets.
Mathematical connections
Subqueries are also used to identify data patterns and trends in mathematical and logical
connections. The following are some scenarios where subqueries are applied in
mathematics.
Moving Averages for Time-Series Analysis: When analyzing trends over time,
subqueries simplify calculating moving averages. I see them defining specific time
windows within nested queries, making it easier to smooth data and spot trends.
Detecting Outliers Using Standard Deviations: Spotting outliers is importing for lots of
things, including things like fraud detection. Subqueries make it straightforward to
compute computed metrics like standard deviations within nested queries.
Using Set Theory Concepts: I find it interesting how subqueries mirror set theory
operations like UNION and INTERSECT . This capability is perfect for tasks like
customer retention analysis, where understanding overlaps and differences between
customer groups can drive smarter marketing strategies.
Conclusion
Mastering SQL subqueries can significantly enhance your ability to manage and analyze
data efficiently. By understanding their structure, applications, and best practices, you can
optimize your SQL queries for better performance. Also, I want to say that mastering
subqueries just makes writing SQL easier, so it's worth learning.
If you are interested in becoming a proficient data analyst, check out our Associate Data
Analyst in SQL career track to learn the necessary skills. The Reporting in SQL course is also
appropriate if you want to learn how to build professional dashboards using SQL. Finally, I
recommend obtaining the SQL Associate Certification to demonstrate your mastery of
using SQL for data analysis and stand out among other data professionals.
Explore Track
[Link] 7/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
AUTHOR
Allan Ouko
Data Science Technical Writer with hands-on experience in data analytics, business
intelligence, and data science. I write practical, industry-focused content on SQL, Python,
Power BI, Databricks, and data engineering, grounded in real-world analytics work. My
writing bridges technical depth and business impact, helping professionals turn data into
confident decisions.
TO P I C S
COURSE
Introduction to SQL
2 hr 1.6M
Learn how to create and query relational databases using SQL in just two hours.
See More
Related
T U TO R I A L
Correlated Subquery in SQL:
How It Works with Examples
[Link] 8/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
T U TO R I A L
CTE in SQL: A Complete Guide
with Examples
T U TO R I A L
See More
LEARN
Learn Python
Learn AI
Learn Power BI
Assessments
Career Tracks
Skill Tracks
Courses
DATA C O U R S E S
Python Courses
R Courses
SQL Courses
Power BI Courses
Tableau Courses
Alteryx Courses
Azure Courses
AWS Courses
Excel Courses
AI Courses
[Link] 9/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
DATA L A B
Get Started
Pricing
Security
Documentation
C E R T I F I C AT I O N
Certifications
Data Scientist
Data Analyst
Data Engineer
SQL Associate
Azure Fundamentals
AI Fundamentals
RESOURCES
Resource Center
Upcoming Events
Blog
Code-Alongs
Tutorials
Docs
Open Source
RDocumentation
Data Portfolio
PLANS
Pricing
For Students
For Business
For Universities
[Link] 10/11
6/10/26, 3:42 PM SQL Subquery: A Comprehensive Guide | DataCamp
Expense DataCamp
DataCamp Donates
FO R B U S I N E S S
Business Pricing
Teams Plan
Customer Stories
Partner Program
ABOUT
About Us
Learner Stories
Careers
Become an Instructor
Press
Leadership
Contact Us
DataCamp Español
DataCamp Português
DataCamp Deutsch
DataCamp Français
S U P PO R T
Help Center
Become an Affiliate
Privacy Policy Cookie Notice Do Not Sell My Personal Information Accessibility Security Terms of Use
[Link] 11/11