Beginner

561. JOIN with Subquery

Learn how a subquery can be used as a data source in a JOIN.

📘 Lesson 561 of 728 ⏱ 14 min 🎯 Advanced

A subquery can produce a temporary result set that can be joined with another table. This is useful when data must be filtered or aggregated before it is combined.

Preprocessing data inside a subquery can make complex analytical queries easier to understand and control.

Calculate customer order totals first and then join those totals to the Customers table.

SQL
SELECT
    c.CustomerName,
    x.TotalSales
FROM Customers c
INNER JOIN (
    SELECT
        CustomerID,
        SUM(OrderAmount) AS TotalSales
    FROM Orders
    GROUP BY CustomerID
) x
    ON c.CustomerID = x.CustomerID;

Used in financial reporting, customer analytics, sales analysis, and complex data transformations.

  • A subquery can act as a derived table.
  • The derived result can be joined.
  • Aggregation can happen before the JOIN.
  • Aliases are required for derived tables in many SQL systems.
  • This approach can simplify complex queries.
Can a subquery be used in a JOIN?

Yes. A subquery can produce a derived result set that can be joined with another table.

Why aggregate inside a subquery before JOINing?

It can reduce the data being joined and prevent unnecessary row multiplication.

Have you finished this lesson?

Introduction to SQL – All Lessons