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
In SQL Server developers will regularly create a temporary table to do some work and drop it. In Oracle a Global Temporary Table (GTT) is a permanent metadata object that holds rows in temporary segments on a transaction-specfic or session-specific basis. It is not considered normal to create and drop GTTs on the fly.
To create a Global Temporary Table, add the “##” symbol before the table name. Global Temporary Tables are visible to all connections and Dropped when the last connection referencing the table is closed. Global Table Name must have an Unique Table Name.
Syntax. The CREATE TEMPORARY TABLE statement is used to create a temporary table. CREATE TEMPORARY TABLE table_name (column definitions); If you want to create a temporary table from scratch, you can use the TEMPORARY keyword when creating a table, i.e. use CREATE TEMPORARY TABLE instead of CREATE TABLE statement.
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.
Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE
, not DROP
) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With