Top Menu

Search This Blog

SQL Constraints(PRIMARY KEY)

Constraints are used to limit the type of data that can go into a table.

Constraints can be specified when a table is created  with the CREATE TABLE statement or after the table is created  with the ALTER TABLE statement.

Here are the most important constraints:

  • PRIMARY KEY
  • NOT NULL
  • UNIQUE
  • FOREIGN KEY
  • CHECK
  • DEFAULT
  • IDENTITY

PRIMARY KEY:
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values. It is normal to just use running numbers,like 1,2,3,4,5,…as values is Primary Key column.IDENTITY(1,1) means the first value will be 1 and then it will increment by 1.

Each table can have only ONE primary key.


CREATE TABLE CANDIDATE
 (
   CandidateId int IDENTITY(1,1) PRIMARY KEY,
   CandidateNumber int NOT NULL UNIQUE,
   LastName varchar(50) NOT NULL,
   FirstName varchar(50) NOT NULL,
   PostCode int NULL,
   Address varchar(50) NULL,
   Phone varchar(50) NULL,
)


you see we use the “Primary Key”:









Set Primary Keys in the MS-SQL Server Tools:
If you use the MS-SQL Server tools you can easily set the primary Key in a table just by right‐click and select “Set primary Key”.


















The primary Key column will then have a small key  in front that this column is a Primary Key.





Post a Comment

Designed by OddThemes | Distributed By Gooyaabi Templates