Primary key in SQL

A primary key is a one-column or combination of the column with a unique value for each row or tuple. The value of the primary key must be unique within the table. The purpose is to bind data together, across tables, without repeating all of the data in every table. It enforces two restrictions on the column – First is Unique value and second is Not null

A primary key is the candidate key that is selected to uniquely identify a tuple in a relation. The mandatory and desired attributes for a primary key are:

Mandatory termDesired term
must uniquely identify a rowshould not change with time(should be fixed)
must not allow NULL values in rowsshould have short size like numeric data types

Note:- When two or more columns together identify the unique row then it is referred to as Composite Primary Key. The combination of rollno and year if selected as a primary key would be a composite primary key.

To implement Primary Key there are four ways. Which are given below:-

Type:-1

CREATE TABLE Personstable
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT per_pk Primary Key (P_Id)
)



Type:-2
CREATE TABLE Persontable
(
P_Id int CONSTRAINT per_pk Primary Key (P_Id) ,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)


Type:-3
CREATE TABLE Persontable
(
P_Id int Primary Key (P_Id) ,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)


Type:-4

CREATE TABLE Persontable
(
P_Id int ,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
Primary Key (P_Id)
)

If you have any query on database management system then comment your questions

Thank you

2 thoughts on “Primary key in SQL

Leave a Reply

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