SQL reference (MySQL and MariaDB dialects)

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#

SQL
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, in INSERT/UPDATE/DELETE/TRUNCATE/ALTER/CREATE INDEX/DESCRIBE and in SHOW COLUMNS, SHOW CREATE TABLE and SHOW INDEX. tmp.col works.
  • As in MySQL a temporary table hides a base table of the same name, even when written db.name. SHOW TABLES does not list temporary tables. DROP TABLE drops the temporary one first. DROP TEMPORARY TABLE drops only temporary ones.
  • LIKE and AS SELECT work with TEMPORARY. Two uses in one query (FROM tmp a JOIN tmp b) work.
  • Privilege: CREATE TEMPORARY TABLES on the database. No table privilege is asked for the hidden names.
  • DESCRIBE of a temporary table answers NULL for Extra where 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 __tmp tables behind; they are never named again and can be dropped by hand.
  • A temporary table cannot be the target of a multi-table UPDATE/DELETE and cannot have foreign keys.

Examples#

Example:

SQL
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;

See also#