SQL Temporary Tables: Scope, Lifetime and Practical Examples

A temporary table stores intermediate rows with an engine-defined session or transaction lifetime, separate from ordinary persistent application tables.

Lesson 59 of 102Intermediate10 min read

A temporary table stores intermediate rows with an engine-defined session or transaction lifetime, separate from ordinary persistent application tables.

Temporary tables are useful when several steps need the same prepared data. They are not the same as a CTE, which names a query within one statement. Choose the tool according to reuse, scope and whether stored intermediate results are actually needed.

This reference adds detail to the main course. You can read it independently: the small database below supplies every table and row used in the examples. Start with the question each query answers, then compare the returned values with the data rather than memorising a line of syntax.

Set up the practice database

Run this setup once in a new practice database, before the examples. It uses four customers and six sales. Ana has two sales, Ben has one, Cara has two, and Dev has none.

Sale 106 has no customer link; sale 104 has an unknown amount. These deliberate test cases expose missing information and unmatched relationships.

SQL
CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name VARCHAR(40) NOT NULL,
  city VARCHAR(40),
  manager_id INTEGER
);
CREATE TABLE sales (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER,
  amount DECIMAL(10,2),
  status VARCHAR(20) NOT NULL,
  created_on DATE NOT NULL
);
INSERT INTO customers (id,name,city,manager_id) VALUES
  (1,'Ana','Leeds',NULL),(2,'Ben','Leeds',1),
  (3,'Cara','Porto',1),(4,'Dev',NULL,2);
INSERT INTO sales (id,customer_id,amount,status,created_on) VALUES
  (101,1,10,'paid','2026-01-01'),
  (102,1,30,'pending','2026-01-02'),
  (103,2,20,'paid','2026-01-02'),
  (104,3,NULL,'pending','2026-02-01'),
  (105,3,20,'paid','2026-02-02'),
  (106,NULL,5,'paid','2026-02-03');

An amount of zero would be a known value. The NULL amount here means the value is unknown. A customer with no matching sale differs from a sale whose customer_id is NULL.

The primary keys identify individual records even when amounts or cities repeat. Dates use year-month-day format. The examples specify sorting whenever order matters; insertion order alone does not guarantee display order.

How Temporary tables works

A temporary table is a real table-like object that can hold rows, be queried repeatedly and often be indexed. It can stage a filtered sales subset for several calculations without repeating the preparation query. Its lifetime is limited according to the engine’s rules, usually to a connection or a transaction option. The rows are a snapshot of what was inserted, not a live view that automatically incorporates later source changes.

PostgreSQL uses CREATE TEMP TABLE and can specify ON COMMIT behaviour. MySQL uses CREATE TEMPORARY TABLE. SQLite uses CREATE TEMP TABLE in the connection’s temporary database. SQL Server commonly prefixes a local temporary table name with a single hash sign. A global hash-prefixed table has different visibility rules and should not be used casually as if it were private to one session. A normal name without the temporary feature remains a permanent table even if an application plans to delete it later.

Connection scope and pooled connections

Connection scope matters in applications with pools. Creating a temporary object through one connection and reading it through another can produce a missing-table error or unintended behaviour. Ensure the entire workflow uses the intended connection and cleans up according to the engine’s lifetime rules. A pooled connection can outlive one request, so do not assume the end of an HTTP response always closes the database session or removes every session object.

Temporary data has costs: creation, insertion, storage and possible statistics or indexing work. A CTE or derived table can be simpler when the intermediate result is used only once. A temporary table can be useful when the same staged result is reused, must have deliberate indexes, or helps divide a complex transformation into observable steps. Inspect row counts and totals after staging to catch accidental duplicate joins or incomplete filters before later reports consume the intermediate data.

MySQL, PostgreSQL, SQL Server and SQLite

The shown CREATE TEMP TABLE spelling is suitable for PostgreSQL and SQLite. Use CREATE TEMPORARY TABLE in MySQL, and a local #paid_stage table with CREATE TABLE in SQL Server. PostgreSQL ON COMMIT options and SQL Server local/global visibility are separate features, not portable lifetime declarations.

Check the engine-specific syntax and version requirements in PostgreSQL temporary tables, SQL Server temporary tables.

Practice task and worked solution

On the same PostgreSQL or SQLite connection, query the paid_stage table to find its smallest and largest known amount.

Try the task before reading its worked solution. The supplied rows make the expected answer checkable by hand.

SQL
SELECT MIN(amount) AS smallest,MAX(amount) AS largest FROM paid_stage;
Output
smallest | largest
5 | 20

The staged values are ten, twenty, twenty and five. The pending thirty is not in the stage, so its maximum is twenty rather than the full sales table’s thirty. This confirms that subsequent queries read the stored subset, not the live source definition.

