How to Create a Temporary Table in MySQL

This article explains how to create and use temporary tables in MySQL. You will learn the exact SQL syntax required to build a temporary table, understand how these tables isolate data within a specific session, and see how they automatically destroy themselves once your database connection ends.

In MySQL, you can create a temporary table by adding the TEMPORARY keyword to a standard CREATE TABLE statement. These tables are ideal for storing intermediate results from complex queries or performing multi-step data manipulations without affecting your permanent schema.

The Syntax for MySQL Temporary Tables

To create a basic temporary table from scratch, use the following SQL syntax:

CREATE TEMPORARY TABLE temp_sales_summary (
    id INT AUTO_INCREMENT PRIMARY KEY,
    category VARCHAR(50),
    total_sales DECIMAL(10,2)
);

You can also create a temporary table and immediately populate it with data from an existing table using a SELECT statement:

CREATE TEMPORARY TABLE temp_active_customers AS
SELECT customer_id, first_name, last_name, email
FROM customers
WHERE status = 'active';

Key Characteristics of Temporary Tables

DROP TEMPORARY TABLE IF EXISTS temp_sales_summary;