Concept · Advanced SQL

Temporary tables in SQL: CREATE TEMP and TEMPORARY TABLE

A temporary table holds working data for the session, or for whatever context the engine defines. You can reuse it across several statements.

Example

SQLite 3.46.1 · verified
CREATE TEMP TABLE large_orders AS
SELECT id, customer_id, total
FROM orders
WHERE total >= 200;

SELECT COUNT(*) AS orders,
       ROUND(SUM(total), 2) AS amount
FROM large_orders;

The first statement materialises five rows in the temporary table. The second works on that set without repeating the original filter.

How it is used

A CTE organises one statement. A permanent table is part of the persistent model. A temporary table sits in between: it materialises data so you can reuse it during a short piece of work, and then it disappears according to the engine's rules.

A useful question: if the result is used only once, a CTE or subquery is usually simpler. If you need to read, transform or index the same set across several statements, a temporary table can be clearer.

What changes from case to case

Which tool fits best
OptionScopeUse it when
CTEOne statementYou want to organise a query without reusing the result in later statements.
Temporary tableSession/connection or transaction, depending on the engineYou need several operations on the same intermediate set.
Permanent CTASUntil the table is droppedThe result must persist as an ordinary object after the session.

Avoid this confusion

Using a temporary table for a single trivial read

Creating, filling and dropping a table adds steps. If a CTE expresses the intent clearly within a single statement, it is usually the simpler option.

Assuming they all last until the same point

PostgreSQL lets you control the behaviour on COMMIT; MySQL documents session scope; SQLite puts the table in its temporary database. The life cycle depends on the engine.

Forgetting that you are materialising data

If the source tables change, a temporary table that has already been filled does not update itself. You have to reload it if you need it to reflect new data.

Key differences between engines
Temporary table scope at a glance
EngineFormTypical lifetime
PostgreSQLCREATE TEMP TABLEDropped when the session ends; ON COMMIT lets you keep the rows, empty them or drop the table when the transaction ends.
MySQLCREATE TEMPORARY TABLEVisible only in the current session and dropped automatically when it closes.
SQLiteCREATE TEMP TABLECreated in the temporary database attached to the connection.

Because of these differences, avoid stating a single universal rule about exactly when the table is dropped. Always check the engine and, in PostgreSQL, whether the table uses the clause ON COMMIT.