HomeMYSQLWhat are temporary tables?

What are temporary tables?

Temporary tables in MySQL are special tables that exist temporarily during a database session. They are useful for storing intermediate results, performing complex queries, or breaking down large tasks into smaller steps without affecting the main database tables.

Here’s a detailed breakdown:


Key Features

  1. Session-specific:
    • Temporary tables are visible only to the session (connection) that created them.
    • When the session ends, the table is automatically dropped.
  2. Same syntax as normal tables:
    • You can define columns, data types, and even indexes.
  3. No name conflicts:
    • Different sessions can create temporary tables with the same name without conflict.
  4. Automatic cleanup:
    • If the session ends unexpectedly, MySQL automatically removes the temporary table.

Creating a Temporary Table

CREATE TEMPORARY TABLE temp_employees (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    salary DECIMAL(10,2)
);

Using a Temporary Table

-- Insert data
INSERT INTO temp_employees (id, name, salary) 
VALUES (1, 'John', 50000), (2, 'Alice', 60000);

-- Query data
SELECT * FROM temp_employees WHERE salary > 50000;

Dropping a Temporary Table

DROP TEMPORARY TABLE IF EXISTS temp_employees;

If you don’t drop it manually, it will be automatically removed when your session ends.


Advantages

  • Helps simplify complex queries.
  • Reduces repeated computations by storing intermediate results.
  • Safe to use in multi-user environments because each session has its own version.

Limitations

  • Cannot be referenced by other sessions.
  • Cannot have foreign keys referencing permanent tables (or vice versa).
  • Data is lost when the session ends.

Here’s a clear comparison between Temporary Tables and Regular Tables in MySQL:

FeatureTemporary TableRegular Table
VisibilityOnly visible within the session that created itVisible to all sessions/users with access
LifetimeExists only for the duration of the session or until manually droppedPermanent until explicitly dropped
Creation SyntaxCREATE TEMPORARY TABLE ...CREATE TABLE ...
Name ConflictsDifferent sessions can have tables with the same name without conflictTable names must be unique within a database
Foreign Key ConstraintsCannot reliably have foreign keys to/from permanent tablesCan have foreign keys between tables
Use CaseStoring intermediate or temporary data for queriesStoring persistent data for applications
Automatic CleanupAutomatically deleted when session endsMust be explicitly deleted
PerformanceUseful for speeding up complex queries or intermediate resultsStandard storage and retrieval operations

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *