runtime
28 / 88

lesson 28 Dates, strings & subqueries · intermediate

Subqueries

Use the result of one query inside another.

the idea

A subquery is a query inside another query. A scalar subquery produces one value, which can be used in a comparison. Parentheses separate the inner query.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
SELECT name, price
FROM products
WHERE price > (
  SELECT AVG(price)
  FROM products
);

Watch for: The inner average summarizes the entire table; it is not a per-row calculation.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Compute the comparison value. A subquery can produce the average price once. The outer query will compare each product to that single number.

    step-1.sql
    SELECT AVG(price) AS avg_price
    FROM products;
  2. Filter rows against the subquery. The parenthesized SELECT runs as a scalar subquery. Rows with price above that average remain.

    step-2.sql
    SELECT name, price
    FROM products
    WHERE price > (
      SELECT AVG(price)
      FROM products
    );

challenge 1

Show name and price of products above the average product price.

Return namepriceany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.