Video in progress

A composite natural key or a surrogate `id`: how do you choose a table's primary key?

In most cases I use a surrogate bigint PK and make the natural key (say, country_code + passport_no) a separate unique constraint. A natural key can change, makes FKs bigger, and is awkward with an ORM. The exception is pure link (many-to-many) tables, where a composite PK is natural.

📖 Answer

The problem with a natural key is that values that "never change" do change. A passport is replaced, a phone number passes to another person, an email changes. If a PK changes, all the FKs that reference it have to be updated too.

Size matters as well: (country_code char(2), passport_no varchar(20)) is repeated in every child table, and in every index too. A bigint is 8 bytes.

So:

CREATE TABLE person (
    id            bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    country_code  char(2)     NOT NULL,
    passport_no   varchar(20) NOT NULL,
    UNIQUE (country_code, passport_no)
);

The business rule (one passport, one person) is kept by the unique constraint, and the PK is technical.

In a many-to-many table, though:

CREATE TABLE user_role (
    user_id bigint REFERENCES users(id),
    role_id bigint REFERENCES roles(id),
    PRIMARY KEY (user_id, role_id)
);
CREATE INDEX ON user_role (role_id);   -- for the reverse direction

Here a surrogate id adds nothing, just an extra index.

On the JPA side, a composite key requires @EmbeddedId or @IdClass, and you have to write equals/hashCode correctly, which is extra code and a place to make mistakes. That's another vote for the surrogate.