Temporary Tables
A temporary table is a table that exists only for the duration of a database session or transaction, and is automatically dropped afterward - useful for storing intermediate results during complex, multi-step queries.
Creating a Temporary Table
CREATE TEMPORARY TABLE high_value_customers AS
SELECT customer_id, first_name
FROM customers
WHERE total_spent > 50000;
SELECT * FROM high_value_customers;
Why Use Temporary Tables
- Break a complex query into smaller, more manageable, readable steps
- Store intermediate results without cluttering the permanent database schema
- Improve performance by avoiding repeated computation of the same subquery
Temporary Tables vs Regular Tables
Unlike regular tables, temporary tables are automatically cleaned up once the session ends, and they're typically only visible to the session that created them - other users or connections cannot see or query them.
Temporary tables are especially handy for data science workflows where a large query needs to be staged in steps before final analysis or export.