// dialect comparison

CTE basics: WITH … AS across dialects

WITH works in all five engines; the details around it don't.

Filed under Querying

The verdict

The basic WITH runs unchanged on all five engines, given MySQL 8.0+. The differences sit at the edges: PostgreSQL's data-modifying CTEs and materialization keywords, Oracle's WITH FUNCTION, and which engines want the RECURSIVE keyword.

Where they differ

WITH name AS (SELECT …) defines a named result for the one statement that follows. The basic form is identical in all five engines. They differ in version floors (MySQL 8.0, SQLite 3.8.3), the RECURSIVE keyword, materialization control and data-modifying CTEs.

How each engine writes it

SQL Server

WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;

The statement before WITH must end with a semicolon. Recursive CTEs use plain WITH; the RECURSIVE keyword is a syntax error.

PostgreSQL

WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;

MATERIALIZED / NOT MATERIALIZED (12+) control inlining. WITH d AS (DELETE … RETURNING *) makes a data-modifying CTE.

MySQL

WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;

8.0+ only; on 5.7 rewrite it as a derived table.

SQLite

WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;

Since 3.8.3, recursive CTEs included. MATERIALIZED / NOT MATERIALIZED hints since 3.35.

Oracle

WITH big AS (SELECT id, total FROM orders WHERE total > 1000) SELECT COUNT(*) AS big_count FROM big;

WITH has been supported since 9i. 12c adds WITH FUNCTION for inline PL/SQL, and the /*+ MATERIALIZE */ hint forces materialization.

Questions that come up

Is a CTE a performance feature or just syntax?

Mostly syntax: it names a subquery. Whether it is computed once or inlined depends on the engine. PostgreSQL 12+ inlines a CTE referenced once and materializes one referenced several times; SQL Server always inlines, like a view, so a CTE referenced three times can run three times. Check the plan when it matters.

Can I reuse a CTE across two queries?

No. A WITH clause belongs to one statement. To reuse a result across statements, put it in a temp table or a view, or repeat the WITH.

How does a recursive CTE work?

An anchor SELECT, UNION ALL, then a SELECT that references the CTE's own name, repeated until it returns no rows. PostgreSQL and MySQL require WITH RECURSIVE; SQLite accepts it with or without the keyword; SQL Server and Oracle (11gR2+) use plain WITH and reject RECURSIVE. Oracle also has its older CONNECT BY syntax.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.