Global Temporary Tables (GTT) is a powerful feature in Oracle Database that provides a way to manage temporary data during a session or transaction.
Unlike regular stored database tables, data stored in GTTs is temporary and automatically cleared when the session ends or the transaction completes.
Features of Global Temporary Tables
- Session-Specific or Transaction-Specific Data: GTTs holds data that persists for either the duration of a session or a transaction.
- Automatic Data Cleanup: Data is automatically deleted when the defined scope ends.
- Performance Optimization: GTTs are often stored in temporary segments, reducing redo log generation and improving performance.
- Structure Persistence: While data is temporary, the table structure itself persists in the database.
Creating a Global Temporary Table
Syntax for creating a GTT is similar to a regular table but includes the ON COMMIT
clause to define its behavior.
Example:
CREATE GLOBAL TEMPORARY TABLE sales_gtt (
sale_number NUMBER,
product_name VARCHAR2(100),
sale_date DATE
) ON COMMIT DELETE ROWS; -- Data deleted at the end of each transaction
Alternatively, for session-specific data retention:
CREATE GLOBAL TEMPORARY TABLE temp_logs (
log_id NUMBER,
log_message VARCHAR2(255)
) ON COMMIT PRESERVE ROWS; -- Data persists until the session ends
Use Cases
- Staging Data for Reporting: Useful for holding intermediate data during complex data transformation tasks.
- Temporary Storage for Batch Processing: will acts as a workspace for data manipulation within a session.
- Session-Based Customization: helps manage session-specific calculations or configurations.
Best Practices
- Avoid Indexing GTTs Unless Necessary: Since data is temporary, indexing may add unnecessary overhead unless performance issues arise.
- Use GTTs for Intermediate Results: Ideal for holding temporary result sets in complex queries.
- Monitor Storage Usage: GTT data is stored in the temporary tablespace; ensure enough space is allocated.