Temporary tables in MySQL are short-lived tables that exist only for the duration of a database session (or until explicitly dropped). They are useful for storing intermediate results, simplifying complex queries, and improving readability of multi-step data processing.
DROP TEMPORARY TABLE.Basic creation syntax:
CREATE TEMPORARY TABLE table_name (column_definitions);
Common patterns:
-- Create a temporary table to store recent orders
CREATE TEMPORARY TABLE recent_orders (
id INT PRIMARY KEY,
customer_id INT,
amount DECIMAL(10,2),
order_date DATETIME
);
-- Insert data into the temporary table from a larger orders table
INSERT INTO recent_orders (id, customer_id, amount, order_date)
SELECT id, customer_id, total, created_at
FROM orders
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY);
-- Use the temporary table to run an aggregated report
SELECT customer_id, COUNT(*) AS order_count, SUM(amount) AS total_spent
FROM recent_orders
GROUP BY customer_id
ORDER BY total_spent DESC
LIMIT 10;
-- Drop the temporary table explicitly (optional)
DROP TEMPORARY TABLE IF EXISTS recent_orders;
CREATE TEMPORARY TABLE statement creates an in-memory/onsite temporary structure accessible only to your session.INSERT ... SELECT copies recent rows into the temporary table quickly and isolates work from the main tables.recent_orders and returns the top customers for the last 30 days.DROP TEMPORARY TABLE), the temporary table is removed automatically.tmp_table_size and max_heap_table_size settings.