0

Is it possible to view the query that created a given table, in oracle sql? (I lost the original code). EDIT: I am actually searching for the query that generated the rows of the table, i.e. the CTAS statement "create table X as select ...". As far as I understood, there is no way to do this.

Giuseppe
  • 518
  • 10
  • 22
  • 1
    Just to pick a nit, queries do not create tables. Tables are created by DDL (Data Definition Language. Queries are DML (Data Manipulation Language) – EdStevens Sep 07 '21 at 13:54

2 Answers2

3

Use DBMS_METADATA.GET_DDL. For example:

SQL> set long 10000
SQL>
SQL> SELECT DBMS_METADATA.get_ddl ('TABLE', table_name, owner)
  2    FROM all_tables
  3   WHERE     owner = 'SCOTT'
  4         AND table_name = 'EMP';

DBMS_METADATA.GET_DDL('TABLE',TABLE_NAME,OWNER)
--------------------------------------------------------------------------------

  CREATE TABLE "SCOTT"."EMP"
   (    "EMPNO" NUMBER(4,0) NOT NULL ENABLE,
        "ENAME" VARCHAR2(10),
        "JOB" VARCHAR2(9),
        "MGR" NUMBER(4,0),
        "HIREDATE" DATE,
        "SAL" NUMBER(7,2),
        "COMM" NUMBER(7,2),
        "DEPTNO" NUMBER(2,0),
         CONSTRAINT "PK_EMP" PRIMARY KEY ("EMPNO")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USER_DATA"  ENABLE
   ) SEGMENT CREATION IMMEDIATE
  PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
 NOCOMPRESS LOGGING
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "USER_DATA"


SQL>

Alternatively, use some GUI tool which lets you see that info in a matter of a few clicks.

Littlefoot
  • 131,892
  • 15
  • 35
  • 57
2

If "query that created a given table" means table was created with CTAS, for example like this

create table some_table as select ... ;

Then you may use v$sql hoping the query is still there

select * from v$sql where upper(sql_text) like 'CREATE TABLE%';
ekochergin
  • 4,109
  • 2
  • 12
  • 19