How to code correlated subqueries

Use a correlated subquery in the SELECT clause

      SELECT categoryID, categoryName, (
        SELECT COUNT(*) 
        FROM products 
        WHERE products.categoryID = categories.categoryID
        ) AS productCount 
      FROM categories;
      
corelated subquery image

The syntax of a subquery that uses the EXISTS operator

      WHERE [NOT] EXISTS (subquery)
      

Get all customers that don’t have any orders

      SELECT c.customerID, firstName, lastName 
      FROM customers c 
      WHERE NOT EXISTS (
        SELECT * FROM orders o WHERE c.customerID = o.customerID
      );
      
customers with no orders image

Description

Back