Create Temporary Table
suggest changeTemporary tables hold data for the current session. They have existed since MySQL 3.23.
A temporary table is dropped when the session ends. You can also drop it yourself.
The same temporary table name can be used in many connections at once, because only the client that created it can see it. A temporary table hides a permanent table of the same name for that session.
The examples below are alternatives, not one script. Creating the same name twice in one session fails until you drop the first table.
--->Basic temporary table creation
CREATE TEMPORARY TABLE tempTable1(
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(100) NOT NULL,
PRIMARY KEY ( id )
);
--->Temporary table creation from select query
CREATE TEMPORARY TABLE tempTable1
SELECT ColumnName1,ColumnName2,... FROM table1;
You can add indexes as you build the table:
CREATE TEMPORARY TABLE tempTable1
( PRIMARY KEY(ColumnName2) )
SELECT ColumnName1,ColumnName2,... FROM table1;
IF NOT EXISTS avoids the “table already exists” error. If that name already exists in the current session, the statement does nothing and the old table is kept.
CREATE TEMPORARY TABLE IF NOT EXISTS tempTable1
SELECT ColumnName1,ColumnName2,... FROM table1;
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents