What is a primary key in a database?

Instruction: Explain uniqueness, non-NULL values, and composite primary keys.

Context: Learn how a primary key identifies table rows and how a composite key works.

Updated

Example Answer

A primary key uniquely identifies each row, and its columns cannot be NULL. A table has one primary-key constraint, although that key can contain several columns. I choose a stable key that other tables can reference.

Small example

CREATE TABLE order_items (
    order_id INTEGER NOT NULL,
    product_id INTEGER NOT NULL,
    quantity INTEGER NOT NULL,
    PRIMARY KEY (order_id, product_id)
);

Here the combination is unique; either column can repeat by itself. A foreign key can reference that combination. A primary key does not have to be an auto-incrementing number.

Reference

PostgreSQL: primary keys

Related Questions