×
>
<

Aptitude

Key in DBMS

Primary Key

A primary key is a constraint in a table that uniquely identifies each row record in a database table by enabling one or more the columns in the table as the primary key.

Foreign Key

The foreign key a constraint is a column or list of columns that points to the primary key column of another table

Primary Key

Creating a primary key

A particular column is made as a primary key column by using the primary key keyword followed with the column name

  
CREATE TABLE EMP ( 
  ID   INT           
  NAME VARCHAR (20)       
  AGE  INT       
  COURSE VARCHAR(10)    
  PRIMARY KEY (ID) 
);  
  

  • Here we have used the primary key on ID column then ID column must contain unique values i.e one ID cannot be used for another student.
  • If you try to enter  duplicate value while inserting in the  row you are displayed with an error
  • Hence primary key will restrict you to maintain unique values and not null values in that particular column

Example
  
CREATE TABLE STUDENT (
    ID int ,
    Name varchar(255) ,
    Age int,
    CHECK (Age>=18)
);  
  
Foreign Key

  • The foreign key a constraint is a column or list of columns that points to the primary key column of another table 
  • The main purpose of the foreign key is only those values are allowed in the present table that will match the primary key column of another table.

Example to create a foreign key
  
CREATE TABLE CUSTOMERS1(
   ID   INT ,            
   NAME VARCHAR (20) ,
   COURSE VARCHAR(10) ,
   PRIMARY KEY (ID)
);   
  
Child Table
  
CREATE TABLE CUSTOMERS2(
   ID   INT ,            
   MARKS INT,     
   REFERENCES CUSTOMERS1(ID)
);