Beginner

535. EXISTS with JOIN

Learn how EXISTS can be combined with JOINs inside a subquery to perform advanced relationship checks.

📘 Lesson 535 of 728 ⏱ 13 min 🎯 Advanced

EXISTS checks whether a subquery returns at least one row. The subquery can itself contain JOINs to evaluate relationships across multiple tables.

Complex business rules may require checking whether related information exists across several tables.

Find customers who have orders containing products from a particular category.

SQL
SELECT
    c.CustomerID,
    c.CustomerName
FROM Customers c
WHERE EXISTS (
    SELECT 1
    FROM Orders o
    INNER JOIN Products p
        ON o.ProductID = p.ProductID
    WHERE o.CustomerID = c.CustomerID
      AND p.Category = 'Electronics'
);

Used in customer segmentation, product analysis, compliance checks, and eligibility rules.

  • EXISTS checks for the presence of rows.
  • The EXISTS subquery can contain JOINs.
  • Only existence matters to the outer query.
  • It can prevent duplicate outer rows.
  • Complex existence rules can be expressed clearly.
Can EXISTS contain a JOIN?

Yes. The subquery used by EXISTS can contain JOINs and other SQL operations.

Why use EXISTS instead of returning joined rows?

EXISTS is useful when the requirement is only to confirm that a related record exists.

Have you finished this lesson?

Introduction to SQL – All Lessons