Search⌘ K

Subqueries in SELECT and WHERE

Learn how nested queries work in SQL.

Step 1: Start with a question

You already know how to ask questions like: Show the average salary for each department.

But what if you want to ask something relative, like: Which employees earn more than the company average salary?

That requires two questions at once:

  1. What’s the company’s average salary?

  2. Which employees earn more than that value?

A subquery lets you nest one question inside another.

Prompt: Write a SQL query that shows employees whose salary is greater than the company’s average salary.

Powered by AI
5 Prompts Remaining
Prompt AI WidgetOur tool is designed to help you to understand concepts and ask any follow up questions. Ask a question to get started.

Step 2: Run and observe

AI might return:

MySQL
SELECT first_name,
last_name,
salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);

 Run it. Now your main query (SELECT ...