Temporary tables
CREATE TEMPORARY TABLE and DROP TEMPORARY TABLE, how a session's temporary tables hide base tables, and their limits.
A temporary table belongs to the session that made it and is dropped when the session ends (D72).
Syntax#
CREATE TEMPORARY TABLE [IF NOT EXISTS] tbl_name (create_definition, ...) [table_option] ...
CREATE TEMPORARY TABLE [IF NOT EXISTS] tbl_name LIKE old_tbl
CREATE TEMPORARY TABLE [IF NOT EXISTS] tbl_name [(create_definition, ...)] [IGNORE | REPLACE] [AS] query_expression
DROP TEMPORARY TABLE [IF EXISTS] tbl_name [, tbl_name] ...Arguments#
The definitions are those of CREATE TABLE.
Remarks#
- How it is built. A temporary table is an ordinary table of the database under the hidden name
__tmp<connection id>_<name>. The session keeps the list of its temporary tables; a table name on the list is redirected to the hidden name in queries, inINSERT/UPDATE/DELETE/TRUNCATE/ALTER/CREATE INDEX/DESCRIBEand inSHOW COLUMNS,SHOW CREATE TABLEandSHOW INDEX.tmp.colworks. - As in MySQL a temporary table hides a base table of the same name, even when written
db.name.SHOW TABLESdoes not list temporary tables.DROP TABLEdrops the temporary one first.DROP TEMPORARY TABLEdrops only temporary ones. LIKEandAS SELECTwork withTEMPORARY. Two uses in one query (FROM tmp a JOIN tmp b) work.- Privilege:
CREATE TEMPORARY TABLESon the database. No table privilege is asked for the hidden names. DESCRIBEof a temporary table answersNULLforExtrawhere MySQL does (a MySQL quirk).
Limits (known)#
- The table lives in the shared database, so it is visible to Raft DB tools (not to MySQL clients through
SHOW TABLES). - A crash leaves hidden
__tmptables behind; they are never named again and can be dropped by hand. - A temporary table cannot be the target of a multi-table
UPDATE/DELETEand cannot have foreign keys.
Examples#
Example:
CREATE TEMPORARY TABLE tmp (a INT PRIMARY KEY, b VARCHAR(10), c DECIMAL(6,2) DEFAULT 1.5);
INSERT INTO tmp (a, b) VALUES (1, 'x'), (2, 'y'), (3, 'z');
SELECT b.id, tmp.b FROM base b JOIN tmp ON tmp.a = b.id ORDER BY b.id;
CREATE TEMPORARY TABLE base (x INT, y INT); -- hides the base table "base"
DROP TEMPORARY TABLE base; -- the base table is visible again
CREATE TEMPORARY TABLE copy1 AS SELECT id, v FROM base;