15

In postgres(9.4) I am trying to create a temporary table from select and apply "on commit drop" to same table. I am using below syntax.

CREATE TEMPORARY TABLE t5 ON COMMIT DROP AS select * from test4

It gives messages

Query returned successfully: 5 rows affected, 62 ms execution time.

But when i query the same table,

select * from t5

It throws error,

ERROR:  relation "t5" does not exist
LINE 1: select * from t5
                      ^
********** Error **********

ERROR: relation "t5" does not exist
SQL state: 42P01
Character: 15

Please let me know what is wrong with my understanding what is the mistake i am committing here.

Thanks

2
  • 3
    My guess is that the temp table is being dropped as soon as the select finishes, when it also has finished just being created. What exact behavior are you looking for here? Commented Sep 18, 2018 at 10:22
  • As Tim said: you probably have autocommit enabled and thus the create table statement is automatically committed and thus the temp table is dropped Commented Sep 18, 2018 at 10:23

1 Answer 1

31

You need to be in a transaction otherwise every single query is performed in its own transaction.

BEGIN; -- start transaction

CREATE TEMPORARY TABLE t5 ON COMMIT DROP AS select * from test4;

select * from t5;

COMMIT; -- drops the temp table
Sign up to request clarification or add additional context in comments.

1 Comment

Yes @Eleke, you are right. This works when i put in a block. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.