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
| Term | Meaning |
|---|---|
| Relation / table | A set of rows with the same columns |
| Primary key | Minimal column set that uniquely identifies a row; not null |
| Candidate key | Any column set that could be the primary key |
| Foreign key | Columns that must match a key in another table (referential integrity) |
| Constraint | Rule enforced on write: NOT NULL, UNIQUE, CHECK, FOREIGN KEY |
| Schema | Named 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 = NULLisUNKNOWN, so useIS NULL/IS NOT NULL.x NOT IN (1, NULL)is neverTRUE: it isFALSEfor 1 andUNKNOWNotherwise.- Aggregates ignore
NULLs, exceptCOUNT(*).
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); -- 0count(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 EXISTSoverNOT INfor anti-joins (sql-joins).
Practice questions
- Why is
WHERE col <> 5not returning rows wherecol IS NULL? - What is the difference between a primary key and a
UNIQUE NOT NULLcolumn? - Which relational-algebra operator does
GROUP BYcorrespond to?
References
- PostgreSQL manual, Data Definition and Constraints: https://www.postgresql.org/docs/current/ddl.html