Create a temporary table in a SELECT statement without a separate CREATE TABLE

MysqlSelectTemp TablesCreate TableDerived Table

Mysql Problem Overview


Is it possible to create a temporary (session only) table from a select statement without using a create table statement and specifying each column type? I know derived tables are capable of this, but those are super-temporary (statement-only) and I want to re-use.

It would save time if I did not have to write up a create table command and keep the column list and type list matched up.

Mysql Solutions


Solution 1 - Mysql

CREATE TEMPORARY TABLE IF NOT EXISTS table2 AS (SELECT * FROM table1)

From the manual found at http://dev.mysql.com/doc/refman/5.7/en/create-table.html

> You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current session, and is dropped automatically when the session is closed. This means that two different sessions can use the same temporary table name without conflicting with each other or with an existing non-TEMPORARY table of the same name. (The existing table is hidden until the temporary table is dropped.) To create temporary tables, you must have the CREATE TEMPORARY TABLES privilege.

Solution 2 - Mysql

In addition to psparrow's answer if you need to add an index to your temporary table do:

CREATE TEMPORARY TABLE IF NOT EXISTS 
  temp_table ( INDEX(col_2) ) 
ENGINE=MyISAM 
AS (
  SELECT col_1, coll_2, coll_3
  FROM mytable
)

It also works with PRIMARY KEY

Solution 3 - Mysql

Use this syntax:

CREATE TEMPORARY TABLE t1 (select * from t2);

Solution 4 - Mysql

Engine must be before select:

CREATE TEMPORARY TABLE temp1 ENGINE=MEMORY 
as (select * from table1)

Solution 5 - Mysql

ENGINE=MEMORY is not supported when table contains BLOB/TEXT columns

Solution 6 - Mysql

As I understand it, a SELECT statement will work on the temporary table if you're using it in something like phpMyAdmin, but following that SELECT, the temporary table will be gone. This means set up exactly what you want to do with it first, and don't view any results till your 'action' statements that change the data (DELETE, UPDATE) are complete.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question700 SoftwareView Question on Stackoverflow
Solution 1 - MysqlpsparrowView Answer on Stackoverflow
Solution 2 - MysqlRafaSashiView Answer on Stackoverflow
Solution 3 - MysqlrizonView Answer on Stackoverflow
Solution 4 - MysqlCrusaderView Answer on Stackoverflow
Solution 5 - MysqlCrisView Answer on Stackoverflow
Solution 6 - MysqlPete855217View Answer on Stackoverflow