Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create in WITH(CTE) using PostgreSQL

Tags:

postgresql

I am trying to create temporary table within WITH using function in PostgreSQL.

Example:

with mm
as
(
     select * from test
)
create table xyz as select * from mm
;

Note: Getting error near create

like image 610
Sarfaraz Makandar Avatar asked Jun 16 '14 12:06

Sarfaraz Makandar


People also ask

Can I use with CTE in Postgres?

In PostgreSQL, the CTE(Common Table Expression) is used as a temporary result set that the user can reference within another SQL statement like SELECT, INSERT, UPDATE or DELETE. CTEs are temporary in the sense that they only exist during the execution of the query.

Can you create table from CTE?

You can use a common table expression (CTE) to simplify creating a view or table, selecting data, or inserting data. Use a CTE to create a table based on another table that you select using the CREATE TABLE AS SELECT (CTAS) clause.

Can we create index on CTE in PostgreSQL?

No you can not create an index on parts of a query, during the query. CTE (common table expressions), is also called Subquery Factoring.

Can we use a CTE within a create view statement?

CTE was introduced in SQL Server 2005, the common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. You can also use a CTE in a CREATE a view, as part of the view's SELECT query.


1 Answers

create table xyz as 

with mm
as
(
     select * from test
)
select * from mm 
where myfield = myvalue
;

Relevant documentation. In documentation, there is no explicit description on how to use create table as together with CTE. However it clearly states it's syntax (simplified):

CREATE TABLE table_name
    AS query

Where query can be (quoting):

A SELECT, TABLE, or VALUES command, or an EXECUTE command that runs a prepared SELECT, TABLE, or VALUES query.

From this it should be pretty much clear why your attempt failed.

like image 148
Tomas Greif Avatar answered Sep 20 '22 13:09

Tomas Greif