SQL Subqueries
SQL

SQL Subqueries — How to Write Queries Inside Queries

CHAPTER 28 of 30 SQL Tutorial — Free Course on Neotech Navigators
A SQL subquery (also called a nested query or inner query) is a query placed inside another SQL statement. The inner query runs first and its result is used by the outer query. In this chapter, you will learn subqueries in WHERE, SELECT, and FROM clauses, plus the difference between correlated and non-correlated subqueries.

What Is a Subquery?

A subquery is a SELECT statement nested inside another statement. The inner query executes first, then its result feeds into the outer query:

SQL — Subquery Structure
SELECT columns
FROM table_name
WHERE column operator (
  SELECT column FROM table_name WHERE condition
);

Sample Table

TABLE: Employees
+----+-----------+------------+--------+-----------+
| ID | Name      | Department | Salary | City      |
+----+-----------+------------+--------+-----------+
| 1  | Priya K.  | Sales      | 55000  | Mumbai    |
| 2  | John D.   | Marketing  | 62000  | London    |
| 3  | Arun M.   | IT         | 78000  | Delhi     |
| 4  | Emma W.   | Sales      | 51000  | Sydney    |
| 5  | Ravi S.   | IT         | 72000  | Mumbai    |
| 6  | Sara L.   | HR         | 58000  | New York  |
+----+-----------+------------+--------+-----------+

Subquery in WHERE Clause

Find employees who earn more than the average salary:

SQL
SELECT Name, Salary
FROM Employees
WHERE Salary > (
  SELECT AVG(Salary) FROM Employees
);
✓ OUTPUT
+-----------+--------+
| Name      | Salary |
+-----------+--------+
| John D.   | 62000  |
| Arun M.   | 78000  |
| Ravi S.   | 72000  |
+-----------+--------+

The inner query calculates the average salary (62,667). The outer query returns employees above that value.

Subquery with IN

Find employees in departments that have someone earning over 70,000. This uses IN with a subquery:

SQL
SELECT Name, Department, Salary
FROM Employees
WHERE Department IN (
  SELECT Department FROM Employees
  WHERE Salary > 70000
);
✓ OUTPUT
+-----------+------------+--------+
| Name      | Department | Salary |
+-----------+------------+--------+
| Arun M.   | IT         | 78000  |
| Ravi S.   | IT         | 72000  |
+-----------+------------+--------+

Subquery in SELECT Clause

Show each employee alongside the company-wide average salary:

SQL
SELECT Name, Salary,
       (SELECT ROUND(AVG(Salary), 0) FROM Employees) AS AvgSalary,
       Salary - (SELECT ROUND(AVG(Salary), 0) FROM Employees) AS Difference
FROM Employees;
✓ OUTPUT
+-----------+--------+-----------+------------+
| Name      | Salary | AvgSalary | Difference |
+-----------+--------+-----------+------------+
| Priya K.  | 55000  | 62667     | -7667      |
| John D.   | 62000  | 62667     | -667       |
| Arun M.   | 78000  | 62667     | 15333      |
| Emma W.   | 51000  | 62667     | -11667     |
| Ravi S.   | 72000  | 62667     | 9333       |
| Sara L.   | 58000  | 62667     | -4667      |
+-----------+--------+-----------+------------+

Subquery in FROM Clause (Derived Table)

First calculate department totals, then filter those totals. The subquery acts as a temporary table using an alias:

SQL
SELECT DeptSummary.Department, DeptSummary.TotalSalary
FROM (
  SELECT Department, SUM(Salary) AS TotalSalary
  FROM Employees
  GROUP BY Department
) AS DeptSummary
WHERE DeptSummary.TotalSalary > 100000;
✓ OUTPUT
+------------+-------------+
| Department | TotalSalary |
+------------+-------------+
| IT         | 150000      |
| Sales      | 106000      |
+------------+-------------+

Correlated vs Non-Correlated Subqueries

Type How It Works Performance
Non-correlated Inner query runs once, independently Faster — executes once
Correlated Inner query runs once per outer row, referencing the outer query Slower — runs many times

A correlated subquery references a column from the outer query. Find employees who earn more than their department average:

SQL — Correlated Subquery
SELECT Name, Department, Salary
FROM Employees AS e1
WHERE Salary > (
  SELECT AVG(Salary) FROM Employees AS e2
  WHERE e2.Department = e1.Department
);
✓ OUTPUT
+-----------+------------+--------+
| Name      | Department | Salary |
+-----------+------------+--------+
| Priya K.  | Sales      | 55000  |
| Arun M.   | IT         | 78000  |
+-----------+------------+--------+

⚠️ Subquery Performance

Correlated subqueries can be slow on large tables because the inner query runs once per outer row. Consider using JOINs or window functions as faster alternatives when possible.

For the complete subquery reference, see the official MySQL subquery documentation. In the next chapter, you will learn SQL Window Functions for advanced row-level calculations.

If you work with data regularly, explore our ready-made Dashboard Templates on NextGenTemplates that use SQL-powered data for business reporting.

📺 Visit our YouTube channel @NeoTechNavigators for step-by-step video tutorials and dashboard demos on this topic.

🧪 Try It Yourself

Write a query that finds the employee with the highest salary using a subquery.

ANSWER
SELECT Name, Department, Salary
FROM Employees
WHERE Salary = (
  SELECT MAX(Salary) FROM Employees
);

Expected Output:

+-----------+------------+--------+
| Name      | Department | Salary |
+-----------+------------+--------+
| Arun M.   | IT         | 78000  |
+-----------+------------+--------+

📝 What You Learned in This Chapter

  • A subquery is a SELECT inside another SQL statement
  • Subqueries can go in WHERE, SELECT, and FROM clauses
  • Non-correlated subqueries run once; correlated subqueries run once per outer row
  • Subqueries in FROM create derived (temporary) tables
  • Use subqueries to compare values against aggregates dynamically
  • Consider JOINs or window functions for better performance on large datasets

Frequently Asked Questions

What is a subquery in SQL?
A subquery (or nested query) is a SELECT statement placed inside another SQL statement. The inner query runs first and its result is used by the outer query. Subqueries can appear in WHERE, SELECT, FROM, and HAVING clauses.
What is the difference between a correlated and non-correlated subquery?
A non-correlated subquery runs independently and executes once. A correlated subquery references the outer query and runs once for each outer row. Correlated subqueries are more flexible but slower on large datasets.
Can I nest multiple subqueries?
Yes. You can nest subqueries within subqueries to multiple levels. However, deeply nested queries become hard to read and may perform poorly. Consider breaking complex logic into simpler queries or using JOINs and CTEs instead.
Are subqueries slower than JOINs?
Not always. Non-correlated subqueries are often optimized similarly to JOINs by the database engine. Correlated subqueries can be slower because they run per row. Modern optimizers often rewrite subqueries as JOINs internally for better performance.
When should I use a subquery vs a JOIN?
Use a subquery when you need a single aggregate value or a list for comparison. Use a JOIN when you need columns from multiple tables in the output. If performance matters and the subquery is correlated, a JOIN is usually faster.

📖 Chapter 28 of 30 — SQL Tutorial on Neotech Navigators

PK
Meet PK, the founder of NeotechNavigators.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you're looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK's services and see how he can take your data analysis skills to the next level!
https://neotechnavigators.com