0% found this document useful (0 votes)
51 views11 pages

Class 05

The document discusses foreign key constraints and composite primary keys. It provides an example of creating tables with a composite primary key on two columns, and incorrectly trying to create a foreign key constraint on only one of those columns. It explains that a foreign key must reference the entire composite primary key, not just parts of it.

Uploaded by

K Harish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views11 pages

Class 05

The document discusses foreign key constraints and composite primary keys. It provides an example of creating tables with a composite primary key on two columns, and incorrectly trying to create a foreign key constraint on only one of those columns. It explains that a foreign key must reference the entire composite primary key, not just parts of it.

Uploaded by

K Harish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Question: I have a FK relation between 2 tables and I want data will not be deleted from child table.

What can we do?


Answer:

CREATE TABLE supplier


( supplier_id numeric(10) not null,
  supplier_name varchar2(50) not null,
  contact_name varchar2(50),
  CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);

CREATE TABLE products


( product_id numeric(10) not null,
  supplier_id numeric(10),
  CONSTRAINT fk_supplier
    FOREIGN KEY (supplier_id)
    REFERENCES supplier(supplier_id)
    ON DELETE SET NULL
);

insert into supplier values (1, 'azx','yryryr');


  insert into supplier values (2, 'rrr','hyuj');
   insert into supplier values (3, 'ggg','seedf');
    insert into supplier values (4, 'uuu','ghyujk');
   
  
insert into products values (1,1);
    insert into products values (1,4);
  
    delete from supplier where supplier_id = 1
  
    select * from products;
Oracle not allow orphan child, so row will be saved but data set to null.

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Question: Can I create a foreign key against only part of a composite primary key?
Answer: NO

CREATE TABLE StuffType


(
  TypeID INT NOT NULL,
  AltID INT NOT NULL,
  TypeName VARCHAR(10) NOT NULL,
  CONSTRAINT pk_StuffType PRIMARY KEY (TypeID, AltID)
);

CREATE TABLE OurStuff


(
  StuffID INT NOT NULL PRIMARY KEY,
  StuffName VARCHAR(10) NOT NULL,
  OurTypeID INT NULL,
  CONSTRAINT fk_StuffType FOREIGN KEY (OurTypeID)
    REFERENCES StuffType(TypeID)
);
Here in child table, I am trying to create FK on a part of PK. It gives errors as expected.

--> Why this error coming? Go to base concept that FK of one table refer to primary/unique key of another table. Here in above
example we created PK as a composite PK PRIMARY KEY (TypeID, AltID), so while creating FK, it should refer to both as a
composite, not as a part. but we are doing  REFERENCES StuffType(TypeID)

Solution is  to create the same combination:

CREATE TABLE OurStuff


(
  StuffID INT NOT NULL PRIMARY KEY,
  StuffName VARCHAR(10) NOT NULL,
  OurTypeID INT NULL,
  OurAltID INT NULL,
  CONSTRAINT fk_StuffType FOREIGN KEY (OurTypeID, OurAltID)
    REFERENCES StuffType(TypeID, AltID)
);
--------------------------------------------------------------------------------------------------------------------
/* More than 6+Years exp*/

composite key
A composite key is a key (primary or alternate) that consists of more than one column. 

create table D (
  ID numeric(1),
  CODE varchar(2),
  constraint PK_D primary key (ID, CODE)
);

composite primary key Vs Sequence

This is a controversial point. If my table with a composite primary key is expected to have millions of rows, the index controlling the
composite key can grow up to a point where CRUD operation performance is very degraded. In that case, it is a lot better to use a simple
integer ID primary key whose index will be compact enough and establish the necessary DBE constraints to maintain uniqueness.
=========================================================================================

Constraints: (when ever we have to strict user over the database level, we have to use constraints)

Oracle Constraints

Oracle constraints are critical to the scalability, flexibility and integrity of your database data.
Constraints apply specific rules to data, ensuring the data conforms to the requirements defined.
There are a number of different kinds of constraints that you will be concerned with as a DBA. These
are:

1. Check
2. Not NULL
3. Primary key
4. Unique
5. Foreign Key

Create table my_status


( status_id     NUMBER      PRIMARY KEY,
  person_id     NUMBER      NOT NULL,
  active_record VARCHAR2(1) NOT NULL
  CHECK (UPPER(active_record)='T' or
         UPPER(active_record)='F'),
  person_ssn   VARCHAR2(20) CONSTRAINT un_person_ssn UNIQUE
);

Insert Into my_status values (2,2,'F','4444'); --> this will be inserted

--> NOT NULL constrains strict users that we cannot insert NULL values in that column. 
Insert Into my_status values (1,1,'X','43435'); --> This will give you check constraint violated
error, because we created a check constraint on column active_record and it should accept the values
'T' and 'F' only. here we are trying to insert 'X' which is not acceptable.
Example, you can explain in interview, that only age> 18 allowed in factory

create table test123(


id number,
age number
)

ALTER TABLE test123


ADD (CONSTRAINT ck_test123
  CHECK ( age > 18));
 
  insert into test123 values (1,10);

not allowing value 10 in the age column, because we created a check constraint that always check the
value before insertion and it must be > 18.
If you need to add a check constraint to a table after the table creation, simply use the alter
table command. Here is an example:

ALTER TABLE my_status


ADD (CONSTRAINT ck_vishal --> (ck_vishal is the name of check constraint. that can be any name as
per our wish)
  CHECK (UPPER(active_record)='T' or
         UPPER(active_record)='F') );

====================================================================================================
============

Question:

How to ensure a constraint to check Answer column of Questions table allows only


‘A’,’B’,’C’,’D’,’P’);

Answer:

We have to create a check constraint, which will validate the record before insert.

 ALTER TABLE Questions

ADD (CONSTRAINT ck_Answer

  CHECK (Answer ='A' or

         Answer='B' or

         Answer='C' or

         Answer='D' or

         Answer='P'

         )
         );

After this if we try to insert a record like below:

         Insert into Questions values ('Q1','frthyy','ju','loi','hytu','jkui','A',sysdate);

This will inserted, because values in Answer column is A, but if try to insert any other value other
than ‘A’,’B’,’C’,’D’,’P’ Then it will not allow:

                  Insert into Questions values ('Q1','frthyy','ju','loi','hytu','jkui','X',sysdate);

Here I am trying to insert a value ‘X’ in answer column, it gives error.

02290. 00000 -  "check constraint (%s.%s) violated"

*Cause:    The values being inserted do not satisfy the named check

=================================================================================================

You might also like