Entities and Keys

A relational schema starts from the things the system has to remember: restaurants, tables, customers, bookings. Each becomes a table, and each row needs a key that identifies it for its whole life. This page covers how to turn entities into tables, how to choose between a natural key and a surrogate one, and the ways a database (or the application) can generate ids.

Every example in this series uses the same domain, a restaurant booking system, and was run on PostgreSQL 17. The results shown are its output.

The running domain

Restaurant 1──* Table             Customer 1──0..1 LoyaltyCard
Customer   1──* Booking           Booking  *──*    Table
Booking    1──* Order             Order    *──*    MenuItem   (with quantity, price)
MenuCategory 0..1──* MenuCategory (sub-categories)
MenuCategory 1──* MenuItem        Staff ── Waiter | Chef | Manager

This page uses only customers; relationships builds the rest.

From entities to tables

An entity is a kind of thing with its own identity: two customers named Ada are still two customers. An entity becomes a table, each instance a row, and each attribute a column.

Not every noun becomes a table:

  • An attribute with one value per row is a column: a customer's name.
  • A value with no identity of its own that is always read together with its owner can stay a column, or a group of columns: a price in cents, a booking's start time.
  • Something with several values per owner, or with its own identity, is a separate table: a customer's bookings, or a restaurant's tables.
CREATE TABLE customers (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL UNIQUE,
    name  text NOT NULL
);

The primary key (id) identifies the row. NOT NULL and UNIQUE on email say that every customer has exactly one email and no two share it. Constraints are covered in 16g. They are part of the model, not an optional extra: a rule the database enforces holds even when some code path forgets to check it.

Natural and surrogate keys

A natural key is an attribute that already identifies the thing in the real world: an email, a tax code, an ISBN. A surrogate key is a value with no meaning, created only to identify the row: 1, 2, 3, or a UUID.

customers above has both. id is the surrogate primary key, and email is a natural key kept as a UNIQUE constraint (also called an alternate key). That combination is the usual choice, for these reasons:

Natural key as PK Surrogate key as PK
Value changes (a customer changes email) every foreign key that points to it must change too only one column changes
Size in foreign keys and indexes can be long (text) 8 bytes
Composite (several columns) joins and foreign keys repeat every column always one column
Meaning readable in raw data needs a join to read
Duplicates of the real thing prevented by the PK prevented only if the natural key is also UNIQUE

The last row matters: a surrogate key alone does not stop the same customer from being inserted twice. It identifies rows, not real-world things. Keep the natural key as a UNIQUE constraint whenever one exists:

INSERT INTO customers (email, name) VALUES ('ada@example.com', 'Ada'), ('bob@example.com', 'Bob');
INSERT INTO customers (email, name) VALUES ('ada@example.com', 'Ada again');
ERROR:  duplicate key value violates unique constraint "customers_email_key"
DETAIL:  Key (email)=(ada@example.com) already exists.

Natural keys work well when the value really is stable and short: a country code (IT), a currency (EUR), or the pair of keys in a join table (see relationships).

Generating ids in the database

Identity columns

GENERATED ALWAYS AS IDENTITY is the SQL-standard way to number rows; PostgreSQL's older serial does the same thing with less checking. The database picks the value, and RETURNING sends it back in the same statement:

INSERT INTO customers (email, name) VALUES ('cat@example.com', 'Cat') RETURNING id;
 id
----
  3

ALWAYS means the application cannot supply its own value by mistake:

INSERT INTO customers (id, email, name) VALUES (10, 'dan@example.com', 'Dan');
ERROR:  cannot insert a non-DEFAULT value into column "id"
DETAIL:  Column "id" is an identity column defined as GENERATED ALWAYS.
HINT:  Use OVERRIDING SYSTEM VALUE to override.

GENERATED BY DEFAULT AS IDENTITY allows explicit values, which is useful when importing data, but then the generator does not know about the imported ids and later inserts can collide with them.

Ids have gaps

After Ada, Bob and Cat (1, 2, 3), the failed duplicate insert for Ada and the rejected insert of Dan, the next customer gets:

INSERT INTO customers (email, name) VALUES ('eve@example.com', 'Eve') RETURNING id;
 id
----
  5

Id 4 was used up by the insert that failed on the unique email. The generator hands out a value before the row is checked, and never takes it back. Ids are unique and increasing, not consecutive. Code that uses max(id) as a count, or expects no gaps, is wrong.

Sequences

An identity column is backed by a sequence, a database object that returns the next number on each call. A sequence can also be created on its own and shared, or configured:

CREATE SEQUENCE booking_seq START 1000 INCREMENT 50;
SELECT nextval('booking_seq'), nextval('booking_seq');
 nextval | nextval
---------+---------
    1000 |    1050

A sequence is outside transactions: a value taken inside a transaction that is rolled back is gone.

