TEMPORARY (or its shorthand TEMP) is a modifier placed in front of CREATE TABLE, CREATE VIEW, and in some systems CREATE SEQUENCE or INDEX. A temporary object is stored in a separate internal schema and is visible only to the session that created it. The object is removed implicitly when the session ends, or earlier if the database supports transaction-scoped lifetimes via ON COMMIT clauses.Key points:- Scope: Visible only inside the connection that created it. Other sessions cannot read or write to the object, even if they use the same name.- Lifetime: Dropped automatically at session end. PostgreSQL allows ON COMMIT PRESERVE ROWS, DELETE ROWS, or DROP to control earlier cleanup. MySQL always drops on session close.- Persistence: Not logged in the main catalog, so temporary objects do not survive server restarts or failovers.- Permissions: Users need CREATE TEMPORARY TABLE or general CREATE rights. Temp objects bypass some naming or foreign-key checks because they reside in an isolated namespace.- Performance: Useful for staging intermediate results, breaking complex queries into steps, or caching lookups without polluting permanent schemas.Caveats:- Name collisions: A temp table can mask a permanent table of the same name inside the session, potentially leading to confusion.- Storage limits: Large temp tables can consume disk on temp tablespaces and may affect other sessions.- Unsupported features: Some engines disallow foreign keys, triggers, or indexes on temp objects, or implement them differently.
CREATE TABLE, GLOBAL TEMPORARY, ON COMMIT, DROP TABLE, WITH (CTE)
SQL:1999
Primarily tables. PostgreSQL also allows TEMPORARY views, sequences, and indexes. Other engines restrict it to tables only.
It lasts for the lifetime of the session unless the engine supports transaction-scoped temp tables. In PostgreSQL you can control this with ON COMMIT.
Yes. Inside the session the temp table masks the permanent one. Outside the session the permanent table is visible again.
Not usually. The database cleans it up automatically, but you can drop it explicitly with DROP TABLE if required for resource management.