Using Temporary Tables

Temporary tables in MySQL can be a powerful means of manipulating a data set. A temporary table exists only for the duration of your MySQL session, after which it is automatically deleted. Otherwise, it works just the same as a regular database table.

You will learn more about creating database tables in Lesson 14, “Creating and Modifying Tables.” For now, consider some examples to simulate different types of a compound query.

Performing a UNION

To join two or more queries using a temporary table, you need to insert the data rows from both queries into the same table.

First, create a new table using the first query to define the columns. The result of this query will also be inserted into the table.

 CREATE TEMPORARY TABLE ...

Get Sams Teach Yourself MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.