Sql Primary Key Constraints


July 16, 2008   SQL — Tags: , , — 52coding    

Primary key is the term used to identify one or more columns in a table that make a row of data unique. Although the primary key typically consists of one column in a table, more than one column can comprise the primary key. For example, either the employee’s Social Security number or an assigned employee identification number is the logical primary key for an employee table. The objective is for every record to have a unique primary key or value for the employee’s identification number. Because there is probably no need to have more than one record for each employee in an employee table, the employee identification number makes a logical primary key. The primary key is assigned at table creation.
The following example identifies the EMP_ID column as the PRIMARY KEY for the EMPLOYEES table:

CREATE TABLE EMPLOYEE_TBL
(EMP_ID聽聽聽聽聽聽聽 CHAR(9)聽聽聽聽聽聽聽 NOT NULL PRIMARY KEY,
EMP_NAME聽聽聽聽聽聽 VARCHAR (40)聽聽 NOT NULL,
EMP_ST_ADDR聽聽聽 VARCHAR (20)聽聽 NOT NULL,
EMP_CITY聽聽聽聽聽聽 VARCHAR (15)聽聽 NOT NULL,
EMP_ST聽聽聽聽聽聽聽聽 CHAR(2)聽聽聽聽聽聽聽 NOT NULL,
EMP_ZIP聽聽聽聽聽聽聽 INTEGER(5)聽聽聽聽聽 NOT NULL,
EMP_PHONE聽聽聽聽聽 INTEGER(10)聽聽聽聽 NULL,
EMP_PAGER聽聽聽聽聽 INTEGER(10)聽聽聽聽 NULL);

This method of defining a primary key is accomplished during table creation. The primary key in this case is an implied constraint.