Skip to content
Engineering Bible
SQL and Databases

SQL and Databases on tables and keys

A relational database stores data in tables

  • A table has named, typed columns. Each row is one thing: one user, one order.
  • You ask for data in SQL, a language that says what you want, not how to fetch it.
  • PostgreSQL, MySQL and SQLite are common ones. The SQL in this guide runs in PostgreSQL.

Types and constraints keep bad data out

  • Every column has a type, such as bigint, text, numeric, boolean or timestamptz.
  • NOT NULL bans missing values. UNIQUE bans duplicates. CHECK takes a rule like total >= 0.
  • Store money as numeric, which is exact. Floating-point types are inexact.
  • timestamptz stores one moment in UTC and shows it in the session's time zone.

A primary key names each row

  • A primary key is unique and never null. A table can have only one.
  • PostgreSQL builds a unique index on it, so finding a row by its key is fast.
  • An identity column fills in the next number for you on every insert.
  • Make it bigint. A 4-byte integer runs out at about 2.1 billion.
CREATE TABLE users (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email text NOT NULL UNIQUE
);
CREATE TABLE orders (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id bigint NOT NULL REFERENCES users (id),
  total numeric(10,2) NOT NULL CHECK (total >= 0),
  created_at timestamptz NOT NULL DEFAULT now()
);
The two tables used on every page. REFERENCES makes orders.user_id a foreign key.

A foreign key links one table to another

  • orders.user_id holds a user's id. That is how an order points at its user.
  • The database rejects an order whose user_id matches no user.
  • Deleting a user who has orders fails by default. ON DELETE CASCADE deletes them too.
  • PostgreSQL does not index the foreign key column for you. Add that index yourself.

UUIDs suit ids made in many places

  • A UUID is a 128-bit id. Any server or client can make one without asking the database.
  • Version 4 is fully random. Version 7 carries a millisecond timestamp, so ids sort by time.
  • PostgreSQL 18 and later make them with uuidv7() and uuidv4().

NULL means unknown, not empty

  • NULL = NULL is not true. It is unknown. Test with IS NULL instead.
  • WHERE keeps a row only when its condition is true, so unknown rows drop out.
  • A UNIQUE column still accepts many NULLs by default.
SQL and Databases in seven pages1 / 7