Introduction to MySQL temporary tables
In MySQL, a temporary table is a special type of table that allows you to store a temporary result set, which you can reuse several times in a single session.
A temporary table is handy when it is impossible or expensive to query data that requires a single SELECT statement. In such cases, you can use a temporary table to store the immediate result and use another query to process it.
A MySQL temporary table has the following features:
- A temporary table is created by using
CREATE TEMPORARY TABLEstatement. Notice that the keywordTEMPORARYis added between theCREATEandTABLEkeywords. - MySQL removes the temporary table automatically when the session ends or the connection is terminated. Also, you can use the
DROP TABLEstatement to remove a temporary table explicitly when you are no longer using it. - A temporary table is only available and accessible to the client that creates it. Different clients can create temporary tables with the same name without causing errors because only the client that creates the temporary table can see it. However, in the same session, two temporary tables cannot share the same name.
- A temporary table can have the same name as a regular table in a database. For example, if you create a temporary table named
employeesin the sample database, the existingemployeestable becomes inaccessible. Every query you issue against theemployeestable is now referring to the temporary tableemployees. When you drop theemployeestemporary table, the regularemployeestable is available and accessible.
For example, if the connection to the database server is lost and you reconnect to the server automatically, you cannot differentiate between the temporary table and the regular one.
Then, you may issue a DROP TABLE statement to remove the permanent table instead of the temporary table, which is not expected.
To avoid this issue, you can use the DROP TEMPORARY TABLE statement to drop a temporary table instead of the DROP TABLE statement
MySQL CREATE TEMPORARY TABLE statement
The syntax of the CREATE TEMPORARY TABLE statement is similar to the syntax of the CREATE TABLE statement except for the TEMPORARY keyword:
CREATE TEMPORARY TABLE table_name(
column1 datatype constraints,
column1 datatype constraints,
...,
table_constraints
);To create a temporary table whose structure is based on an existing table, you cannot use the CREATE TEMPORARY TABLE ... LIKE statement. Instead, you use the following syntax:
CREATE TEMPORARY TABLE temp_table_name
SELECT * FROM original_table
LIMIT 0;