Example
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
| Option | Scope | Use it when |
|---|---|---|
| CTE | One statement | You want to organise a query without reusing the result in later statements. |
| Temporary table | Session/connection or transaction, depending on the engine | You need several operations on the same intermediate set. |
| Permanent CTAS | Until the table is dropped | The 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
| Engine | Form | Typical lifetime |
|---|---|---|
| PostgreSQL | CREATE TEMP TABLE | Dropped when the session ends; ON COMMIT lets you keep the rows, empty them or drop the table when the transaction ends. |
| MySQL | CREATE TEMPORARY TABLE | Visible only in the current session and dropped automatically when it closes. |
| SQLite | CREATE TEMP TABLE | Created 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.