A subquery can produce a result set that is treated like a derived table. That result can then be JOINed with other tables.
Complex business logic can be separated into smaller steps, making analytical queries easier to build and understand.
Calculate total sales per customer and then JOIN the totals with customer information.
SELECT
c.CustomerName,
s.TotalSales
FROM Customers c
INNER JOIN (
SELECT
CustomerID,
SUM(OrderAmount) AS TotalSales
FROM Orders
GROUP BY CustomerID
) s
ON c.CustomerID = s.CustomerID;
Used in reporting, customer analytics, financial summaries, and complex data transformations.
- A subquery can act as a derived table.
- The derived result can be JOINed normally.
- Aggregation can be performed before the JOIN.
- Aliases are required for derived tables in many SQL systems.
- This pattern can simplify complex reporting queries.
Can a subquery be used in a JOIN?
Yes. A subquery can produce a derived table that can be JOINed with another table.
Why aggregate inside a subquery before JOINing?
It can reduce the data to the required level before combining it with the main table.