✏️ Explanatory Question

What is a temporary table and when do you use it?

👁 10 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

74

What is a temporary table and when do you use it?

Level: Advanced — Temporary tables are invaluable for breaking down complex, multi-step operations.

A temporary table is a special table that exists only for the duration of the current session (connection) and is automatically dropped when the session ends. It's created with CREATE TEMPORARY TABLE and is visible only to the session that created it.

Key point: A temporary table is private to its session — two connections can even create temp tables with the same name without conflict. It's dropped automatically on disconnect, or manually with DROP TEMPORARY TABLE.

When to Use Temporary Tables

  • Multi-step processing: Store intermediate results in complex ETL or reports.
  • Breaking down big queries: Simplify a huge query into manageable stages.
  • Reusing a result set: Compute once, reference multiple times in a session.
  • Performance: Avoid recomputing an expensive subquery repeatedly.

Temporary Table vs Regular Table

Feature Temporary Table Regular Table
Lifespan Current session only Permanent
Visibility Only creating session All sessions
Auto-dropped? Yes (on disconnect) No
Name conflicts None across sessions Must be unique
Stored in Memory/disk (temp) Permanent storage

Important Limitations

  • Cannot be referenced twice in the same query (e.g., self-join) before MySQL 8.0.
  • Not visible in SHOW TABLES.
  • A temp table with the same name as a real table hides the real one for that session.

Quick Example

-- Create a temporary table from a query
CREATE TEMPORARY TABLE temp_high_earners AS
SELECT emp_id, name, salary
FROM employees
WHERE salary > 60000;

-- Use it like a normal table within the session
SELECT COUNT(*) FROM temp_high_earners;

SELECT t.name, d.dept_name
FROM temp_high_earners t
JOIN departments d ON t.emp_id = d.dept_id;

-- Create an empty temp table with a defined structure
CREATE TEMPORARY TABLE temp_summary (
    dept_id  INT,
    total    INT
);

INSERT INTO temp_summary
SELECT dept_id, COUNT(*) FROM employees GROUP BY dept_id;

-- Manually drop it (or it auto-drops on disconnect)
DROP TEMPORARY TABLE temp_high_earners;
Interviewer tip: The one-liner they want — "A temporary table exists only for the current session, is visible only to that session, and is auto-dropped on disconnect. It's ideal for storing intermediate results in complex, multi-step queries."