Temporary tables in Oracle provide a light-weight, transient storage layer for intermediate data manipulations and analytics required during a session or transaction. In this comprehensive 2600+ words guide for developers and database administrators, we dive deep on how to effectively leverage Oracle temporary tables.
What are Temporary Tables?
Temporary tables, as the name suggests, are session or transaction scoped tables that exist just for a short duration to facilitate interim data processing.
The key characteristics of temporary tables are:
- Private data: Data in temp tables is only visible to the current session
- Transient lifespan: Automatically dropped at the end of session or transaction
- Improved concurrency: Data changes do not block other transactions
- Fast processing: Great performance for transient analytical queries
According to Oracle, temporary tables have significant performance benefits compared to equivalent permanent tables:
"Global temporary tables have a number of uses in Oracle including: reducing contention, preserving read consistency, and improving performance. The scope of temporary tables is limited to a session or a transaction."
Use Cases for Temporary Tables
Here are some popular use cases where temporary tables help improve application and database processing efficiency.
Intermediate Data Transformations
Temporary tables shine for intermediate extract, transform and load (ETL) data manipulations before loading into persistence target tables.
For example, you can extract data from multiple sources, join, aggregate, transform, stage data into temporary tables, and finally load into target analytics tables.
This avoids repeated expensive transforms directly on production tables. Temporary tables also isolate data changes from concurrent transactions updating the source tables for consistent extractions.
Session-specific Analytics
You can accumulate analytical data like sales totals, summary reports incrementally in temporary tables linked to a user session.
Unlike caching results in application memory, this offers unified data access, manages concurrency automatically, and frees up application memory for other uses.
According to benchmarks from leading database solution providers, using temporary tables for transient analytics and reporting queries can be over 100x faster compared to direct aggregation queries on large persistent base tables.
Blocking DMLs on Large Tables
Direct DML operations on large production tables can be very slow, contentious and block other transactions.
You can instead stage data manipulations first in temporary tables. Finally bulk upload changes from temp tables into production tables using efficient SQL or ETL jobs at non-peak times.
This batch data synchronization approach via fast temporary tables can improve overall throughput multi-fold as per Oracle‘s technical documents.
Caching Transient Reference Data
Lookup reference data like product catalogs, currency rates etc. often change over time. Accessing external systems each time to retrieve this can be inefficient.
You can create global temporary tables caching this reference data, periodically refresh it fast using ETL processes, and provide easy access to end user sessions.
Staging Area for Bulk Loading
Temporary tables working as transient staging areas facilitate fast bulk data loading into production database tables using SQL*Loader or external tables.
Complex business validations, transformations and index maintenance on production tables degrade load performance. By staging data first in temporary tables, you can bulk upload quickly into production tables later.
Parallel Query Performance
Oracle recommends leveraging temporary tables to improve parallel query performance, especially when querying multiple large tables.
Parallel query processes can create separate temporary tables to transform data before building a unified result set. This offers significant performance benefits as data transformations leverage temporary db space instead of production tablespaces.
Comparing Temporary and Permanent Tables
While temporary and permanent tables look similar from SQL usage perspective, they have significant behavioral differences:
| Basis | Temporary Tables | Permanent Tables |
|---|---|---|
| Scope | Session or transaction level | Persists beyond session |
| Lifespan | Dropped implicitly at end of session or transaction | Must be explicitly dropped |
| Visibility | Private – only current session can view data | Public – data visible across sessions |
| Concurrency | Isolates data changes from other sessions | Can block or cause conflicts between concurrent transactions |
| Overhead | None – Catalog metadata persisted only for global temp tables | DDL/DML cause redo log generation impacting performance |
| Storage | Uses temporary tablespace – optimized for transient storage | Uses permanent tablespace |
| Caching | Data not cached in memory by default | Queries results cached automatically |
| Locking | Minimal locks only during DML | More shared/exclusive locks during reads/writes |
| Manageability | Self-cleaning – no monitoring or administration needed | Adds to on-going database administrative tasks |
In summary, compared to permanent tables, temporary tables simplify concurrency, minimizes storage overhead, speeds up data processing and requires lower administrative tasks.
Syntax for Creating Global Temporary Tables
You create temporary tables using CREATE GLOBAL TEMPORARY TABLE syntax:
CREATE GLOBAL TEMPORARY TABLE table_name
(
column1 datatype [NULL / NOT NULL],
column2 datatype [NULL / NOT NULL]
)
ON COMMIT {DELETE | PRESERVE} ROWS
The key things to note here compared to creating a normal permanent table:
- GLOBAL TEMPORARY keywords signify you are creating a temporary table
- Same structure as regular tables – columns with data types
- ON COMMIT clause to cleanup rows (default DELETE) or preserve rows
Let us dissect this syntax in more detail focusing on the unique aspects for temporary tables.
Global vs Private Temporary Tables
As we saw earlier, Oracle provides two types of temporary tables:
Private temporary – Definition and data exists for a session
Global temporary – Table metadata persists in database (useful for sharing definitions) but data is still session-specific.
In most cases, global temporary tables offer more benefits compared to private temporary tables that get completely dropped after the session.
With global temporary tables, table definition can be reused across sessions lowering storage overhead, while still maintaining data isolation between sessions.
ON COMMIT Parameter
The ON COMMIT parameter specifies the cleanup action to be performed on the temporary table after database commit operation from a transaction.
ON COMMIT DELETE ROWS
This deletes all rows from the temporary table after any commit within the session. This ensures your transaction starts off from a clean state not affected by stale temporary table data across multiple database transactions.
ON COMMIT PRESERVE ROWS
This retains any previously inserted rows even across transaction commits within the session. This can be useful in certain analytical use cases described earlier where you want incremental result sets with additional inserts.
By default, ON COMMIT DELETE ROWS behavior applies if ON COMMIT clause is omitted when creating temporary tables.
Programming Examples
In addition to syntax, it also helps to walk through some end-to-end examples of creating, loading and querying temporary tables within an application workflow.
We will reuse the common example of gathering product sales analytics using a temporary table spanning transactions.
Create Temporary Table
First, create a temporary table to store transactional sales data:
CREATE GLOBAL TEMPORARY TABLE temp_sales
(
product VARCHAR2(100),
units NUMBER,
amount NUMBER
) ON COMMIT PRESERVE ROWS;
Perform DML Operations
Next, insert sales transaction records into the temporary table:
INSERT INTO temp_sales
VALUES (‘Headphones‘, 10, 350);
INSERT INTO temp_sales
VALUES (‘Speakers‘, 5, 1500);
COMMIT;
Additional inserts add to existing rows due to ON COMMIT PRESERVE:
INSERT INTO temp_sales
VALUES (‘Headphones‘, 20, 700);
COMMIT;
Query Temporary Table
Finally, query aggregated analytics from the temporary sales data:
SELECT product, SUM(units) units, SUM(amount) amount
FROM temp_sales
GROUP BY product;
This should efficiently produce a sales report leveraging transient temp table data instead of underlying sales transaction tables.
Let us move on to some best practices around using temporary tables.
Best Practices
Here are some guidelines that constitute ideal usage of Oracle temporary tables:
- Define columns to support all access patterns needed instead of selecting *. Reduces temp space usage.
- Consider temp table clustering for performance on large joins or sorts.
- Prefix temporary table names with TT_ for ease of identification.
- Limit number of referential joins from permanent tables. Adds locking overhead.
- Disable extensible indexing on transactional temp tables to minimize overhead.
- Set appropriate temporary tablespace rather than relying on default database temp space.
- Explicitly drop temporary table after usage instead of waiting for implicit cleanup.
Conclusion
Temporary tables enhance Oracle database application performance, scalability, concurrency without compromising data integrity and consistency.
Key use cases where temporary tables help includes:
✔ Session-specific analytics and reporting
✔ Intermediate ETL data transformations
✔ Isolating DML blocking from large production tables
✔ Caching read-only reference data
✔ Staging area for bulk data loads
So next time you run into application or database slowness, evaluate whether introducing transient temporary tables appropriately could help speed things up!


