Database.Beginner.What is a subquery?

What is a Subquery in SQL?

✅ A subquery is:

A query inside another query.

  • It’s enclosed in parentheses (...).
  • It is executed first, and its result is used by the outer query.
  • It can return:
    • A single value (scalar).
    • A row.
    • A table (multiple rows and columns).

Where Can You Use a Subquery?

You can use subqueries in:

ClauseExample
SELECT listIn column selection
FROM clauseAs a derived table
WHERE clauseTo filter rows
HAVING clauseTo filter groups

Simple Example

Suppose you have a table Products:

product_idnameprice
1Phone800
2Laptop1200
3Tablet600

Find products that are more expensive than the average price.

Step-by-step:

  1. First, calculate the average price:
SELECT AVG(price) FROM Products;

Then, find products with price > average:

SELECT name, price
FROM Products
WHERE price > (SELECT AVG(price) FROM Products);

✅ The part:

(SELECT AVG(price) FROM Products)

is a subquery — it returns a single value (the average price) and is used in the WHERE clause.

Types of Subqueries

TypeDescription
Scalar SubqueryReturns a single value (one row, one column).
Row SubqueryReturns a single row (multiple columns).
Table SubqueryReturns a full table (multiple rows, multiple columns).
Correlated SubqueryRefers to columns from the outer query. Runs row-by-row.

What is a Correlated Subquery?

A correlated subquery depends on the outer query — it runs once for each row.

Example:
Find customers who placed more orders than average for their city:

SELECT c.customer_id, c.city
FROM Customers c
WHERE 
    (SELECT COUNT(*)
     FROM Orders o
     WHERE o.customer_id = c.customer_id) 
    > 5;

Here, the subquery depends on c.customer_id from the outer query.

It’s executed once for each customercorrelated.

Key Points About Subqueries

FeatureDetails
Executed firstInner query runs before the outer query.
Can be used in many clausesSELECT, FROM, WHERE, HAVING.
Helps build complex logicBreaks down complex problems.
Scalar, Row, or TableCan return different amounts of data.
Correlated vs Non-correlatedCorrelated re-executes per row; non-correlated runs once.

In Short

Subquery = Query inside another query — used to get values or tables dynamically inside your SQL statements.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.