Tables, rows and keys
A table looks like a spreadsheet, but it’s much stricter. Each column has a name and a type, and the database refuses values that don’t fit. Each row is one thing: one customer, one product, one order.
Every table needs a way to point at exactly one row. That’s the primary keyPrimary keyThe column (or columns) that uniquely identifies each row of a table; never empty, never repeated.Open in glossary →: a column whose value is unique and never empty. Think of a student ID card. Two students can share a name, but never an ID. Most tables use a number that the database generates for you.
The types you’ll use most:
| Type | Holds | Example |
|---|---|---|
integer, bigint | whole numbers | ids, quantities |
text, varchar(100) | strings | names, emails |
numeric(10, 2) | exact decimals | prices, money |
boolean | true or false | is_active |
date, timestamptz | a day, a moment in time | birthday, created_at |
A few rules you can attach to a column, called constraints:
NOT NULL: the column must always have a value.UNIQUE: no two rows may have the same value.DEFAULT: the value to use when an insert doesn’t give one.PRIMARY KEY: unique and not null, the row’s identity.
A table is a set of rows with a fixed, typed schema; the database enforces types and constraints on every write, which is the main thing an app gets over a file or a key-value store. Choices that matter in interviews and in production:
- Keys. A surrogate key (a generated
bigintor UUID) is the default; a natural key (email, ISBN, country code) is fine only when it truly never changes. Put aUNIQUEconstraint on natural identifiers anyway. UseGENERATED ALWAYS AS IDENTITY(SQL standard, PostgreSQL 10+) instead of the olderserial; MySQL usesAUTO_INCREMENT, SQLite’sINTEGER PRIMARY KEYis the rowid. - Money.
numeric(p, s)or integer cents. Neverreal/double precision: binary floats can’t represent 0.10 exactly. - Time.
timestamptzstores an instant (normalized to UTC) and converts on display;timestampwithout a zone stores whatever wall-clock value you give it, which breaks when servers or users are in different zones. - Strings. In PostgreSQL
textandvarchar(n)perform the same;varchar(n)only adds a length check. Case-insensitive uniqueness needs a unique index onlower(email)or thecitexttype. - Constraints are concurrency-safe. Checking “does this email exist?” in app code and then inserting races under load; a
UNIQUEconstraint can’t.
Predict the output
The email column is UNIQUE. Two inserts run one after the other with the same email. What happens?
INSERT INTO customers (email, name) VALUES ('ana@example.com', 'Ana');
INSERT INTO customers (email, name) VALUES ('ana@example.com', 'Ana Petrović');The database checks the constraint on every write and rejects the second row with an error like 'duplicate key value violates unique constraint customers_email_key'. Nothing is replaced silently. If you want insert-or-update, you have to ask for it (ON CONFLICT in PostgreSQL, covered in the SQL basics lesson).
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE,
name text NOT NULL,
country char(2), -- may be empty (NULL)
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
price numeric(10, 2) NOT NULL CHECK (price >= 0),
stock integer NOT NULL DEFAULT 0 CHECK (stock >= 0),
is_active boolean NOT NULL DEFAULT true
);The price that doesn’t add up
Tap the line with the bug.
CREATE TABLE cart_items (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
cart_id bigint NOT NULL,
price real NOT NULL,
quantity integer NOT NULL
);
SELECT sum(price * quantity) FROM cart_items WHERE cart_id = 7;Hint: Look at the types table above. Which type is meant for money?
real is a binary floating-point number, like Float in Swift or float in Kotlin and Java. It can’t store 0.10 exactly, only something very close to it. Add up enough prices and the total becomes 59.989998 instead of 59.99, the invoice disagrees with the payment provider, and the accountant opens a ticket.
Store money in a type that’s exact:
price numeric(10, 2) NOT NULL -- up to 99,999,999.99, exact
-- or
price_cents bigint NOT NULL -- 5999 means 59.99The same rule holds in app code: use Decimal in Swift and BigDecimal in Kotlin and Java, or whole cents.
Deep diveChoosing a primary key: bigint, UUIDv4 or UUIDv7Interview favorite
bigint identity: 8 bytes, new values always go to the right edge of the index, so inserts are cheap and pages stay full. Downsides: ids are guessable (/orders/1001 invites trying 1002, an IDORIDOR (Insecure Direct Object Reference)A security bug where the server returns or changes an object just because the client knows its id, without checking that the caller owns it.Open in glossary → risk if authorization is weak), they leak volume, and they need the database to generate them, which complicates merging data from offline clients or several databases.
UUIDv4: 16 bytes, random, generated anywhere (a phone can create the id offline). Randomness is the problem: each insert lands on a random page of the B-tree index, so a big table touches cold pages, splits them and bloats the index and the write-ahead log.
UUIDv7: 16 bytes, the first 48 bits are a millisecond timestamp, so new ids are roughly increasing like a sequence while still being generated anywhere. PostgreSQL 18 has uuidv7(); elsewhere you generate them in the app. It reveals the creation time, which is usually fine.
A common answer: bigint internally, plus a separate random public id (or UUIDv7) for URLs and APIs. Whatever you choose, never reuse ids and never change a primary key value, because other tables point at it.
- Surrogate
bigint GENERATED ALWAYS AS IDENTITY(or UUIDv7) as the primary key; natural identifiers get their ownUNIQUE. - Money:
numericor integer cents, never floats. Time:timestamptz. PostgreSQLtext=varchar(n)in speed. - Constraints (
NOT NULL,UNIQUE,CHECK) are enforced on every write and are race-free; app-side checks aren’t. - UUIDv4 keys scatter inserts across the index; UUIDv7 and sequences append.
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
price numeric(10, 2) CHECK (price >= 0),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX customers_email_lower ON customers (lower(email));Check this part
What makes a column a good primary key?
Which type should a price column use?
Why does app code that checks "email exists?" before inserting still allow duplicates?
Why are random UUIDv4 primary keys slow to insert into a large table?