Primary key with two columns in Oracle? - oracle

I have tables with emp1 and emp2
emp1:
emp_1 | emp_2
1 | 2
3 | 4
5 | 6
emp2:
emp
1
2
3
6
I tried to set primary key to table emp1 and foreign key to emp2.
My code:
For primary key:
alter table emp1 add primary key(emp_1,emp_2);
For foreign key:
alter table emp2
add foreign key (emp)
references a_t1(emp_1,emp_2);
Error:
Error report -
SQL Error: ORA-02256: number of referencing columns must match referenced columns
02256. 00000 - "number of referencing columns must match referenced columns"
*Cause: The number of columns in the foreign-key referencing list is not
equal to the number of columns in the referenced list.
*Action: Make sure that the referencing columns match the referenced
columns.
Kindly help me to solve this error and set the primary key.

The only way I can think to do it is a nasty hack involving a materialized view. It would be better to fix your data so that you don't have the primary key spread across two columns.
CREATE TABLE EMP1 (
EMP_1 INT UNIQUE,
EMP_2 INT UNIQUE,
PRIMARY KEY ( EMP_1,EMP_2 )
);
CREATE MATERIALIZED VIEW LOG ON EMP1
WITH SEQUENCE, ROWID(EMP_1, EMP_2)
INCLUDING NEW VALUES;
CREATE MATERIALIZED VIEW EMP1_MV
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS SELECT EMP_1 AS EMP
FROM EMP1
UNION ALL
SELECT EMP_2
FROM EMP1;
ALTER TABLE EMP1_MV ADD CONSTRAINT EMP1_MV__PK PRIMARY KEY ( EMP );
CREATE TABLE EMP2 (
EMP INT PRIMARY KEY REFERENCES EMP1_MV( EMP )
);

Related

How do I create a foreign key on two columns that are under the primary key constraint?

