Where to use subqueries

Four ways to introduce a subquery in a SELECT statement

  1. In a WHERE clause as a search condition
  2. In a HAVING clause as a search condition
  3. In the FROM clause as a table specification
  4. In the SELECT clause as a column specification

Use a subquery in the WHERE clause

      SELECT productName, listPrice 
      FROM products 
      WHERE listPrice > (
        SELECT AVG(listPrice)
        FROM products
        );
      ORDER BY listPrice DESC;
      

The result set

      The value returned by the subquery 841.895 
      
The result set subquery result set image

Use another subquery in the WHERE clause

      SELECT productName, listPrice 
      FROM products 
      WHERE categoryID = (
        SELECT categoryID 
        FROM categories 
        WHERE categoryName = 'Basses'
        );
      
The result set 2nd 2 rows image

Description

Back