Home

Primary Keys

   

Introduction

To create a primary column using SQL, use the PRIMARY KEY keyword. Here is an example:

CREATE TABLE Persons
(
    PersonID int identity(1,1) PRIMARY KEY NOT NULL,
    FirstName nvarchar(20),
    LastName nvarchar(20) NOT NULL
);

A Constraint on the Primary Key

You can also create a primary key as a constraint. The  formula to use is:

CONSTRAINT PrimaryKeyName PRIMARY KEY(ColumnName)

Here is an example:

CREATE TABLE Persons
(
    PersonID int identity(1,1) NOT NULL,
    FirstName nvarchar(20),
    LastName nvarchar(20) NOT NULL,
    CONSTRAINT PrimKeyPeople PRIMARY KEY(PersonID)
);

By convention or tradition, the name of the primary starts with PK_ followed by the name of the table. Here is an example:

USE Exercise2;
GO

CREATE TABLE Persons
(
    PersonID int identity(1,1) NOT NULL,
    FirstName nvarchar(20),
    LastName nvarchar(20) NOT NULL,
    CONSTRAINT PK_Persons PRIMARY KEY(PersonID)
);
GO

Home Copyright © 2007-2011 FunctionX.com, Inc.