SQL CTE Formatter

Format SQL queries that use WITH common table expressions. Each CTE is indented clearly so multi-step queries are easy to follow. Free and private.

Part of the free SQL Formatter. Runs in your browser — nothing is uploaded.

SQL CTE Formatter

Common table expressions break a complex query into named steps, but on one line they are unreadable. Formatting separates each CTE and the final SELECT so you can trace the data flow from the first step to the last.

Worked example: Two chained CTEs and a final SELECT

Input

with recent_orders as (select customer_id, sum(total) as spent from orders where created_at > now() - interval '30 days' group by customer_id), vip as (select customer_id from recent_orders where spent > 1000) select c.name, r.spent from customers c join recent_orders r on r.customer_id = c.id where c.id in (select customer_id from vip) order by r.spent desc;

Formatted CTE query

WITH
  recent_orders AS (
    SELECT
      customer_id,
      sum(total) AS spent
    FROM
      orders
    WHERE
      created_at > now() - interval '30 days'
    GROUP BY
      customer_id
  ),
  vip AS (
    SELECT
      customer_id
    FROM
      recent_orders
    WHERE
      spent > 1000
  )
SELECT
  c.name,
  r.spent
FROM
  customers c
  JOIN recent_orders r ON r.customer_id = c.id
WHERE
  c.id IN (
    SELECT
      customer_id
    FROM
      vip
  )
ORDER BY
  r.spent DESC;

Practical tip

Give CTEs descriptive names like recent_orders rather than t1. The formatted query then reads like a short story of how the result is built.

How to use this SQL Formatter

  1. 1Use the live tool above — it runs entirely in your browser and never uploads your data.
  2. 2Paste the sample from the worked example, or use your own input.
  3. 3Copy the result, then adapt the same steps in your editor, script, or pipeline.

SQL CTE Formatter FAQs

Does it support recursive CTEs?

Yes. WITH RECURSIVE queries are formatted with the same structure, with the anchor and recursive parts indented.

Are CTEs faster than subqueries?

Not by themselves. They mainly improve readability, and the optimizer often treats them like subqueries, though behavior varies by database.

More SQL Formatter pages

Open the full SQL Formatter tool →