The MySQL TEMPORARY TABLE
statement is used to create a temporary table that exists only for the duration of a session. This statement is essential for storing intermediate results and data manipulation during complex queries.
CREATE TEMPORARY TABLE table_name (
column1 datatype [constraints],
column2 datatype [constraints],
...
);
The CREATE TEMPORARY TABLE
statement has the following components:
table_name
: The name of the temporary table to be created. It must be unique within the session.column1, column2, ...
: The names of the columns in the table.datatype
: The data type of the column (e.g., INT
, VARCHAR(100)
, DATE
).[constraints]
: Optional constraints for the column (e.g., PRIMARY KEY
, NOT NULL
, AUTO_INCREMENT
).Let's look at an example of the MySQL TEMPORARY TABLE
statement and how to use it:
USE mydatabase;
This query sets the context to the database named mydatabase
.
Create a temporary table to work with:
CREATE TEMPORARY TABLE temp_employees (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE
);
This query creates a temporary table named temp_employees
with columns for id
, first_name
, last_name
, and email
.
Insert some data into the temporary table:
INSERT INTO temp_employees (first_name, last_name, email)
VALUES ('John', 'Doe', 'john.doe@example.com'),
('Jane', 'Smith', 'jane.smith@example.com');
This query inserts two rows into the temp_employees
table.
Select data from the temporary table:
SELECT * FROM temp_employees;
This query retrieves all rows from the temp_employees
table.
Drop the temporary table:
DROP TEMPORARY TABLE temp_employees;
This query deletes the temp_employees
table. Since it is a temporary table, it would also be dropped automatically when the session ends.
The MySQL TEMPORARY TABLE
statement is a powerful tool for creating tables that exist only for the duration of a session. Understanding how to use the TEMPORARY TABLE
statement is essential for efficient data manipulation and intermediate result storage during complex queries in MySQL.