Temporary Tables
Learn how to create session-only tables in MySQL to hold intermediate results during complex, multi-step operations.
Introduction
Sometimes a task is too complex to solve with a single query. You might need to calculate some intermediate numbers first, store them somewhere, and then run further queries against that intermediate result. Creating a brand-new permanent table just for this throwaway purpose would clutter your database forever.
MySQL solves this problem with temporary tables — tables that exist only for the lifetime of your current session and vanish automatically afterward, leaving no cleanup for you to do.
- What a temporary table is and how it differs from a normal table.
- Why temporary tables are useful for multi-step processes.
- How to create one with CREATE TEMPORARY TABLE.
- What happens to a temporary table when your session ends.
What is a Temporary Table?
A temporary table is a special kind of table that is automatically dropped (deleted) as soon as the database session or connection that created it is closed. While it exists, you can use it exactly like a normal table — you can insert into it, select from it, update it, and join it with other tables.
The key difference is visibility: a temporary table is only visible to the exact connection that created it. If two different users, or two different application connections, each create a temporary table with the same name, they do not clash — each connection sees only its own private copy.
A temporary table is like scratch paper you use while solving a problem. You write on it, use it to work things out, and once you are done (and you leave the room), it gets thrown away automatically. Nobody else can read your scratch paper while you are using it, either.
Why Use Temporary Tables?
Temporary tables shine whenever a task needs to happen in stages. Rather than writing one giant, hard-to-read query with deeply nested subqueries, you can break the problem down: store an intermediate result in a temporary table, then run simpler follow-up queries against it.
Multi-Step Processing
Break a complex calculation into smaller, easier-to-read steps.
Reusing a Result
Calculate an expensive result once, then query it multiple times without recalculating.
Session-Private
Other users and connections cannot see or interfere with your temporary table.
Automatic Cleanup
No need to remember to DROP the table — MySQL removes it for you.
Creating a Temporary Table
You create a temporary table with the CREATE TEMPORARY TABLE statement. The syntax for defining columns is identical to a normal CREATE TABLE statement — the only difference is the TEMPORARY keyword.
CREATE TEMPORARY TABLE high_value_orders (
order_id INT,
customer_name VARCHAR(50),
total_amount DECIMAL(10, 2)
);Imagine you need to find all orders worth more than $500, and then run several different reports against just that subset. Instead of repeating the same filtering logic in every report query, you can filter once into a temporary table.
INSERT INTO high_value_orders (order_id, customer_name, total_amount)
SELECT order_id, customer_name, total_amount
FROM orders
WHERE total_amount > 500;Working with a Temporary Table
Once created and populated, you can query a temporary table exactly like any other table. Here we run two separate "reports" against the same intermediate data, without ever touching the original, much larger orders table again.
-- Report 1: How many high-value orders are there in total?
SELECT COUNT(*) AS total_high_value_orders
FROM high_value_orders;
-- Report 2: List them, highest first
SELECT customer_name, total_amount
FROM high_value_orders
ORDER BY total_amount DESC;+-------------------------+
| total_high_value_orders |
+-------------------------+
| 3 |
+-------------------------+
+---------------+--------------+
| customer_name | total_amount |
+---------------+--------------+
| Priya Shah | 980.00 |
| Alex Turner | 725.50 |
| Sam Lee | 512.00 |
+---------------+--------------+You can also update rows, add indexes, or even join a temporary table with a permanent one, just as you would with any regular table.
SELECT h.customer_name, h.total_amount, c.email
FROM high_value_orders h
JOIN customers c ON c.name = h.customer_name;What Happens When the Session Ends
The defining feature of a temporary table is that it disappears automatically once your session ends — whether that means closing your MySQL Workbench connection, disconnecting your application, or the connection timing out.
-- While your session is open:
SELECT * FROM high_value_orders; -- works fine, returns rows
-- ...after you disconnect and reconnect (a brand new session)...
SELECT * FROM high_value_orders; -- ERROR!ERROR 1146 (42S02): Table 'shop.high_value_orders' doesn't existThis is expected and correct behavior — not a bug. The table was never meant to survive past your session. If you need the data to persist permanently, insert it into a normal, permanent table instead.
Do not rely on a temporary table to store anything you need later. If your connection drops unexpectedly (for example, your network hiccups), the temporary table — and everything in it — disappears immediately, with no warning and no recovery.
Temporary Tables and Naming
Because a temporary table is only visible within the session that created it, it can safely share the exact same name as a permanent table. MySQL will use the temporary one whenever both exist, for the duration of that session.
CREATE TABLE orders (id INT, total DECIMAL(10,2)); -- permanent table
CREATE TEMPORARY TABLE orders (id INT, total DECIMAL(10,2)); -- temporary table, same name
SELECT * FROM orders; -- refers to the TEMPORARY table while it exists
DROP TEMPORARY TABLE orders;
SELECT * FROM orders; -- now refers to the permanent table againYou do not have to wait for the session to end. You can drop a temporary table early yourself with DROP TEMPORARY TABLE table_name; — useful if you want to reuse the same name for a second batch of intermediate results within the same session.
Common Mistakes
- Expecting a temporary table to still exist the next time you connect — it will not.
- Using a temporary table to share data between two different applications or users — they cannot see each other's temporary tables.
- Forgetting the TEMPORARY keyword and accidentally creating (or overwriting) a permanent table.
- Relying on a temporary table as a backup — a dropped connection destroys it instantly.
Best Practices
- Use temporary tables to simplify genuinely multi-step queries, not as a habit for every query.
- Give temporary tables clear, descriptive names so your intent is obvious to anyone reading the script.
- Add indexes to a temporary table if it will be queried many times and is large.
- Explicitly DROP TEMPORARY TABLE when you are done with it early in a long-running session, to free up resources sooner.
Frequently Asked Questions
Can two different connections create a temporary table with the same name?
Yes. Temporary tables are private to the session that created them, so there is no conflict, even with an identical name.
Can I use a temporary table to pass data between two separate scripts?
Only if both scripts run within the exact same session/connection. Across separate connections, temporary tables are invisible to each other.
Do temporary tables support indexes and constraints?
Yes, temporary tables support most of the same features as regular tables, including indexes, though some advanced features may be more limited.
Is a temporary table the same as a view?
No. A view is a saved, permanent, virtual query definition that anyone with access can use. A temporary table physically stores its own rows and is private to one session.
What happens if I forget to drop a temporary table?
Nothing bad — MySQL automatically drops it for you the moment your session ends, so no manual cleanup is strictly required.
Key Takeaways
- A temporary table is created with CREATE TEMPORARY TABLE and behaves like a normal table while it exists.
- It is visible only to the session/connection that created it.
- It is automatically dropped when that session or connection ends.
- Temporary tables are ideal for holding intermediate results in a multi-step process.
- You can drop one early yourself with DROP TEMPORARY TABLE.
Summary
Temporary tables give you a safe, self-cleaning scratch space for breaking complex tasks into simpler steps, without permanently cluttering your database schema.
In this lesson, you learned what a temporary table is, why it is useful, how to create and populate one, and what happens to it once your session ends. Next, you will learn how to move data in and out of MySQL entirely, by importing and exporting databases.
- You understand what a temporary table is and how its lifecycle works.
- You can create, populate, and query a temporary table.
- You know temporary tables are private to the session that created them.
- You are ready to learn about importing and exporting databases.