Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redshift INSERT INTO TABLE from CTE

According to the Redshift WITH Clause documentation, you can use a WITH clause with a INSERT INTO...SELECT statement. However when testing this, I am getting the below error. Is this not possible, or do I have the syntax wrong?

CREATE TABLE TestCTEInsert (SomeTimestamp TIMESTAMP);
WITH CTE AS
(SELECT GETDATE() as SomeTimestamp)
INSERT INTO TestCTEInsert
    (SomeTimestamp) SELECT SomeTimestamp from CTE;

ERROR: 42601: syntax error at or near "insert"

Interestingly, it does support inserting into a new table i.e.

WITH CTE AS
(SELECT GETDATE() as SomeTimestamp)
INSERT SomeTimestamp INTO NewTable 
SELECT SomeTimestamp from CTE;

The command completed successfully (1 rows affected)

EDIT: Just to confirm, I get the same error when using an INTEGER column rather than TIMESTAMP:

CREATE TABLE TestCTE (SomeInt INTEGER);
WITH CTE AS
(SELECT 1 as SomeInt)
INSERT INTO TestCTEInsert 
SELECT SomeInt from CTE;

ERROR: 42601: syntax error at or near "insert"

like image 686
fez Avatar asked Jan 18 '16 10:01

fez


2 Answers

Try putting the CTE in the insert (not sure if that beats the point)

INSERT INTO TestCTEInsert
WITH CTE AS
(SELECT CURRENT_TIMESTAMP as SomeTimestamp)
SELECT SomeTimestamp from CTE;
like image 84
Adeeb Armalite Avatar answered Oct 11 '22 14:10

Adeeb Armalite


The ; terminates a statement, so it needs to go at the end of the statement, not somewhere in the middle:

You can do this in two ways, either use a create table as select

create table TestCTEInsert 
as
WITH CTE AS
(  
   SELECT current_timestamp as SomeTimestamp
)
SELECT SomeTimestamp 
from CTE; -- ; only at the end

Or in two steps:

CREATE TABLE TestCTEInsert (SomeTimestamp TIMESTAMP); -- end this with a ;

insert into TestCTEInsert
WITH CTE AS
(  
   SELECT current_timestamp as SomeTimestamp
)
SELECT SomeTimestamp 
from CTE; -- ; only at the end

The above runs on a vanilla Postgres installation, I don't have access to RDS

like image 31
a_horse_with_no_name Avatar answered Oct 11 '22 12:10

a_horse_with_no_name