Wednesday, May 1, 2013

oracle Add Primary Key Constraints

oracle Add Primary Key Constraints

    Primary key constraint makes sure all rows are unique. It uniquely identifies rows in the table.
It doesn't accept null values.it can be single column or multiple columns..

Every individual row can be fetched with primary key. and it returns only one row.

for ex:  if Employee number is primary key in the table.  then Every employee has only one employee number. with that employee number user can get his/her details. Employee table never allow more than one employee number to Employee . if administrator assigns another empno, then it becomes duplicate value for that employee.


Add Primary key constraint using Alter table command

Syntax: alter table [tablename] add constraint [constraint_name]  primary key (col1,col2,col3...);


for ex: alter table employees add constraint pk_emp_empno primary key (empno);


Multicolumn Primary key Constraint

ex: Alter table houseaddress add constraint pk_ha primary key(ID,hno);


Adding Primary key Constraint to Existing Table


SQL> select * from sports;
 

        ID NAME                 CO
---------- -------------------- --
         1 cricket              IN
         2 cricket              UK
         3 Hand FootBall        US
         4 Base Ball            US

Sports table has data and ID column has all rows are unique.(1,2,3,4), no number is repeated ,so you can add primary key constraint to this column. 



Ex: alter table sports add constraint pk_sports_id primary key(ID);

 
 Tags:oracle Add Primary Key Constraints, alter table primary key, single column primary constraint, multiple column primary key in oracle, adding primary key with alter table,
adding multi column primary key with alter table,
Adding Primary key Constraint to Existing Table

No comments:

Post a Comment