In a relational database, a set of attributes is considered a superkey if it can uniquely identify each tuple (row) in a relation (table). This means no two distinct tuples in a valid instance of the relation can have the same values for all attributes in the super key.

A candidate key is a minimal superkey, meaning it has no proper subset that is also a superkey. If any attribute is removed from a candidate key, it loses its ability to uniquely identify tuples.

It is possible to have multiple candidate keys for a single table, but an RDBMS can have at most one primary key for a single table. The database designer picks a primary key from candidate keys. The primary key serves as the main identifier for tuples in the relation.

In SQL

In SQL, we use integrity constraints to represent keys.

To add a primary key constraint, we can use the primary key keyword:

create table Student (
    studentNumber integer primary key,
    name          varchar(50) not null
);

Alternatively, we can add primary key with extra clauses:

create table Student (
    studentNumber integer,
    name          varchar(50) not null,
    primary key   (studentNumber)
);

composite primary key

An explicit clause can be very useful if we have a table where no single column is an identifier, and we want to use multiple columns:

create table EnrolledIn (
 studentNumber integer,
 course        char(8),
 grade         integer,
 PRIMARY KEY (studentNumber, course)
);

We can also name the primary key constraint,

create table Student (
    studentNumber integer,
    name          varchar(50) not null,
    constraint S_PK primary key (studentNumber)
);

or even change it after table creation:

create table Student (
    studentNumber integer,
    name          varchar(50) not null
);
 
alter table Student add constraint S_PK primary key (studentNumber);

unique Constraints

The unique constraint can be used to express candidate keys. It is useful if we want columns other than the primary key to be unique. For example,

create table Student (
    -- In my university, student number and id are two different identifiers for students
    studentNumber integer primary key,
    studentID     char(8) unique not null,
    name          varchar(50) not null
);

Note because unique permit null, a candidate key must be declared unique not null.

On null and unique

SQL standard allows more than one row with null values in a unique column. However, some DBMSs allow at most one row with null in that column.

See also