Monday, July 27, 2020

SQL Server Primary Key

SQL Server Primary Key

Whats is primary Key in SQL | How to create Primary Key in SQL | Primary Key with Example in SQL Server

The PRIMARY KEY constraint which is uniquely identifies each row in a table into the Database. It must contain UNIQUE values and they can not be null.
A table in SQL is strictly restricted to have one and only one primary key, which is comprised of single or multiple fields (columns).

CREATE TABLE Employee ( /* Create table with a single field as primary key */
    ID INT NOT NULL
    Name VARCHAR(255)
    PRIMARY KEY (ID)
);

CREATE TABLE Employees ( /* Create table with multiple fields as primary key */
    ID INT NOT NULL
    LastName VARCHAR(255)
    FirstName VARCHAR(255) NOT NULL,
    CONSTRAINT PK_Employee
    PRIMARY KEY (ID, FirstName)
);

ALTER TABLE Employees /* Set a column as primary key */
ADD PRIMARY KEY (ID);

ALTER TABLE Employees /* Set multiple columns as primary key */
ADD CONSTRAINT PK_Employee /*Naming a Primary Key*/
PRIMARY KEY (ID, FirstName);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SQL Server Unique Constraint

SQL Server Unique Constraint Whats is Unique Constraint in SQL | How to create Unique Constraint in SQL | Unique Constraint with Example in ...