12/09/2020
Primary Key SQL / Primary Key Constraint in SQL
**********************************************************
-- Primary Key Constraint: Primary Key constraint is used to create unique value in the field/column.
-- Primary Key constraint: It can not accept NULL Value.
--Example:
Create Table OrderDetails
(
OrderId int NOT NULL constraint pkPrimary Primary Key,--Applying Primary key 'pkPrimary' is name of Primary key
ProductId int NOT NULL,
ProductName varchar(30)NOT NULL,
Price float not null,
Quantity int NOT NULL,
SumAmount float NOT NULL,
Country varchar(30)NOT NULL,
ZipCode varchar(20)NOT NULL,
ContactNo Varchar(30)NOT NULL,
eMail varchar(50)NOT NULL,
OrderDate Datetime NOT NULL,
CustomerId int NOT NULL,
DeliveryDate Date not null,
TrackingID int not null,
Remarks varchar(300)
)
Select * from OrderDetails
--Now Inserting vlaues
Insert into OrderDetails values('1','1','DEL Laptop',200,50,200*50,'Korea','###XX','#########X','[email protected]',GETDATE(),2,GETDATE(),05,'Fast')
--We have used Primary Key Constraint on OrderId. we are going to check.
--Here is, the OrderId 1 is already inserted. Again we are trying to insert same order id
Insert into OrderDetails values('2','1','Dell Desktop',150,20,150*20,'USA','###XX','#########X','[email protected]',getdate(),2,getdate(),15,'Fast')
--Here is an error because we have inserted sam order id
Insert into OrderDetails values('3','2','Acer',150,50,150*50,'Canada','###XX','#########X','[email protected]',GETDATE(),4,GETDATE(),06,'Fast')
Insert into OrderDetails values('4','4','iPhone',100,300,100*50,'UK','###XX','#########X','[email protected]',GETDATE(),6,GETDATE(),07,'Fast')
Insert into OrderDetails values('5','1','iPhone',100,100,100*100,'Korea','###XX','#########X','[email protected]',GETDATE(),2,GETDATE(),09,'Fast')
Insert into OrderDetails values('6','1','Mouse',20,100,20*100,'Korea','###XX','#########X','[email protected]',GETDATE(),2,GETDATE(),12,'Fast')
Insert into OrderDetails values('7','5','DELL Server',500,50,500*50,'USA','###XX','#########X','[email protected]',GETDATE(),8,GETDATE(),11,'Fast')
Select * from OrderDetails
--Some more query
Select * from OrderDetails where OrderId='1'
Select * from OrderDetails where CustomerId='2'
Select SUM(SumAmount) from OrderDetails Where ProductId='1'
Select COUNT(CustomerId) from OrderDetails where CustomerId='2'