Primary keys

Introduction to Relational Databases in SQL

Timo Grossenbacher

Data Journalist

Primary keys

  • One primary key per database table, chosen from candidate keys
  • Uniquely identifies records, e.g. for referencing in other tables
  • Unique and not-null constraints both apply
  • Primary keys are time-invariant: choose columns wisely!
Introduction to Relational Databases in SQL

Specifying primary keys

CREATE TABLE products (
    product_no integer UNIQUE NOT NULL,
    name text,
    price numeric
);
CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

Taken from the PostgreSQL documentation.

CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    PRIMARY KEY (a, c)
);
Introduction to Relational Databases in SQL

Specifying primary keys (contd.)

ALTER TABLE table_name
ADD CONSTRAINT some_name PRIMARY KEY (column_name)
Introduction to Relational Databases in SQL

Introduction to Relational Databases in SQL

Let's practice!

Introduction to Relational Databases in SQL

Preparing Video For Download...