PostgreSQL – Using WITH and CREATE TEMPORARY TABLE AS SELECT

postgresqltemporary-tables

I would like to create a temporary table using a select statement that uses temporary views specified in a WITH statement (not the WITH statement of CREATE TEMPORARY TABLE).

e.g. something along the lines of

WITH a AS (
SELECT 1 foo, 2 bar 
), b AS (
SELECT 4 bar, 5 baz
)
CREATE TEMPORARY TABLE foo AS
SELECT * from a JOIN b ON (a.bar=b.bar)

If I comment out the CREATE TEMPORARY TABLE line, this works. How to create a temporary table using the query result of the SELECT, without rewriting the temporary views into a single query?

Best Answer

The WITH goes after the CREATE TABLE

CREATE TEMPORARY TABLE foo 
AS
WITH a AS (
SELECT 1 foo, 2 bar 
), b AS (
SELECT 4 bar, 5 baz
)
SELECT * from a JOIN b ON (a.bar=b.bar)

Note the above will result in "ERROR: column "bar" specified more than once" - but I assume you are using better (distinct) column names in the real query.