A primary key in SQL 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 – The first is Unique value and the 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 term | Desired term |
---|---|
It must uniquely identify a row | It should not change with time(should be fixed) |
It must not allow NULL values in rows | It should have a 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 queries or problem on any topics in database management system then comment your questions
Thank you