PostgreSQL Tutorial
Data Types
Querying & Filtering Data
Managing Tables
Modifying Data
Conditionals
Control Flow
Transactions & Constraints
Working with JOINS & Schemas
Roles & Permissions
Working with Sets
Subquery & CTEs
User-defined Functions
Important In-Built Functions
PostgreSQL PL/pgSQL
Variables & Constants
Stored Procedures
Working with Triggers
Working with Views & Indexes
Errors & Exception Handling
In PostgreSQL, a temporary table (or temp table) is a short-lived table that exists temporarily and is visible only within the current session. Once the session ends, the temporary table is automatically dropped.
Here are some key points and uses of temporary tables:
Creation:
You can create a temporary table using the CREATE TEMPORARY TABLE
or CREATE TEMP TABLE
command:
CREATE TEMPORARY TABLE temp_table_name (column_definitions);
For example:
CREATE TEMP TABLE temp_users AS SELECT * FROM users WHERE active = false;
Visibility:
Lifespan:
By default, a temporary table will last only for the duration of the session in which it was created.
You can also specify the ON COMMIT
option to drop the table at the end of a transaction. For instance:
CREATE TEMP TABLE temp_table_name (column_definitions) ON COMMIT DROP;
Usage:
Temporary tables can be useful in various scenarios:
Location:
Temporary tables are generally stored in the pg_temp
schema. However, you don't need to specify the schema when referencing them.
Indexes:
You can create indexes on temporary tables, which can improve the performance of queries involving the temp table. Remember, like the table itself, these indexes are temporary and will be dropped at the end of the session.
Considerations:
Always think about the specific needs of your operations and the potential impacts on the database system when deciding to use temporary tables.
PostgreSQL create temporary table example:
To create a temporary table in PostgreSQL, use the CREATE TEMPORARY TABLE
statement:
CREATE TEMPORARY TABLE temp_table ( id SERIAL PRIMARY KEY, name VARCHAR(255) );
Create temporary table with data in PostgreSQL: You can create a temporary table and insert data in a single query:
CREATE TEMPORARY TABLE temp_table AS SELECT id, name FROM source_table WHERE condition;
Insert into temporary table in PostgreSQL: Insert data into a temporary table:
INSERT INTO temp_table (name) VALUES ('John'), ('Jane'), ('Doe');
Drop temporary table in PostgreSQL: Drop a temporary table at the end of the session or when it's no longer needed:
DROP TEMPORARY TABLE IF EXISTS temp_table;