Can you create nested WITH clauses for Common Table Expressions?

Joe Phillips picture Joe Phillips · Sep 12, 2009 · Viewed 114.1k times · Source
WITH y AS (
    WITH x AS (
        SELECT * FROM MyTable
    )
    SELECT * FROM x
)
SELECT * FROM y

Does something like this work? I tried it earlier but I couldn't get it to work.

Answer

spender picture spender · Sep 12, 2009

While not strictly nested, you can use common table expressions to reuse previous queries in subsequent ones.

To do this, the form of the statement you are looking for would be

WITH x AS 
(
    SELECT * FROM MyTable
), 
y AS 
(
    SELECT * FROM x
)
SELECT * FROM y