Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 10 / Topic 2 of 9

CREATE TABLE, done properly

The full professional form, building the library for real (in public now — the lesson's running build):

CREATE TABLE authors (
  author_id  integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name       text NOT NULL
);
CREATE TABLE books (
  book_id    integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  title      text NOT NULL,
  isbn       text UNIQUE,
  added_on   date NOT NULL DEFAULT current_date
);
CREATE TABLE
CREATE TABLE

The piece worth dwelling on: GENERATED ALWAYS AS IDENTITY — the modern surrogate key. The database assigns ids from an internal sequence, and ALWAYS means it rejects you writing one by hand:

INSERT INTO books (book_id, title) VALUES (999, 'Sneaky Manual Id');
ERROR:  cannot insert a non-DEFAULT value into column "book_id"
DETAIL:  Column "book_id" is an identity column defined as GENERATED ALWAYS.
HINT:  Use OVERRIDING SYSTEM VALUE to override.

That error is a feature — id collisions can't even be attempted (OVERRIDING SYSTEM VALUE exists for deliberate loads like restoring a backup; GENERATED BY DEFAULT accepts manual values routinely, inviting exactly the collisions ALWAYS prevents). Older code uses serial — it works, but it's a macro from before identity columns existed (less standard, messier permissions, allows silent manual ids). Write identity in new code; recognise serial in old.

🧪 Quick quiz — answer from memory, then check.

  1. You insert an explicit value into a GENERATED ALWAYS AS IDENTITY column. What happens?
  2. Identity vs serial — which, and why?
Show the answers
  1. An error, unless you write OVERRIDING SYSTEM VALUE — ALWAYS protects the sequence from manual collisions.
  2. Identity: SQL-standard, rejects accidental manual ids, cleaner ownership of its sequence. serial is the legacy spelling.

Done here? The practice set for Part 10 — 6 exercises with solutions — is on the part page.

Search the guide