- 1 1. (Beginner-Friendly) What Is a MySQL Temporary Table? Differences from Regular Tables
- 2 2. (With Sample Code) How to Create a Temporary Table in MySQL
- 3 3. How to Manipulate Data in a MySQL Temporary Table (INSERT, UPDATE, DELETE)
- 4 4. Are MySQL Temporary Tables Automatically Dropped? How to Drop Them Manually
- 5 5. 5 Practical Use Cases for MySQL Temporary Tables (Including Performance Optimization)
- 6 6. Three Important Precautions When Using MySQL Temporary Tables Safely
- 7 7. 10 Frequently Asked Questions (FAQ) About MySQL Temporary Tables
- 8 8. Summary: Key Points for Using MySQL Temporary Tables Effectively
1. (Beginner-Friendly) What Is a MySQL Temporary Table? Differences from Regular Tables
Introduction
When managing data with MySQL, there are times when you need to store data temporarily. For example, when processing a large dataset, you may want to save intermediate results while you work. In those cases, a temporary table (Temporary Table) is very useful.
In this article, we will explain the basic mechanism of MySQL temporary tables and how they differ from regular tables.
1-1. What Is a Temporary Table?
A temporary table is a special table that exists only during a database session (connection).
Unlike a regular table, it is automatically removed when the session ends, making it ideal for storing temporary data.
Main Features of Temporary Tables
- Isolated per session
A temporary table can be accessed only within the session that created it. Other sessions cannot reference it. - Automatically removed when the session ends
Temporary tables disappear automatically when the session ends, even if you do not drop them explicitly. - You can create temporary tables with the same name
Unlike regular tables, it is possible to create temporary tables with the same name in different sessions.
1-2. Differences from Regular Tables
Temporary tables and regular tables differ in the following ways.
| Comparison | Temporary Table | Regular Table |
|---|---|---|
| Data retention | Valid only during the session (automatically removed) | Stored permanently |
| Access scope | Only within the session that created it | Accessible to all users (subject to privileges) |
| Name conflicts | You can create temporary tables with the same name | You cannot create another table with the same name in the same database |
| Required privileges | Requires the CREATE TEMPORARY TABLES privilege | Requires the standard CREATE TABLE privilege |
| Indexes | Supported | Supported |
| Performance | Often created in memory and can be fast | Stored on disk; performance can degrade as data grows |
Which one should you use?
- If you only need the data temporarily and it can be discarded after processing → Temporary table
- If you want to keep the data permanently and reuse it later → Regular table
For example, temporary tables are very useful for tasks like large-scale data analysis or temporary aggregation.
1-3. When You Need a Temporary Table
MySQL temporary tables are especially useful in the following situations.
1) Improve query performance
For example, when performing complex JOIN operations, you can reduce processing time by creating a temporary table to store intermediate data in advance.
Example: Reduce JOIN overhead
CREATE TEMPORARY TABLE temp_users AS
SELECT id, name FROM users WHERE status = 'active';By storing the target data in a temporary table first and then running the JOIN, performance can improve.
2) Store data temporarily
Temporary tables are also useful when an application needs to manage data temporarily.
For example, you can store data a user searched for in a temporary table and have it removed after the session ends.
3) Intermediate tables for batch processing
When processing large amounts of data, using temporary tables as intermediate tables can improve the stability of the process.
1-4. Limitations of Temporary Tables
Temporary tables are convenient, but there are a few limitations.
1) Automatically removed when the session ends
Because temporary tables are automatically removed when the session ends, they are not suitable for storing data permanently.
2) Not accessible from other sessions
Temporary tables can be used only within the session that created them, so they cannot be shared with other users or processes.
3) Potential conflict with a regular table of the same name
If a regular table with the same name exists, creating a temporary table with that name will make the regular table temporarily invisible, so be careful.
CREATE TEMPORARY TABLE users (id INT, name VARCHAR(255));
SELECT * FROM users; -- This query references the temporary table dataAs shown above, once a temporary table is created, you cannot access the regular table with the same name until the temporary table is gone. Choose table names carefully.
Summary
MySQL temporary tables are a convenient feature for temporary data storage and query optimization.
By understanding how they differ from regular tables and using them appropriately, you can process data more efficiently.
✔ Quick recap
- Temporary tables are automatically removed when the session ends
- Unlike regular tables, they are isolated per session
- Great for temporary storage and improving query performance
- Not suitable for permanent storage because data disappears when the session ends
- Not accessible from other sessions, and can conflict with regular tables of the same name
2. (With Sample Code) How to Create a Temporary Table in MySQL
Introduction
In the previous section, we explained the basic concept of temporary tables and how they differ from regular tables.
In this section, we will walk through how to create a temporary table and how to work with data in it.
Creating a temporary table is simple, but if you do not use the correct syntax, it may not behave as expected. This section explains basic syntax, creating from an existing table, and how to confirm temporary tables in detail.
2-1. Basic Syntax for a Temporary Table
To create a temporary table, use the CREATE TEMPORARY TABLE statement.
Basic syntax
CREATE TEMPORARY TABLE table_name (
column_name data_type [constraints],
column_name data_type [constraints],
...
);The syntax is almost the same as CREATE TABLE, but adding TEMPORARY makes it a temporary table.
Example: Store user information in a temporary table
CREATE TEMPORARY TABLE temp_users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);This temp_users table is valid only in the current session and is automatically removed when the session ends.
2-2. Create a Temporary Table Based on Data from an Existing Table
You can also create a temporary table based on data from an existing table.
Syntax
CREATE TEMPORARY TABLE temp_table_name AS
SELECT * FROM existing_table WHERE condition;Example: Store only active users in a temporary table
CREATE TEMPORARY TABLE active_users AS
SELECT id, name, email FROM users WHERE status = 'active';This method extracts only users with status = 'active' from the users table and stores them in a new temporary table named active_users.
Key points
- Copies data from an existing table as-is
- Column data types are set automatically
- Indexes are not copied, so add them explicitly if needed
2-3. How to Check Temporary Table Data
List tables
SHOW TABLES;However, a temporary table will not appear in the list from a normal SHOW TABLES.
Check the structure of a temporary table
DESC temp_users;or
SHOW CREATE TABLE temp_users;This lets you check column structure and constraints for the temporary table.
2-4. Insert Data into a Temporary Table
Inserting data into a temporary table is the same as with a regular table.
Insert data
INSERT INTO temp_users (name, email) VALUES
('Taro Tanaka', 'tanaka@example.com'),
('Hanako Sato', 'sato@example.com');Check the data
SELECT * FROM temp_users;This confirms that data has been stored in the temporary table.
2-5. Notes When Creating Temporary Tables
1) Watch out for table name conflicts
If you create a temporary table with the same name as a regular table, the temporary table takes precedence, and the regular table becomes temporarily inaccessible.
CREATE TEMPORARY TABLE users (id INT, name VARCHAR(50));
SELECT * FROM users; -- This returns data from the temporary tableFor this reason, it is recommended to use a prefix like “temp_” for temporary table names.
2) Indexes are not inherited automatically
When you copy data from an existing table, indexes are not applied automatically.
If needed, you must add indexes explicitly.
ALTER TABLE temp_users ADD INDEX (email);3) You need the privilege to create temporary tables
To create a temporary table, you need the CREATE TEMPORARY TABLES privilege.
GRANT CREATE TEMPORARY TABLES ON database_name.* TO 'user'@'localhost';Without this privilege, you cannot create temporary tables.
Summary
In this section, we explained how to create temporary tables.
✔ Quick recap
- Create a temporary table with
CREATE TEMPORARY TABLE - You can also create one by copying data from an existing table
- Automatically removed when the session ends
- Indexes are not applied automatically—be careful
- Use a prefix like “temp_” to avoid name conflicts
- You need the proper privilege (
CREATE TEMPORARY TABLES)
3. How to Manipulate Data in a MySQL Temporary Table (INSERT, UPDATE, DELETE)
Introduction
In the previous section, we explained how to create a temporary table in MySQL.
In this section, we will explain how to insert, update, and delete data in a temporary table using specific SQL commands.
Temporary tables support the same data operations as regular tables,
but there are some important notes to keep in mind, which we will also cover.
3-1. Insert data into a temporary table (INSERT)
To add data to a temporary table, use the INSERT INTO statement, just like with a regular table.
Basic syntax
INSERT INTO temp_table_name (column1, column2, ...)
VALUES (value1, value2, ...);Example: Add user information
CREATE TEMPORARY TABLE temp_users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO temp_users (name, email)
VALUES
('Taro Tanaka', 'tanaka@example.com'),
('Hanako Sato', 'sato@example.com');Insert existing data using INSERT…SELECT
You can also fetch data from an existing table and insert it into a temporary table.
INSERT INTO temp_users (id, name, email)
SELECT id, name, email FROM users WHERE status = 'active';This method lets you store only active users in a temporary table.
3-2. Update data in a temporary table (UPDATE)
To change data in a temporary table, use the UPDATE statement.
Basic syntax
UPDATE temp_table_name
SET column_name = value
WHERE condition;Example: Update a user’s name
UPDATE temp_users
SET name = 'Ichiro Tanaka'
WHERE email = 'tanaka@example.com';Bulk update for rows that match a condition
For example, if you want to change email addresses under a specific domain to example.jp, you can write:
UPDATE temp_users
SET email = REPLACE(email, 'example.com', 'example.jp')
WHERE email LIKE '%@example.com';3-3. Delete data from a temporary table (DELETE)
To delete data, use the DELETE statement.
Basic syntax
DELETE FROM temp_table_name WHERE condition;Example: Delete a specific user’s data
DELETE FROM temp_users WHERE email = 'tanaka@example.com';Delete all rows (difference from TRUNCATE)
If you want to delete all rows, you can write:
DELETE FROM temp_users;In contrast, for regular tables, you can often delete all rows faster using TRUNCATE TABLE. However, you cannot use TRUNCATE on a temporary table in MySQL.
TRUNCATE TABLE temp_users; -- Error (cannot be used on temporary tables in MySQL)Therefore, to remove all rows from a temporary table, you must use DELETE.
3-4. Notes when manipulating data in a temporary table
1) Data disappears when the session ends
A temporary table is automatically removed when the session (connection) ends,
so it is not suitable for use cases that require persistent data storage.
2) Not accessible from other sessions
A temporary table is valid only within the session that created it, and cannot be accessed from other sessions.
SELECT * FROM temp_users;If you run this SQL in a different session, you will get the error “Table ‘temp_users’ doesn’t exist”.
3) Indexes on temporary tables are not applied automatically
If you create a table using CREATE TEMPORARY TABLE ... AS SELECT ...,
indexes from the original table are not inherited. If needed, add indexes manually using ALTER TABLE.
ALTER TABLE temp_users ADD INDEX (email);Summary
In this section, we covered data manipulation (INSERT, UPDATE, DELETE) for temporary tables.
✔ Quick recap
- Use INSERT to add data (
INSERT INTO ... VALUES/INSERT INTO ... SELECT) - Use UPDATE to modify data (conditional updates and leveraging
REPLACE()) - Use DELETE to remove data (
DELETE FROM ... WHERE;TRUNCATEis not allowed) - The temporary table is removed when the session ends
- Not accessible from other sessions
- Indexes are not inherited automatically; add them manually if needed
4. Are MySQL Temporary Tables Automatically Dropped? How to Drop Them Manually
Introduction
Unlike regular tables, a MySQL temporary table (Temporary Table) is automatically removed when the session ends. However, there are cases where you may need to drop it manually.
In this section, we explain how automatic removal works and how to drop temporary tables manually in detail.
4-1. How automatic removal works for temporary tables
1) Automatically removed when the session ends
A MySQL temporary table is automatically removed when the session (database connection) that created it ends.
Because of this, you usually do not need to drop it manually.
Example: Automatic removal when the session ends
-- Create a temporary table in a new session
CREATE TEMPORARY TABLE temp_users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(100)
);
-- Insert data
INSERT INTO temp_users (name, email) VALUES ('Taro Tanaka', 'tanaka@example.com');
-- End the session (disconnect the MySQL client)
EXIT;At this point, the temporary table temp_users is automatically removed.
2) The temporary table remains as long as the session continues
Because temporary tables are managed per session, they are not removed as long as the session remains open.
SELECT * FROM temp_users; -- Data can be retrieved if the session is still activeIn other words, the temporary table stays in memory until you close the MySQL client (or the program disconnects).
4-2. How to drop a temporary table manually
You can also drop temporary tables manually.
In MySQL, use DROP TEMPORARY TABLE to remove a temporary table.
1) Use DROP TEMPORARY TABLE
DROP TEMPORARY TABLE temp_users;This immediately removes the temporary table temp_users.
2) Add IF EXISTS to avoid errors
If the table does not exist, you can use IF EXISTS to avoid an error.
DROP TEMPORARY TABLE IF EXISTS temp_users;This syntax prevents errors even if the table does not exist.
3) Different from a normal DROP TABLE
If you try to drop a temporary table using a normal DROP TABLE, you may see an error like the following:
DROP TABLE temp_users;Error:
ERROR 1051 (42S02): Unknown table 'temp_users'Because MySQL manages regular tables and temporary tables separately, you must use DROP TEMPORARY TABLE when dropping a temporary table.
4-3. How to confirm a temporary table was dropped
1) You cannot confirm with SHOW TABLES
A temporary table will not appear in the output of SHOW TABLES.
SHOW TABLES;→ Temporary tables are not listed
2) Confirm using INFORMATION_SCHEMA
You can check whether a temporary table exists by querying INFORMATION_SCHEMA.
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'temp_users';If this query returns a result, it indicates that the temporary table exists.
4-4. Notes when dropping temporary tables
1) Temporary tables differ by session
You can create temporary tables with the same name in multiple sessions.
You cannot drop a temporary table created by another session.
Example
-- Created in session A
CREATE TEMPORARY TABLE temp_data (id INT);
-- Attempt to drop in session B
DROP TEMPORARY TABLE temp_data;An error occurs:
ERROR 1051 (42S02): Unknown table 'temp_data'A temporary table can be dropped only in the session that created it.
2) Potential conflict with a regular table of the same name
If a temporary table has the same name as a regular table,
the temporary table takes precedence, and the regular table becomes invisible.
Example
-- A regular table (users) exists
SELECT * FROM users;
-- Create a temporary table with the same name
CREATE TEMPORARY TABLE users (id INT, name VARCHAR(50));
-- This now references the temporary table users
SELECT * FROM users;Solution:
- Use a prefix like
temp_for temporary tables to avoid naming conflicts.
Summary
In this section, we explained how temporary table removal works and how to drop them.
✔ Quick recap
- Temporary tables are automatically removed when the session ends
- They remain as long as the session is active
- To drop manually, use
DROP TEMPORARY TABLE - Add
IF EXISTSto avoid errors - You cannot confirm temporary tables with
SHOW TABLES - You can drop a temporary table only in the session that created it
- Use a prefix to avoid conflicts with regular tables of the same name
5. 5 Practical Use Cases for MySQL Temporary Tables (Including Performance Optimization)
Introduction
MySQL temporary tables allow you to store intermediate data and simplify complex queries, helping to improve database performance.
In this section, we introduce five practical use cases for temporary tables.
We explain how they can be used in real-world scenarios, along with sample SQL.
5-1. Optimize Query Performance (Reduce JOIN Overhead)
Problem
When processing large datasets, executing JOIN operations directly can degrade performance.
Solution
Use a temporary table to pre-filter target data before performing the JOIN, reducing processing overhead.
Example: Retrieve order data for active users
-- First, store only active users in a temporary table
CREATE TEMPORARY TABLE temp_active_users AS
SELECT id, name FROM users WHERE status = 'active';
-- Perform JOIN using the temporary table
SELECT o.order_id, t.name, o.total_price
FROM orders o
JOIN temp_active_users t ON o.customer_id = t.id;Benefits
- Reduces JOIN workload by targeting only active users instead of the entire
userstable - Simplifies the main query, improving readability
5-2. Temporary Aggregation Processing
Problem
Repeatedly running the same aggregation query can reduce performance.
Solution
Store aggregation results in a temporary table once to avoid unnecessary repeated calculations.
Example: Store monthly sales data in a temporary table
-- Calculate monthly total sales and store in a temporary table
CREATE TEMPORARY TABLE temp_monthly_sales AS
SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total_price) AS total_sales
FROM orders
GROUP BY month;
-- Retrieve aggregated results
SELECT * FROM temp_monthly_sales WHERE total_sales > 100000;Benefits
- Reuse aggregated data multiple times
- Improve performance by avoiding redundant calculations
5-3. Store Intermediate Data for Batch Processing
Problem
When performing bulk updates or deletes, errors during processing can leave data in an inconsistent state.
Solution
Use a temporary table to store intermediate data and maintain data consistency.
Example: Update order data under specific conditions
-- Store target rows in a temporary table
CREATE TEMPORARY TABLE temp_orders AS
SELECT order_id, total_price FROM orders WHERE status = 'pending';
-- Perform update based on the temporary table
UPDATE orders o
JOIN temp_orders t ON o.order_id = t.order_id
SET o.total_price = t.total_price * 1.1; -- Increase price by 10%Benefits
- Safely update only selected data
- Easy to verify data before and after updates
5-4. Per-User Temporary Data Management
Problem
If temporary user-specific data is stored in a regular table, unnecessary data may accumulate over time.
Solution
Temporary tables automatically remove data when the session ends, eliminating maintenance overhead.
Example: Store search results in a temporary table
-- Store user-specific search results
CREATE TEMPORARY TABLE temp_search_results AS
SELECT * FROM products WHERE category = 'electronics';
-- Display search results
SELECT * FROM temp_search_results;Benefits
- Data is automatically removed when the session ends
- Temporary search results can be reused during the session
5-5. Choosing Between Temporary Tables and Views
Problem
When optimizing frequently executed queries, you may wonder whether to use a temporary table or a VIEW, especially if temporary data storage is required.
Solution
- If data does not change frequently → Use a view (VIEW)
- If data changes frequently or needs materialization → Use a temporary table
Example: Using a temporary table
CREATE TEMPORARY TABLE temp_high_value_customers AS
SELECT customer_id, SUM(total_price) AS total_spent
FROM orders
GROUP BY customer_id
HAVING total_spent > 50000;
SELECT * FROM temp_high_value_customers;Example: Using a view
CREATE VIEW high_value_customers AS
SELECT customer_id, SUM(total_price) AS total_spent
FROM orders
GROUP BY customer_id
HAVING total_spent > 50000;Benefits
- Temporary tables store data physically, which can improve performance
- Views are convenient for query reuse, but performance may decrease with large datasets
Summary
In this section, we introduced five practical use cases for MySQL temporary tables.
✔ Quick recap
- Optimize query performance (reduce JOIN overhead)
→ Store only required data in a temporary table before performing JOIN - Temporary aggregation processing
→ Store aggregated results to avoid repeated calculations - Intermediate data for batch processing
→ Safely handle large-scale updates - Per-user temporary data management
→ Data is automatically removed when the session ends - Choose between temporary tables and views
→ Use temporary tables for changing data, views for stable query reuse
6. Three Important Precautions When Using MySQL Temporary Tables Safely
Introduction
MySQL temporary tables operate independently per session and are automatically removed under certain conditions, making them a convenient feature. However, improper use can lead to performance degradation or unexpected errors.
In this section, we explain three important precautions to ensure safe use of temporary tables.
6-1. Precaution 1: Do Not Over-Rely on Automatic Removal
Problem
Because temporary tables are automatically removed when the session ends, it may seem unnecessary to drop them explicitly. However, this can sometimes cause unintended issues.
Examples of issues
- Long-running connections continue consuming memory
- If a session remains open, temporary tables are not removed and continue consuming database resources.
- Failure to drop explicitly may cause design flaws
- If a batch process reconnects unexpectedly, the temporary table may disappear and cause errors.
Solution
- Explicitly drop temporary tables when no longer needed using
DROP TEMPORARY TABLE - In long-running connections (e.g., batch jobs), drop temporary tables periodically
Example: Explicitly drop a temporary table
DROP TEMPORARY TABLE IF EXISTS temp_users;Key point
- Adding
IF EXISTSprevents errors if the table does not exist.
6-2. Precaution 2: Avoid Name Conflicts with Regular Tables
Problem
You can create a temporary table with the same name as a regular table. However, when you do so, the regular table becomes temporarily invisible.
Example of the issue
-- A regular users table exists
SELECT * FROM users;
-- Create a temporary table with the same name
CREATE TEMPORARY TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50)
);
-- This now returns data from the temporary table, not the regular one
SELECT * FROM users;As long as the temporary table exists, the regular table with the same name is hidden, which can lead to unexpected data retrieval errors.
Solution
- Use a prefix such as “temp_” for temporary table names
- Adopt a clear naming convention to distinguish temporary and regular tables
Example: Safe temporary table creation
CREATE TEMPORARY TABLE temp_users (
id INT PRIMARY KEY,
name VARCHAR(50)
);Benefits
- Using the
temp_prefix prevents conflicts with the regularuserstable. - Makes it easier to distinguish tables in application code.
6-3. Precaution 3: Indexes and Constraints Are Not Automatically Inherited
Problem
If you create a table using CREATE TEMPORARY TABLE ... AS SELECT ..., indexes and constraints from the original table are not inherited, which can degrade performance.
Example of the issue
-- Regular users table (with indexes)
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(100) UNIQUE,
name VARCHAR(50)
);
-- Create temporary table (indexes are NOT inherited)
CREATE TEMPORARY TABLE temp_users AS
SELECT id, email, name FROM users;In this case, PRIMARY KEY and UNIQUE constraints are not carried over to temp_users, which may slow searches and allow duplicate data.
Solution
- Explicitly add indexes after creating the temporary table
- If defining columns manually with
CREATE TEMPORARY TABLE, specify indexes during creation
Example: Add indexes manually
CREATE TEMPORARY TABLE temp_users (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(100) UNIQUE,
name VARCHAR(50)
);
ALTER TABLE temp_users ADD INDEX idx_email (email);This approach allows you to create a temporary table with indexes similar to the original table.
Summary
In this section, we explained three important precautions for safely using temporary tables.
✔ Quick recap
- Do not over-rely on automatic removal
- Explicitly drop temporary tables using
DROP TEMPORARY TABLE - Periodically remove them in long-running sessions
- Avoid name conflicts with regular tables
- If a regular table with the same name exists, the temporary table takes precedence
- Use a prefix like
temp_to clearly distinguish
- Indexes and constraints are not inherited automatically
- With
CREATE TEMPORARY TABLE ... AS SELECT ..., indexes are lost - Add indexes manually after creation
By keeping these points in mind, you can safely leverage MySQL temporary tables while improving database performance.
7. 10 Frequently Asked Questions (FAQ) About MySQL Temporary Tables
Introduction
In this section, we answer 10 frequently asked questions about MySQL temporary tables.
We cover how they work, their limitations, performance considerations, and troubleshooting in practical scenarios.
7-1. Questions About Basic Specifications
Q1. Can a temporary table be accessed from another session?
A. No, it cannot.
A temporary table is valid only within the session that created it and cannot be accessed from other sessions.
-- Created in Session A
CREATE TEMPORARY TABLE temp_users (
id INT PRIMARY KEY,
name VARCHAR(50)
);
-- Attempt to access from Session B (results in error)
SELECT * FROM temp_users;Error:
ERROR 1146 (42S02): Table 'temp_users' doesn't existIf you need to share data across sessions, you must use a regular table.
Q2. Are temporary tables stored on disk?
A. They are usually stored in memory, but may move to disk under certain conditions.
If the table size exceeds tmp_table_size or max_heap_table_size, MySQL may create the temporary table on disk using InnoDB or MyISAM.
SHOW VARIABLES LIKE 'tmp_table_size';To improve performance, configure tmp_table_size appropriately.
Q3. Can I create indexes on a temporary table?
A. Yes, you can.
You can define PRIMARY KEY or INDEX just like with a regular table.
CREATE TEMPORARY TABLE temp_users (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(100) UNIQUE,
name VARCHAR(50)
);
ALTER TABLE temp_users ADD INDEX idx_email (email);However, if you use CREATE TEMPORARY TABLE ... AS SELECT ..., indexes are not inherited, so you must add them manually.
7-2. Questions About Performance and Behavior
Q4. Are there changes to temporary tables in MySQL 8.0?
A. MySQL 8.0 introduced Common Table Expressions (CTEs) using the WITH clause.
From MySQL 8.0 onward, you can process temporary result sets using CTEs without explicitly creating a temporary table.
WITH temp_users AS (
SELECT id, name FROM users WHERE status = 'active'
)
SELECT * FROM temp_users;Using CTEs instead of temporary tables can simplify queries and reduce memory usage.
Q5. What is the difference between a temporary table and a MEMORY table?
A. A MEMORY table persists beyond a session, while a temporary table does not.
A temporary table is removed when the session ends, whereas a MEMORY table remains until the server restarts (or is explicitly dropped).
CREATE TABLE memory_table (
id INT PRIMARY KEY,
name VARCHAR(50)
) ENGINE=MEMORY;When to use which?
- Temporary table: Short-term, session-scoped processing
- MEMORY table: High-speed access with server-level persistence
7-3. Questions About Deletion and Troubleshooting
Q6. Can I drop a temporary table using DROP TABLE?
A. No, you must use DROP TEMPORARY TABLE.
Always use DROP TEMPORARY TABLE when removing a temporary table.
DROP TEMPORARY TABLE temp_users;Using a regular DROP TABLE may result in an error.
Q7. Why doesn’t SHOW TABLES display temporary tables?
A. Temporary tables are not listed by SHOW TABLES.
To check their existence, query INFORMATION_SCHEMA.
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'temp_users';If no result is returned, the temporary table may have already been removed.
Summary
In this section, we covered 10 frequently asked questions about MySQL temporary tables.
✔ Quick recap
- Temporary tables cannot be accessed from other sessions
- They are created in memory but may move to disk if large
- Indexes must be defined manually if using AS SELECT
- CTEs (
WITH) are available in MySQL 8.0+ - Unlike MEMORY tables, temporary tables disappear at session end
- Use
DROP TEMPORARY TABLEto remove them SHOW TABLESdoes not display temporary tables
8. Summary: Key Points for Using MySQL Temporary Tables Effectively
Introduction
MySQL temporary tables are a powerful tool for storing intermediate data and optimizing query performance.
Here, we summarize the key points discussed throughout this guide.
8-1. Basic Concepts of MySQL Temporary Tables
What is a temporary table?
- Exists independently per session
- Automatically removed when the session ends
- Supports
INSERT,UPDATE, andDELETElike a regular table
Basic creation syntax
CREATE TEMPORARY TABLE temp_users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(100)
);Main use cases
- Temporary data storage
- Query performance optimization
- Intermediate tables for batch processing
- Per-user temporary data management
8-2. Advantages of Temporary Tables
1) Improve query performance
- Reduce JOIN workload
- Perform aggregation in advance to reduce repeated calculations
- Simplify queries by excluding unnecessary data
Example: Reduce JOIN overhead
CREATE TEMPORARY TABLE temp_active_users AS
SELECT id, name FROM users WHERE status = 'active';
SELECT o.order_id, t.name, o.total_price
FROM orders o
JOIN temp_active_users t ON o.customer_id = t.id;2) Temporary storage and session-based management
- Automatically removed at session end
- Ideal for short-term data storage
- Independent data manipulation without affecting other sessions
Example: Temporary storage of search results
CREATE TEMPORARY TABLE temp_search_results AS
SELECT * FROM products WHERE category = 'electronics';
SELECT * FROM temp_search_results;3) Safe data updates
- Useful as an intermediate table in batch processing
- Can serve as a backup during data updates
- Effective for creating test datasets
Example: Safe data update
CREATE TEMPORARY TABLE temp_orders AS
SELECT order_id, total_price FROM orders WHERE status = 'pending';
UPDATE orders o
JOIN temp_orders t ON o.order_id = t.order_id
SET o.total_price = t.total_price * 1.1;8-3. Disadvantages and Precautions
1) Data disappears when the session ends
- Not suitable for permanent storage
- Use regular tables for long-term persistence
2) Cannot be shared across sessions
- Not accessible from other connections
- Use regular tables when sharing data across users
3) Indexes and constraints are not automatically inherited
CREATE TEMPORARY TABLE ... AS SELECT ...does not create indexes- Add indexes manually if required
ALTER TABLE temp_users ADD INDEX idx_email (email);8-4. Best Practices for Safe Usage
✅ Explicitly drop when no longer needed
DROP TEMPORARY TABLE IF EXISTS temp_users;✅ Avoid naming conflicts with regular tables
- Use a
temp_prefix
CREATE TEMPORARY TABLE temp_users (...);✅ Design with performance in mind
- If the table grows large and moves to disk, consider adjusting
tmp_table_size
SHOW VARIABLES LIKE 'tmp_table_size';8-5. Temporary Tables vs Alternatives (Views and CTEs)
It is also important to consider when to use temporary tables versus views (VIEW) or CTEs (Common Table Expressions).
| Method | Characteristics | Best Use Case |
|---|---|---|
| Temporary table | Removed at session end | When you need to store intermediate data |
| View (VIEW) | Data retrieved in real time; performance may degrade with large datasets | Save and reuse frequently referenced queries |
| CTE (WITH clause) | Virtual table valid only within a single query | Handle temporary data without creating a table |
Summary
In this guide, we covered all key aspects of MySQL temporary tables.
✔ Quick recap
- Temporary tables are automatically removed when the session ends
- They help optimize performance by reducing JOIN and aggregation overhead
- Useful for batch processing, temporary search results, and test data
- They cannot be shared across sessions, and indexes must be added manually when needed
- Choosing between temporary tables, views, and CTEs enables flexible data management
You have now completed all sections of the MySQL temporary table guide! 🎉
Use this reference to effectively leverage temporary tables in your MySQL projects.