CREATE TABLE "RESEARCH_DEP"."RESEARCH_TV_COMPANY"
( "CID" NUMBER(38,0) NOT NULL ENABLE,
"SOURCE_ID" NUMBER(2,0),
CONSTRAINT "PK_RESEARCH_TV_COMPANY_1" PRIMARY KEY ("CID", "SOURCE_ID")
USING INDEX (CREATE UNIQUE INDEX "RESEARCH_DEP"."IDX_TV_COMPANY_CID_SOURCE_ID" ON "RESEARCH_DEP"."RESEARCH_TV_COMPANY" ("CID", "SOURCE_ID")
CREATE TABLE "RESEARCH_DEP"."RESEARCH_METRICS_PHARMA_AUD"
( "ID" NUMBER GENERATED ALWAYS AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE NOKEEP NOSCALE NOT NULL ENABLE,
"SOURCE_ID" NUMBER(2,0) NOT NULL ENABLE,
"MEDIA_COMPANY_ID" NUMBER(*,0) NOT NULL ENABLE
)
NEED
ALTER TABLE RESEARCH_DEP.RESEARCH_METRICS_PHARMA_AUD
ADD CONSTRAINT fk_METRICS_PHARMA_AUD_TV_COMPANY_ID
FOREIGN KEY (MEDIA_COMPANY_ID,SOURCE_ID) REFERENCES RESEARCH_DEP.RESEARCH_TV_COMPANY(CID,SOURCE_ID);
ORA-02298: parent keys not found
DO I NEED TO CREATE A COMPOSITION COLUMN: CID,SOURCE_ID?
OR
create sequence of values two column oracle CID,SOURCE_ID ?
Your code is more or less OK:
SQL> create table research_tv_company
2 (cid number,
3 source_id number,
4 --
5 constraint pk_rtc primary key (cid, source_id)
6 );
Table created.
SQL> create table research_metrics_pharma_aud
2 (id number,
3 source_id number,
4 media_company_id number
5 );
Table created.
SQL> alter table research_metrics_pharma_aud
2 add constraint fk_rmpa_rtc
3 foreign key (media_company_id, source_id)
4 references research_tv_company (cid, source_id);
Table altered.
SQL>
Note that I
removed double quotes
removed NOT NULL for primary key columns (they can't be NULL anyway)
don't have any indexes created so Oracle will - along with table creation - create a primary key constraint AND unique index to support it
as I'm on 11gXE and it doesn't support identity columns, I removed that
from the second table; I'd have to enforce it via a trigger. You don't have to do anything about it, just saying (so that you wouldn't wonder where did it go?)
Error you got:
ORA-02298: parent keys not found
means that there are combinations of (media_company_id, source_id) in the second table that do not exist as pairs of (cid, source_id) in the first table. To illustrate it:
Drop the foreign key constraint first (otherwise, I wouldn't be able to do that):
SQL> alter table research_metrics_pharma_aud drop constraint fk_rmpa_rtc;
Table altered.
Insert a row into the first (master) table:
SQL> insert into research_tv_company (cid, source_id) values (1, 1);
1 row created.
Insert two rows into the second (detail) table; the first combination is valid, the second is not as (2, 2) don't exist in research_tv_company:
SQL> insert into research_metrics_pharma_aud (id, source_id, media_company_id) values (1, 1, 1);
1 row created.
SQL> insert into research_metrics_pharma_aud (id, source_id, media_company_id) values (2, 2, 2);
1 row created.
SQL>
If we try to create a foreign key constraint:
SQL> alter table research_metrics_pharma_aud
2 add constraint fk_rmpa_rtc
3 foreign key (media_company_id, source_id)
4 references research_tv_company (cid, source_id);
add constraint fk_rmpa_rtc
*
ERROR at line 2:
ORA-02298: cannot validate (SCOTT.FK_RMPA_RTC) - parent keys not found
SQL>
See? The same error you got.
What can you do?
insert missing primary key values into the master table, or
delete detail rows that violate the constraint, or
create the constraint, but instruct Oracle not to check whether existing rows are valid or not:
SQL> alter table research_metrics_pharma_aud
2 add constraint fk_rmpa_rtc
3 foreign key (media_company_id, source_id)
4 references research_tv_company (cid, source_id)
5 enable novalidate;
Table altered.
SQL>
The enable novalidate means that foreign key constraint will be enabled for any new or modified rows, but existing rows won't be checked. If that option suits you, use it. However, I believe that one of the first two option is better, with the first one - adding missing primary keys - being the best.

How to make foreign key from two different table in third table?

I have three tables named as :
Staff(id,name,address);
Members(id,name,address);
Plans(id,Userid,type);
I want to create Userid from Plans foreign key for both Staff and Members table
How can i do it?
Umm ... not like that.
Staff and members should be stored in the same table, with additional column (and table to be referenced) which says whether someone is "staff" or "member". Then plans table doesn't have a problem any more.
SQL> create table type_sm
2 (id_sm number constraint pk_tsm primary key,
3 name varchar2(20) constraint ch_typ check (name in ('staff', 'member'))
4 );
Table created.
SQL> create table staff_members
2 (id_sta_mem number constraint pk_stamem primary key,
3 id_sm number constraint fk_sm_typ references type_sm (id_sm),
4 name varchar2(20),
5 address varchar2(30)
6 );
Table created.
SQL> create table plans
2 (id_pla number constraint pk_pla primary key,
3 id_sta_mem number constraint fk_plastamem references staff_members (id_sta_mem)
4 );
Table created.
SQL>

add composite/ foreign key in sqlplus

I have a very basic question regarding the Keys in SQL. I am trying to write an SQL statement so I can add the foreign key to my tables, however, it would always "table not found or missing". And the reason why I can't create that table is that the next table also has foreign keys from another table that I need to reference. Is there a way around it?
create table table_name (id char (3) primary key, name varchar (8));
SQL > table created.
create table table_name_2 (table2ID char (3) primary key, CID char (3),
name varchar (8), title varchar (8), foreign key (CID) references table_name_3);
SQL > missing table (table_name_3);
create table table_name_3 (CID char (3) primary key, tTitle varchar (8),
foreign key (phone) references table_name_4);
So I was only able to create table 3. What do I need to do so that I can create the table and add the foreign keys referencing while I write the SQL statements?
I am not ALLOWED to use ALTER table.
Create foreign keys separately, using the ALTER TABLE statement. Like this:
SQL> CREATE TABLE table_name(
2 id CHAR(3)PRIMARY KEY,
3 name VARCHAR(8)
4 );
Table created.
SQL> CREATE TABLE table_name_2(
2 table2id CHAR(3)PRIMARY KEY,
3 cid CHAR(3),
4 name VARCHAR(8),
5 title VARCHAR(8)
6 );
Table created.
SQL> CREATE TABLE table_name_3(
2 cid CHAR(3)PRIMARY KEY,
3 ttitle VARCHAR(8)
4 );
Table created.
Now the foreign key:
SQL> ALTER TABLE table_name_2 ADD CONSTRAINT fk_2_3 FOREIGN KEY(cid)
2 REFERENCES table_name_3;
Table altered.
SQL>
one approach you can od is to create the table with the Primary key and then do
and add the foreign key.
ALTER TABLE child_table
ADD CONSTRAINT fk_name
FOREIGN KEY (col1) REFERENCES parent_table(col1);

Alter Table , adding a Foreign key constraint at a column ORA-02253

Hello there i am studying for the Oracle Certification of SQL Associate .
And trying to do some Examples .
I have an issue where i cannot find easily a reference on this .
create table employees
(employee_id number NOT NULL,
first_name varchar(20),
last_name varchar(30),
constraint employee_pk primary key (employee_id));
create table employee_notes
(employee_notes_id number,
employee_notes varchar(500),
constraint pk_employee_notes primary key (employee_notes_id));
create sequence employee_notes_seq start with 1 increment by 1
Now i want to add a new column at employee_notes table with a foreign key constraint .
I can't find out in syntax where is the problem .
****alter table employee_notes
add employee_id number
constraint fk_employee_notes foreign key (employee_id) references employees (employee_id);****
i get this error
ORA-02253: constraint specification not allowed her
I also tried to alter the table and add column and then the constraint but cannot
alter table employee_notes
add employee_id number;
--
alter table employee notes
add constraint fk_employee_notes foreign key (employee_id) references employees (employee_id);
ORA-02253: constraint specification not allowed here
I would like to know how i can do this
and why this syntax is wrong :)
You did something wrong because - it works OK:
SQL> CREATE TABLE employees
2 (
3 employee_id NUMBER NOT NULL,
4 first_name VARCHAR (20),
5 last_name VARCHAR (30),
6 CONSTRAINT employee_pk PRIMARY KEY (employee_id)
7 );
Table created.
SQL>
SQL> CREATE TABLE employee_notes
2 (
3 employee_notes_id NUMBER,
4 employee_notes VARCHAR (500),
5 CONSTRAINT pk_employee_notes PRIMARY KEY (employee_notes_id)
6 );
Table created.
SQL> ALTER TABLE employee_notes ADD employee_id NUMBER;
Table altered.
SQL> ALTER TABLE employee_notes ADD CONSTRAINT fk_employee_notes
2 FOREIGN KEY (employee_id)
3 REFERENCES employees (employee_id);
Table altered.
SQL>
When you use ALTER TABLE ... ADD in order to add a column and a constraint in one statement, do the following:
-- notice the () and the comma!
alter table employee_notes
add (
employee_id number
, constraint fk_employee_notes
foreign key (employee_id) references employees (employee_id)
) ;
That should do the trick. See dbfiddle. The syntax is similar to CREATE TABLE, where you'd also write all column names, data types etc in (), separated by commas.

In oracle on delete set null is not working

I have created two tables:
Create Table Dept
(Department_id number Constraint Depart_id_pk Primary Key
,Department_name varchar2(20));
Create table Emp
(Emp_id number Constraint Empl_id_pk Primary Key
,First_name varchar2(10)
,salary number
,Department_id number
,Constraint depart_id_fk Foreign Key (department_id)
References Dept (Department_id) on delete set null);
Then I have inserted some records in dept and Emp table. But when I try to drop dept table, instead of setting null in Emp.department_id column it shows error like this:
SQL> Drop Table Dept;
Drop Table Dept
*
ERROR at line 1:
ORA-02449: unique/primary keys in table referenced by foreign keys
The foreign key's clause say "on delete set null". Delete is a DML operation, and had you attempted to delete rows from the dept table, the corresponding emp rows would have been updated with a null dept_id.
But this isn't the case - you tried to drop the entire table, a DDL operation. This isn't allowed, because you'd be leaving behind constraints on the emp table that reference a table that no longer exists. If you want to drop these constraints too, you can use a cascade constraints clause:
DROP TABLE dept CASCADE CONSTRAINTS

Resources