sqlcmd.net validated sql reference
intermediate subqueries MySQL MariaDB SQL Server PostgreSQL SQLite

Nest A Query Inside Another With Subqueries

Embed a `SELECT` inside another query to filter, compute, or supply values that depend on aggregated or derived data.

Docker-validated Not currently validation-green

Find employees who earn above the company average

The inner query computes the average salary (72500). The outer query then filters to only the rows where salary exceeds that value. Alice (70000) and Bob (50000) fall below the average and are excluded.

Rows loaded before the example query runs.
Setup
CREATE TABLE employees (id INT, name VARCHAR(50), salary INT);

INSERT INTO
  employees (id, name, salary)
VALUES
  (1, 'Alice', 70000),
  (2, 'Bob', 50000),
  (3, 'Carol', 90000),
  (4, 'Dave', 80000);
Shared across supported engines.
SQL
SELECT
  name,
  salary
FROM
  employees
WHERE
  salary > (
    SELECT
      AVG(salary)
    FROM
      employees
  )
ORDER BY
  salary DESC;
Returned rows for the shared example.
namesalary
Carol90000
Dave80000

Output is identical across all engines.

Where this command helps.

  • comparing rows against a derived value like an average or maximum
  • breaking a query into nested logical steps without a separate table

What the command is doing.

A subquery is a SELECT wrapped in parentheses and used where a value or table is expected. In a WHERE clause it computes a scalar value to compare against. In a FROM clause it acts as a derived table. Subqueries are evaluated once per logical step and can reference outer query columns to become correlated subqueries.