SQL BASIC
SQL JOINS
SQL ADVANCED
SQL REFERENCE
Advertisements

SQL Temporary Tables

In this tutorial you will learn how to create temporary tables using SQL.

Creating Temporary Tables

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.

Syntax

The CREATE TEMPORARY TABLE statement is used to create a temporary table.

CREATE TEMPORARY TABLE table_name (column definitions);

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.


Creating a Temporary Copy of an Existing Table

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:

mysql> CREATE TEMPORARY TABLE persons SELECT * FROM persons;

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 INSERT, UPDATE or DELETE without worrying about affecting the original persons base table by mistake.

Tip: A temporary table can have the same name as a permanent base table. If you specify the name of a temporary table same as the existing base table, then the permanent base table is hidden until the temporary table is dropped.

Note: Since temporary tables are session-specific, so two different sessions can use the same temporary table name without conflicting with each other.


Dropping Temporary Tables

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:

mysql> DROP TEMPORARY TABLE persons;

The above statement will delete the temporary table persons from the database. After that, the original persons base table becomes visible.

Advertisements
Bootstrap UI Design Templates