Introduction
Temporary tables are a powerful feature used to store transient data during the execution of complex queries or stored procedures. In an Oracle database, temporary tables provide a way to handle intermediate results without affecting the actual schema objects. This tutorial will guide you through creating and using global and private temporary tables in Oracle, explaining their differences and best practices.
Global Temporary Tables
Definition
Global temporary tables (GTTs) are regular table structures that store data temporarily on a per-session or per-transaction basis. They exist once but can be used multiple times across different sessions.
Creating a Global Temporary Table
To create a GTT, you use the CREATE GLOBAL TEMPORARY TABLE
statement:
CREATE GLOBAL TEMPORARY TABLE today_sales (
order_id NUMBER
)
ON COMMIT PRESERVE ROWS;
- ON COMMIT PRESERVE ROWS: This clause indicates that the data persists until explicitly deleted. If "DELETE ROWS" were used, data would be removed at transaction commit.
Usage
Once created, you can perform standard DML operations on GTTs as with regular tables:
INSERT INTO today_sales (order_id) SELECT order_id FROM orders WHERE order_date = SYSDATE;
SELECT * FROM today_sales;
Private Temporary Tables
Introduced in Oracle 18c, private temporary tables are session-specific, allowing more flexibility and performance improvements.
Creating a Private Temporary Table
Private temporary tables can be created dynamically:
CREATE PRIVATE TEMPORARY TABLE ora$ptt_today_sales AS
SELECT * FROM orders WHERE order_date = SYSDATE;
- Session-Specific: They exist only for the duration of your session and are automatically discarded once you disconnect.
Benefits
- Performance: Being in-memory, private temporary tables offer faster data access.
- Convenience: Eliminates the need to manage table creation and deletion manually.
Best Practices
-
Avoid Overuse: While useful, GTTs should not replace well-designed queries that can eliminate intermediate storage needs.
-
Use Inline Views: Complex operations often requiring temporary tables can be streamlined using inline views or CTEs (Common Table Expressions).
-
Leverage
MATERIALIZE
Hint: For performance enhancements in SELECT statements within a Common Table Expression, use:WITH CTE AS ( SELECT /*+ MATERIALIZE */ 'FOO' AS "STUFF" FROM DUAL ) SELECT * FROM CTE;
-
Understand Commit Behavior: Decide between
PRESERVE ROWS
orDELETE ROWS
based on whether the data should persist across transactions.
Conclusion
Temporary tables in Oracle, both global and private, provide robust solutions for managing intermediate query results efficiently. Understanding their proper use ensures better performance and resource management within your database applications. When used judiciously, they can simplify complex logic without compromising system stability or design integrity.