A subquery is a SELECT inside a SELECT, in parentheses. We use it when we need an intermediate result such as an average or a list of customers.
Products pricier than the average of all products. Open in SQL Lab
Customers with orders in 2026. Open in SQL Lab
EXISTS asks whether a row exists. Here: products never sold. Open in SQL Lab
Subquery in FROM
Aggregate per customer first and then per city: aggregation on aggregation. Open in SQL Lab
Combining results: UNION, INTERSECT, EXCEPT
| Command | Result |
|---|---|
| UNION | Combine without duplicates |
| UNION ALL | Combine keeping duplicates (faster) |
| INTERSECT | What both results share |
| EXCEPT | In the first but not in the second |
Customers who ordered in both 2025 and 2026. Open in SQL Lab
For advanced readers CTEs and performance
A WITH clause (CTE) names a subquery and makes the query clearer; we cover it in the advanced stage with window functions. EXISTS is often faster than IN on large tables, and some optimizers rewrite one into the other.
Exercise 1 — Show the name and price of products pricier than the average price of all products.
A subquery AVG(price) inside WHERE.
Exercise 2 — Show the names of products that were never sold (absent from order_items).
NOT EXISTS correlated on product_id.
Exercise 3 — Show customer_id of customers who ordered both before 2026 and in 2026.
INTERSECT between two queries.
- A subquery is a SELECT inside a SELECT.
- EXISTS and IN check existence.
- UNION, INTERSECT and EXCEPT combine results.
Want an expert to do it for you?
Gomaa Intelligence turns your data into clear reports and decisions. Tell us your problem and we will reply.