Search code examples
databasepostgresqltemp-tables

Postgres: Do I need to create temporary tables in each session?


In my Application, I need to create few temporary tables. Do I need to execute the SQL in each session to create temp tables else can I run the SQL manually once, and can use those temporary tables in each session?


Solution

  • From the fine manual:

    Temporary Tables

    Although the syntax of CREATE TEMPORARY TABLE resembles that of the SQL standard, the effect is not the same. In the standard, temporary tables are defined just once and automatically exist (starting with empty contents) in every session that needs them. PostgreSQL instead requires each session to issue its own CREATE TEMPORARY TABLE command for each temporary table to be used. This allows different sessions to use the same temporary table name for different purposes, whereas the standard's approach constrains all instances of a given temporary table name to have the same table structure.

    So temporary tables are local to each session and each session will need its own CREATE TEMPORARY TABLE and the temporary tables will be different in each session even if they have the same name.