CodeBlanks Logo Icon CodeBlanks

What is a subquery?

Run a query inside another query.

What is a subquery?

A subquery is a query inside another query. It is wrapped in parentheses.

SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);

This query returns products above the average.

name is selected from products. WHERE keeps only the rows where price > (SELECT AVG(price) FROM products) holds.

What is a subquery? — details

The subquery runs first and feeds its result to the outer query. It enables nested queries.

For example, WHERE price > (SELECT AVG(price) FROM products) computes the average first, then returns products above it.

Practice What is a subquery?

Find products priced above average using a subquery.

Starter code

query.sql
-- above average
SELECT name FROM products
WHERE price >

Sample solution

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

Expected output

name
Laptop
Telefon

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is a subquery inside?

  • Curly braces
  • Parentheses Correct answer
  • Square brackets
  • Quotes

Explanation: A subquery is wrapped in parentheses.

2 Add parentheses

Question
SELECT name FROM products
WHERE price > ____SELECT AVG(price) FROM products);
Answer
SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);

Explanation: A subquery is always written inside parentheses.

3 What is a subquery: match the terms

Term Meaning
subquery inner query
parentheses grouping
SELECT select
WHERE filter

All lessons in Intermediate