SQL SERVER KEYS

Published on by LakshmiSaahul,Dhana Royal

Types of SQL Keys

We have following types of keys in SQL which are used to fetch records from tables and to make relationship among tables or views.

  1. Super Key

Super key is a set of one or more than one keys that can be used to identify a record uniquely in a table.

Example : Primary key, Unique key, Alternate key are subset of Super Keys.

  1. Candidate Key

A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table. There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key.

  1. Primary Key

Primary key is a set of one or more fields/columns of a table that uniquely identify a record in database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key.

  1. Alternate key

A Alternate key is a key that can be work as a primary key. Basically it is a candidate key that currently is not primary key.

  1. Composite/Compound Key

Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate key, Primary key.

  1. Unique Key

Uniquekey is a set of one or more fields/columns of a table that uniquely identify a record in database table. It is like Primary key but it can accept only one null value and it can not have duplicate values.

  1. Foreign Key

Foreign Key is a field in database table that is Primary key in another table. It can accept multiple null, duplicate values.

Defining Keys in SQL Server

--Department Table

CREATE TABLE Department

(

DeptID int PRIMARY KEY, --primary key

Name varchar (50) NOT NULL,

Address varchar (200) NOT NULL

)

--Student Table

CREATE TABLE Student

(

ID int PRIMARY KEY, --primary key

RollNo varchar(10) NOT NULL,

Name varchar(50) NOT NULL,

EnrollNo varchar(50) UNIQUE, --unique key

Address varchar(200) NOT NULL,

DeptID int FOREIGN KEY REFERENCES Department(DeptID) --foreign key

Advertising
To be informed of the latest articles, subscribe:
Comment on this post