← Back to list

What is a subquery?

A subquery is a query written inside another SQL query. It is used to retrieve data that will be used by the main query.

Nivethabaskar · 2026-05-22 17:21 · 0 claps · 0.8 min read
#data-science #data #subquery #sql
Open on Medium ↗
Wiki topics: ML · Machine Learning 🔬 · Science · General

What is a subquery?

A **subquery** is a query written inside another SQL query. It is used to retrieve data that will be used by the main query.

Syntax

SELECT column_name
FROM table_name
WHERE column_name = (
    SELECT column_name
    FROM another_table
);

Example

Suppose you have an Employees table.

To find employees who earn more than the average salary:

SELECT name, salary
FROM Employees
WHERE salary > (
    SELECT AVG(salary)
    FROM Employees
);

How it works

  1. The inner query (subquery) calculates the average salary.
  2. The outer query selects employees whose salary is greater than that value.

Types of Subqueries

  1. Single-row subquery — returns one value
  2. Multiple-row subquery — returns multiple values
  3. Correlated subquery — depends on the outer query
  4. Nested subquery — subquery inside another subquery

Advantages

  • Simplifies complex queries
  • Improves readability
  • Helps perform calculations before the main query executes

Simple Definition

A subquery is a query inside another query used to help the main query get the required result.


메타데이터
post_id
e2c58a6f4f4f
slug
what-is-a-subquery-e2c58a6f4f4f
url
https://medium.com/@nivethabaskar88/what-is-a-subquery-e2c58a6f4f4f
canonical_url
https://medium.com/@nivethabaskar88/what-is-a-subquery-e2c58a6f4f4f
author_url
https://medium.com/@nivethabaskar88
status
ok
fetched_at
2026-07-28 21:17:07