Overview

A relational database stores data as relations (tables): sets of tuples (rows) that share the same attributes (columns). SQL is the practical language over this model. The model gives you declarative queries (say what you want, the engine chooses how) and integrity rules the database enforces for you.

Why it matters

Every engine in this section (PostgreSQL, SQL Server, Oracle) is relational, and even ClickHouse speaks SQL. Schema design, indexing and query tuning all build on these ideas.

Core concepts

TermMeaning
Relation / tableA set of rows with the same columns
Primary keyMinimal column set that uniquely identifies a row; not null
Candidate keyAny column set that could be the primary key
Foreign keyColumns that must match a key in another table (referential integrity)
ConstraintRule enforced on write: NOT NULL, UNIQUE, CHECK, FOREIGN KEY
SchemaNamed collection of tables, views and other objects

Relational algebra is the theory underneath: selection (WHERE), projection (SELECT list), join, union, difference, and aggregation. The optimizer rewrites your query into an equivalent algebra tree and picks an execution plan (see query-planning).

NULL and three-valued logic

NULL means unknown, not zero or empty. Comparisons with NULL yield UNKNOWN, and WHERE keeps only rows where the predicate is TRUE.

  • NULL = NULL is UNKNOWN, so use IS NULL / IS NOT NULL.
  • x NOT IN (1, NULL) is never TRUE: it is FALSE for 1 and UNKNOWN otherwise.
  • Aggregates ignore NULLs, except COUNT(*).

Worked example

CREATE TABLE customers (
  id      int PRIMARY KEY,
  name    text NOT NULL,
  country text NOT NULL
);
CREATE TABLE orders (
  id          int PRIMARY KEY,
  customer_id int REFERENCES customers(id),
  ordered_at  date NOT NULL,
  amount      numeric(10,2) NOT NULL CHECK (amount >= 0),
  status      text NOT NULL
);

On PostgreSQL 17, with a table of five employees where one has manager_id IS NULL:

SELECT count(*), count(manager_id) FROM employees;   -- 5 | 4
SELECT count(*) FROM employees WHERE manager_id NOT IN (1, NULL);   -- 0

count(manager_id) skips the NULL, and the NOT IN list containing NULL returns no rows at all.

Pitfalls and production notes

  • Put constraints in the database, not only in application code: several services and ad-hoc scripts write to the same tables.
  • A foreign key does not create an index on the referencing column in PostgreSQL, SQL Server or Oracle. Add one yourself, otherwise joins and parent deletes scan the child table (see indexing-theory).
  • Prefer NOT EXISTS over NOT IN for anti-joins (sql-joins).

Practice questions

  1. Why is WHERE col <> 5 not returning rows where col IS NULL?
  2. What is the difference between a primary key and a UNIQUE NOT NULL column?
  3. Which relational-algebra operator does GROUP BY correspond to?

References

sql-joins · normalization · transactions-acid · Databases