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

Name A Subquery With A CTE

Use `WITH` to define a named temporary result set that can be referenced in the main query, improving readability over inline subqueries.

Docker-validated Not currently validation-green

Summarize order totals per customer, then filter top spenders

The CTE totals groups and sums each customer's orders. The outer query then filters to customers whose total exceeds 200. Bob (140) is excluded. Writing this without a CTE would require a subquery in FROM or repeating the aggregation twice.

Rows loaded before the example query runs.
Setup
CREATE TABLE orders (id INT, customer VARCHAR(50), amount INT);

INSERT INTO
  orders (id, customer, amount)
VALUES
  (1, 'Alice', 100),
  (2, 'Alice', 150),
  (3, 'Bob', 80),
  (4, 'Bob', 60),
  (5, 'Carol', 300);
Shared across supported engines.
SQL
WITH
  totals AS (
    SELECT
      customer,
      SUM(amount) AS total
    FROM
      orders
    GROUP BY
      customer
  )
SELECT
  customer,
  total
FROM
  totals
WHERE
  total > 200
ORDER BY
  total DESC;
Returned rows for the shared example.
customertotal
Carol300
Alice250

Output is identical across all supported engines.

Where this command helps.

  • making a multi-step query easier to read
  • reusing a derived result within one larger statement

What the command is doing.

A Common Table Expression (CTE) is defined with WITH name AS (SELECT ...) before the main query. It behaves like an inline view: the database evaluates it and makes it available by name for the rest of the query. CTEs are especially useful when the same derived result is referenced multiple times, or when breaking a complex query into readable steps.