How to know to which columns a foreign key is referencing in Oracle SQL Developer?

637 Views Asked by At

I can check what the columns in a foreign key are that are referencing but how do I know which columns this foreign key is referencing in the other table? Since, it doesn't have to be the primary keys of a table. Is there an easy way to do this on Oracle SQL Developer without executing any query?

2

There are 2 best solutions below

0
On BEST ANSWER

You could join the user_cons_columns and user_constraints views to get the metadata information for the primary key and foreign key references.

For example,

SQL> COLUMN table_name format a10
SQL> COLUMN column_name format a11
SQL> COLUMN constraint_name format a20
SQL> COLUMN owner format a10
SQL> COLUMN ref_table_name format a15
SQL> COLUMN ref_pk format a10
SQL> SELECT a.table_name,
  2    a.column_name,
  3    a.constraint_name,
  4    b.owner,
  5    c_pk.table_name ref_table_name,
  6    c_pk.constraint_name ref_pk
  7  FROM user_cons_columns a
  8  JOIN user_constraints b
  9  ON a.owner            = b.owner
 10  AND a.constraint_name = b.constraint_name
 11  JOIN user_constraints c_pk
 12  ON b.r_owner            = c_pk.owner
 13  AND b.r_constraint_name = c_pk.constraint_name
 14  WHERE b.constraint_type = 'R';

TABLE_NAME COLUMN_NAME CONSTRAINT_NAME      OWNER      REF_TABLE_NAME  REF_PK
---------- ----------- -------------------- ---------- --------------- ----------
EMP        DEPTNO      FK_DEPTNO            SCOTT      DEPT            PK_DEPT

SQL>

You could also use DBMS_METADATA.GET_DDL to generate the DDL for the table. It will have complete table information.

For example,

SQL> set long 200000 pages 0 lines 131
SQL> column txt format a121 word_wrapped
SQL> select dbms_metadata.get_ddl('TABLE', 'EMP') from dual;

  CREATE TABLE "SCOTT"."EMP"
   (    "EMPNO" NUMBER(4,0),
        "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 "USERS"  ENABLE,
         CONSTRAINT "FK_DEPTNO" FOREIGN KEY ("DEPTNO")
          REFERENCES "SCOTT"."DEPT" ("DEPTNO") 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 "USERS"
0
On

Without executing any query, Yes.

Open the table editor.

enter image description here

If you don't see the Model page, upgrade to version 4.1