There is an old and deprecated command in PostgreSQL that predates CREATE TABLE AS SELECT
(CTAS) called SELECT ... INTO .... FROM
, it supports WITH
clauses / Common Table Expressions (CTE). So, for instance, I can do this..
WITH w AS (
SELECT *
FROM ( VALUES (1) ) AS t(x)
)
SELECT *
INTO foo
FROM w;
But, I can't do this..
WITH w AS (
SELECT *
FROM ( VALUES (1) ) AS t(x)
)
CREATE TABLE foo AS
SELECT * FROM w;
Or, I get
ERROR: syntax error at or near "CREATE"
LINE 5: CREATE TABLE foo AS
How would I do that using the standardized CTAS syntax.
Best Answer
It may be awkward, but you have to move the
WITH
clause from the top into the query. It's a part of the statement to generate the table, and that statement comes after theCREATE TABLE
, so you would use this syntax.Also worth noting that it's not explicit in the official docs, it just falls under query
The docs mention two other use cases for the
WITH
keyword,storage_options
NO DATA
You can see both of them in use like this,
Now you've got a table with nothing.