How do you create a temporary table in an Oracle database?

GigaPr picture GigaPr · Apr 20, 2010 · Viewed 480.3k times · Source

I would like to create a temporary table in a Oracle database

something like

Declare table @table (int id)

In SQL server

And then populate it with a select statement

Is it possible?

Thanks

Answer

hamishmcn picture hamishmcn · Apr 20, 2010

Yep, Oracle has temporary tables. Here is a link to an AskTom article describing them and here is the official oracle CREATE TABLE documentation.

However, in Oracle, only the data in a temporary table is temporary. The table is a regular object visible to other sessions. It is a bad practice to frequently create and drop temporary tables in Oracle.

CREATE GLOBAL TEMPORARY TABLE today_sales(order_id NUMBER)
ON COMMIT PRESERVE ROWS;

Oracle 18c added private temporary tables, which are single-session in-memory objects. See the documentation for more details. Private temporary tables can be dynamically created and dropped.

CREATE PRIVATE TEMPORARY TABLE ora$ptt_today_sales AS
SELECT * FROM orders WHERE order_date = SYSDATE;

Temporary tables can be useful but they are commonly abused in Oracle. They can often be avoided by combining multiple steps into a single SQL statement using inline views.