Thursday 1 August 2013

Creating database Constraints -Part 2

Bismillahir Rahmanir Raheem
Now we are going to see the other way of creating constraints with Alter table statement.
And with that we will also look at both the approach in-line and outof-line.

Lets start creating constraints one by one.
1. Primary Key constraint
DML ststement for the table creation is
create table xyz(x number);

a)in-line
alter table xyz
modify x primary key;
    or
alter table xyz
modify x constraint cons1 primary key;   

b)outof-line
alter table xyz
add primary key(x);
    or
alter table xyz
add constraint c1 primary key(x);

2. Unique Key Constraint   
DML ststement for the table creation is
create table xyz(x number);

a)in-line
alter table xyz
modify x unique;
    or
alter table xyz
modify x constraint unique;

b)outof-line
alter table xyz
add unique(x);
    or
alter table xyz
add constraint cvh unique(x);

3. Check Constraint   
Again DML ststement for the table creation is
create table xyz(x number);

a)in-line
alter table xyz
modify x check(x in (1,2));
    or
alter table xyz
modify x constraint check1 check(x in(1,2));

b)outof-line
alter table xyz
add check(x in(1,2));
        or
alter table xyz
add constraint cer check(x in(1,2));

4. Foreign key constraint
Here are the DML statements of the tables used below.

create table f1(id number primary key);
create table f2(name varchar2(20),assignment number);

a)in-line   
alter table f2
modify assignment references f1(id);
    or
alter table f2
modify assignment constraint fk_cons references f1(id);

b)outof-line
alter table f2
add foreign key(assignment)    references f1(id);
    or
alter table f2
add constraint fk_cons foreign key(assignment) references f1(id);

5.    Not null constraint
DML ststement for the table creation is
create table xyz(x number);
a)in-line
alter table xyz
modify x not null;
    or
alter table xyz
modify x constraint nyc not null;

b)outof-line
As the case with create table statement same is true for alter table statement
you can not use outof-line approach for not null constraint    .




   

No comments:

Post a Comment