BEGIN; SELECT nextval('booking_seq'); ROLLBACK;   -- returns 1100
SELECT nextval('booking_seq');
 nextval
---------
    1150

This is deliberate. If a rollback could return a value, every other transaction would have to wait to know whether 1100 was still taken, and inserts could not run in parallel.

UUIDs

A UUID is a 128-bit random value. It can be generated anywhere (in the database, the application, the browser) without coordination, because collisions are practically impossible.

CREATE TABLE devices (id uuid PRIMARY KEY DEFAULT gen_random_uuid(), label text);
INSERT INTO devices (label) VALUES ('kiosk') RETURNING id;
                  id
--------------------------------------
 c067de26-75e3-4f0a-8ee7-4922c7b5fcb6

Use them when ids must be created before reaching the database (offline clients, merging data from several databases), or must not be guessable in URLs. The costs: 16 bytes instead of 8, harder to read, and random version-4 UUIDs land in random places of the primary key's B+ tree (16i), which spreads writes over the whole index. Time-ordered UUIDs (version 7, generated by uuidv7() from PostgreSQL 18) avoid that.

Generating ids in the application

Before identity columns were common, and in databases without sequences, the application generated ids itself. Two patterns are still worth knowing.

A key table (IdBroker)

One table holds the next free id for each table, and the application takes ids from it. A class that hides this is often called an IdBroker.

CREATE TABLE id_broker (table_name text PRIMARY KEY, next_id bigint NOT NULL);
INSERT INTO id_broker VALUES ('restaurants', 1);

UPDATE id_broker SET next_id = next_id + 1
WHERE table_name = 'restaurants'
RETURNING next_id - 1 AS id;
 id
----
  1

The second call returns 2. The UPDATE ... RETURNING is a single statement, and it locks the row until the transaction ends, so two clients can never get the same id. The version that reads the value with a SELECT and then writes next_id + 1 with a second statement has the check-then-act race: two clients read 7 and both use it.

The row lock is also the weakness: every insert into restaurants in the whole system waits for the same row. The key table should be updated in its own short transaction, not inside the business transaction.

final class IdBroker {
    private final DataSource ds;
    IdBroker(DataSource ds) { this.ds = ds; }

    long next(String table) {
        String sql = "UPDATE id_broker SET next_id = next_id + 1 WHERE table_name = ? RETURNING next_id - 1";
        try (Connection c = ds.getConnection();               // autocommit: its own transaction
             PreparedStatement ps = c.prepareStatement(sql)) {
            ps.setString(1, table);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) throw new PersistenceException("no id_broker row for " + table);
                return rs.getLong(1);
            }
        } catch (SQLException e) {
            throw new PersistenceException("cannot generate id for " + table, e);
        }
    }
}

Hi-lo

Hi-lo reduces the trips to the key table. The application takes one "high" value, say 7, and then creates ids 700 to 799 in memory (hi * 100 + lo) before it asks again. One round trip gives 100 ids. A sequence with INCREMENT 50, as above, is used the same way: the application calls nextval once and owns the 50 values after it. ORMs use this to insert many rows without asking the database for each id (JPA and Hibernate).

The cost is larger gaps: if the application restarts, the unused part of its block is lost.

Which to use

Strategy Use it when
Identity column the default for a single database
Sequence with an increment an ORM inserts in batches (hi-lo style)
UUID (v7 if possible) ids are created outside the database, or must not be guessable
Key table the database has no sequences

Reading the generated id in Java

After an insert, the application needs the new id: to return it, and to use it as a foreign key in the next insert (a booking needs its customer's id). With JDBC, ask the driver to return the generated column, then read it from getGeneratedKeys():

String sql = "INSERT INTO customers (email, name) VALUES (?, ?)";
try (PreparedStatement ps = connection.prepareStatement(sql, new String[] {"id"})) {
    ps.setString(1, "fay@example.com");
    ps.setString(2, "Fay");
    ps.executeUpdate();
    try (ResultSet keys = ps.getGeneratedKeys()) {
        keys.next();
        customer.setId(keys.getLong(1));
    }
}

Passing the column name (new String[] {"id"}) rather than Statement.RETURN_GENERATED_KEYS makes the PostgreSQL driver return only that column instead of the whole row. Setting the id back on the object right after the insert is the rule from the DAO pattern (data access patterns): once the method returns, the object is in step with its row.

Common mistakes

  • No natural key constraint. A surrogate id with no UNIQUE on email lets the same customer be inserted twice; the bug shows up months later as two accounts.
  • Assuming ids are consecutive or using them to count or order events by time. Use a timestamp column for time.
  • Reading max(id) + 1 to choose the next id. Two clients read the same maximum.
  • int ids for tables that may grow past 2³¹ rows (events, logs). bigint costs 4 more bytes and removes the question.
  • Exposing sequential ids in URLs when they should not be enumerable (/invoice/1041, /invoice/1042). Use a UUID for the public identifier, or check access on every request anyway.