Query paid_stage repeatedly to demonstrate statement-to-statement reuse on one connection. In a separate connection, check whether the local temporary object is visible; it should not be assumed shared. Change source data in a disposable setup and verify the staged rows stay as inserted. Rebuild or refresh the stage deliberately before calling it a current report.

SQL Temporary Tables: Scope, Lifetime and Practical Examples Syntax

Temporary tables

-- PostgreSQL or SQLite temporary-table example.
CREATE TEMP TABLE paid_stage (id INTEGER PRIMARY KEY,amount DECIMAL(10,2));
INSERT INTO paid_stage (id,amount)
SELECT id,amount FROM sales WHERE status='paid';
SELECT COUNT(*) AS rows_staged,SUM(amount) AS total FROM paid_stage;

SQL Temporary Tables: Scope, Lifetime and Practical Examples Summary

  • A temporary table holds rows for the current session or transaction and is removed automatically afterwards.
  • Unlike a CTE, it can be queried, indexed and reused across several statements.
  • Syntax differs: CREATE TEMP TABLE in PostgreSQL and SQLite, CREATE TEMPORARY TABLE in MySQL and #name tables in SQL Server.
  • Temporary rows are a snapshot; they don't follow later changes to the source tables.
  • With connection pools, make sure every step uses the same connection and clean up explicitly.

SQL Temporary Tables: Scope, Lifetime and Practical Examples Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Staging paid sales in a temporary table

The temporary destination receives the four paid sale rows, including the anonymous paid sale. The verification count and sum describe the stored stage. A later change to sales does not automatically refresh paid_stage.

SQL
-- PostgreSQL or SQLite temporary-table example.
CREATE TEMP TABLE paid_stage (id INTEGER PRIMARY KEY,amount DECIMAL(10,2));
INSERT INTO paid_stage (id,amount)
SELECT id,amount FROM sales WHERE status='paid';
SELECT COUNT(*) AS rows_staged,SUM(amount) AS total FROM paid_stage;
Output
rows_staged | total
4 | 55

Common SQL Temporary Tables: Scope, Lifetime and Practical Examples Mistakes

Reading a temp table from another connection

Creating a temporary table in one pooled connection and querying through another does not share the intended session object. Keeping a temporary stage around can also leave stale results after source changes. Make the connection boundary and refresh step explicit in the workflow.

SQL Temporary Tables: Scope, Lifetime and Practical Examples in Real Projects

Staging data for a multi-step report job

A multi-step reporting job can stage qualifying paid sales once, validate its count and total, and then build several exports from that same snapshot. Keep the stage private to the job where possible. A stable intermediate result can simplify reconciliation when the source remains active during report generation.

Keep a staged-report workflow on the intended connection and define when the stage is refreshed. In a pool, a session may continue after an application request ends. Temporary data can therefore outlive a request or be unavailable on another borrowed connection. Capture counts and totals at staging time so later outputs can be reconciled with that snapshot.

SQL Temporary Tables: Scope, Lifetime and Practical Examples FAQ

Is a temporary table a CTE?

No. A CTE belongs to one statement and disappears when it finishes. A temporary table is stored and can be reused across statements in its allowed scope, and it can have indexes, which helps when a large intermediate result is used several times.

Are temporary rows automatically current?

No. They reflect the rows inserted into the object at the time; later changes to the source tables don't appear. Refresh the stage deliberately, or use a view when you need always-current results.

Does ending a web request remove session tables?

Not necessarily. Connection pools can hand the same database session to the next request, so a temporary table may still exist, or be missing from a different pooled connection. Manage cleanup and lifetime explicitly, for example with DROP TABLE IF EXISTS at the start and end of the job.

Can other users see my temporary table?

No. A temporary table is private to the session that created it, so two users can each have a temporary table with the same name. SQL Server's global temporary tables, named with ##, are the exception and are visible to all sessions.

Should I index a temporary table?

If it's large and later queries filter or join on a column, yes: create the index after loading the rows, which is faster than maintaining it during the load. For a few hundred rows, an index rarely makes a difference.

SQL Temporary Tables: Scope, Lifetime and Practical Examples Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choicemedium

What are the smallest and largest known values in paid_stage?

SQL Temporary Tables: Scope, Lifetime and Practical Examples Quiz

2 questions to check what you learned.

  1. Does a temporary table automatically refresh from its source?

    • Yes, every SELECT reruns the original insertion source
    • Yes, but only when the source and stage use the same column names
    • No, it holds the rows inserted into it
  2. Which SQL Server name commonly denotes a local temporary table?

    • #paid_stage
    • paid_stage without a prefix, which always becomes temporary
    • ##paid_stage, which has global rather than local temporary-table semantics