SQL Subquery Explanation
Definition
A SQL subquery is a query that is embedded inside another SQL query. It acts like a nested
query that runs first, and its result is then used by the outer query to filter, compare, or
calculate data.
You can think of a subquery as a mini-query inside a bigger query. This helps to break down
complex questions into simpler steps, making SQL code more powerful and flexible.
Key Points About Subqueries
- A subquery is enclosed in parentheses ( ).
- It can return a single value, a list of values, or even a table.
- Subqueries can appear in SELECT, FROM, WHERE, or HAVING clauses.
- Subqueries can be independent (run on their own) or correlated (depend on values from
the outer query).
Why Use Subqueries?
- To filter data based on complex conditions.
- To calculate intermediate results for comparison.
- To avoid multiple query steps in application code by doing it all in SQL.
- To make queries easier to understand by breaking them into logical parts.
Example
Find customers who placed orders above the average order amount:
```sql
SELECT customer_id, order_amount
FROM orders
WHERE order_amount > (
SELECT AVG(order_amount)
FROM orders
);
```
Here, the subquery calculates the average order amount, and the outer query selects orders
greater than that average.