Search code examples
sqldatabaseoracleforeign-keys

Add multiple foreign keys to existing table in Oracle


I want to add multiple foreign keys to existing table in Oracle database. Following sql query gives me an error. One by one I can add foreign key constraint. But I want to do this within one statement like below.

ALTER  TABLE address                                                                                                  
ADD  CONSTRAINT fk_customer_id FOREIGN KEY (customer_id) 
     REFERENCES  customer (id) ON  DELETE CASCADE ,
ADD  CONSTRAINT fk_city_id     FOREIGN KEY (city_id) 
     REFERENCES  city (id) ON  DELETE  CASCADE;

Any idea how to do this?


Solution

  • That's not entirely true (what @Thorsten has said). You can add two constraints at a time.

    SQL> create table test (empno number, deptno number);
    
    Table created.
    
    SQL>
    SQL> alter table test add
      2    ( constraint fk_test_emp  foreign key (empno)  references emp (empno),
      3      constraint fk_test_dept foreign key (deptno) references dept (deptno)
      4    );
    
    Table altered.
    
    SQL>