WHAT IS THE DIFFERENCE BETWEEN PRIMARY KEY AND FOREIGN KEY IN SQL?

Primary Key VS Foreign Key

S.No.PRIMARY KEYFOREIGN KEY
1A primary key is column of table used to ensure data in the specific column is unique and NOT NULL.A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables.
2Primary Key uniquely identifies a record in the relational database table.Foreign Key refers to the field in a table which is the primary key of another table.
3Only one primary key is allowed in a table.One or more than one foreign keys are allowed in a table.
4Primary Key is a combination of UNIQUE and Not Null constraints.Foreign Key can contain duplicate values and a table in a relational database.
5Primary Key does not allow NULL values.Foreign Key can also contain NULL values.
6Primary Key value cannot be deleted from the parent table.Foreign Key value can be deleted from the child table.
7Primary Key constraint can be implicitly defined on the temporary tables.Foreign Key constraint cannot be defined on the local or global temporary tables.
PRIMARY KEY VS FOREIGN KEY
Primary Key Creation with CREATE TABLE command-

CREATE TABLE [table_name] (

col_1 datatype NOT NULL PRIMARY KEY,

col_2 datatype, ………………….

col_n datatype);

Primary Key Naming with CREATE TABLE command –

CREATE TABLE [table_name] (

col_1 datatype NOT NULL,

col_2 datatype, ………………….

col_n datatype

CONSTRAINT [primarykey_name] PRIMARY KEY (col_name));

Primary Key Creation with ALTER TABLE command-

ALTER TABLE [table_name]

ADD PRIMARY KEY (col_name);

Primary Key Naming with ALTER TABLE command-

ALTER TABLE [table_name]

ADD CONSTRAINT [primarykey_name] PRIMARY KEY (col_name);

–Note-The primary key column(s) must have been declared to not contain NULL values

Foreign Key Creation with CREATE TABLE command –

CREATE TABLE [table_name] (

col_1 datatype NOT NULL PRIMARY KEY,

col_2 datatype FOREIGN KEY REFERENCES [referencetable_name] (col_name), ……..

col_n datatype);

Foreign Key Naming with CREATE TABLE command –

CREATE TABLE [table_name] (

col_1 datatype NOT NULL,

col_2 datatype, ………………….

col_n datatype

CONSTRAINT [foreignkey_name] FOREIGN KEY (col_name)

REFERENCES [referencetable_name] (col_name));

Foreign Key Creation with ALTER TABLE command-

ALTER TABLE [table_name]

ADD FOREIGN KEY (col_name) REFERENCES [referencetable_name] (col_name);

Foreign Key Naming with ALTER TABLE command-

ALTER TABLE [table_name]

ADD CONSTRAINT [foreignkey_name] FOREIGN KEY (col_name)

REFERENCES [referencetable_name] (col_name);


Leave a Reply

Your email address will not be published. Required fields are marked *