A temporary table is a table that is visible only to the current session, and is dropped automatically when the session in which it was created is closed.
Since temporary tables are not stored in the database on a permanent basis, therefore, it would be useful in a situation where you need a table only for a short time to perform or test something, after which you want it to disappear automatically.
CREATE TEMPORARY TABLE statement is used to create a temporary table.
If you want to create a temporary table from scratch, you can use the
TEMPORARY keyword when creating a table, i.e. use
CREATE TEMPORARY TABLE instead of
CREATE TABLE statement. See the create table chapter for complete syntax and examples.
Temporary tables can be useful in situations when you just want to test the SQL queries without affecting the database. Let's create a temporary copy of an existing table in MySQL database.
Type the following command at the MySQL command prompt and press enter:
The above statement creates a temporary table named persons on the fly from the result set of an existing base table persons. Also, since it is a temporary copy of the persons table, therefore you can perform any operation like
DELETE without worrying about affecting the original persons base table by mistake.
Temporary tables are dropped automatically when the database connection or session in which they are created is closed. However, if want to delete them without closing the current session, you can use the
DROP TEMPORARY TABLE statement, as follow:
The above statement will delete the temporary table persons from the database. After that, the original persons base table becomes visible.