Databases 3 min read

Mastering MySQL Temporary Tables: Creation, Usage, and Deletion

This guide explains what MySQL temporary tables are, how they exist only for the current connection, provides step‑by‑step SQL examples for creating, inserting, querying, and dropping a temporary table, and discusses practical scenarios such as high‑concurrency writes.

JavaEdge
JavaEdge
JavaEdge
Mastering MySQL Temporary Tables: Creation, Usage, and Deletion

What is a MySQL Temporary Table?

Temporary tables are useful for storing transient data. They are visible only to the current connection; when the connection closes, MySQL automatically drops the table and frees its space.

Temporary tables were introduced in MySQL 3.23.

If you create a temporary table via a Java MySQL client, the table persists until the client program ends, unless you drop it manually.

Example

Creating a temporary table:

CREATE TEMPORARY TABLE SalesSummary (
    product_name VARCHAR(50) NOT NULL,
    total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00,
    avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00,
    total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);

Inserting data:

INSERT INTO SalesSummary (product_name, total_sales, avg_unit_price, total_units_sold)
VALUES ('cucumber', 100.25, 90, 2);

Query the table as usual. Note that SHOW TABLES will not list temporary tables.

When the MySQL session ends, the temporary table disappears, so a subsequent SELECT will fail because the table no longer exists.

Dropping a Temporary Table

By default, a temporary table is removed when the connection is closed. You can also drop it manually within the same session:

DROP TABLE SalesSummary;
SELECT * FROM SalesSummary;  -- will return an error because the table was dropped

Practical Scenario

In high‑concurrency write scenarios, you can let each thread create its own temporary table, write data there, and later merge into the main tables, or control writes at the source to avoid simultaneous inserts.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceSQLdatabasemysqltemporary table
JavaEdge
Written by

JavaEdge

First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.