How relational databases work

Topic 2 of 4 in Getting started12 min readBeginnerFree course

Overview

Before writing more SQL, it’s worth understanding what you’re querying. A relational database stores information in tables that are linked to each other by keys. The idea was published by Edgar F. Codd at IBM in 1970, and it has outlived almost every other technology from that era because it’s simple, flexible and mathematically sound.

In this lesson you’ll learn the vocabulary — table, row, column, data type, NULL, primary key, foreign key, relationship, schema — by exploring the Bean & Leaf database. Every later lesson builds on these ideas.

Tables, rows and columns

Anatomy of a table, using products. The column names across the top are id, name, category_id, price and stock. Each row is one product, for example 2, Colombian Supremo, category 1, price 12.00, stock 55. The id column is the primary key: a unique id for each row. The category_id column is a foreign key pointing to categories.id; for the Gift Card row it is NULL, because the gift card has no category. Each column has a name and a data type, and a row holds a value or NULL in every column. Rows have no built-in order: you ask for one with ORDER BY.

A table holds one kind of thing. Bean & Leaf has six:

Table One row is…
categories a product category (Coffee, Tea, …)
products something the shop sells
customers a person who has signed up
orders one purchase by a customer
order_items one product line within an order
employees a member of staff

Each row (also called a record) is one item: one product, one customer, one order. Each column (also called a field or attribute) is one fact about that item, and every row has the same columns. Here’s the smallest table in the shop:

SQL
SELECT * FROM categories;
Text
 id |    name     
----+-------------
  1 | Coffee
  2 | Tea
  3 | Equipment
  4 | Accessories
(4 rows)

SELECT * means “all columns”. Four categories, two columns each. Notice that Accessories exists even though — as you’ll discover later — no product belongs to it yet.

Data types

Every column has a data type, fixed when the table is created. It decides what values the column can hold and how they behave:

  • integer — whole numbers such as ids, quantities and stock levels.
  • numeric(10,2) — exact decimals with two places, perfect for money: 14.50, not 14.499999….
  • text — any string: names, emails, cities.
  • date and timestamp — calendar dates, and dates with a time of day.

Types are a safety net. Try to put the word 'lots' into the stock column and PostgreSQL refuses. Spreadsheets will happily let you mix numbers and text in one column; databases won’t, which is one reason they stay trustworthy as they grow.

NULL: the missing value

Sometimes a value is unknown or doesn’t apply. Some customers didn’t give a phone number; the gift card doesn’t belong to any category. SQL represents this with a special marker, NULL:

SQL
SELECT id, first_name, phone FROM customers;
Text
 id | first_name |       phone       
----+------------+-------------------
  1 | Asha       | +91 98200 11223
  2 | Ben        | +44 7700 900123
  3 | Chen       | 
  4 | Dee        | +234 803 555 0101
  5 | Elena      | 
  6 | Farhan     | +91 99870 44556
  7 | Grace      | +1 206 555 0147
  8 | Hugo       | 
  9 | Isha       | +91 98111 77889
 10 | Jack       | 
(10 rows)

psql shows NULL as an empty space, so Chen, Elena, Hugo and Jack have no phone number on file. NULL is not zero and not an empty string — it means “no value”. It has its own rules in comparisons, which you’ll meet in Working with NULL.

Primary keys: identifying each row

Two customers could share a name; a product could be renamed. So every table has a column whose only job is to identify each row uniquely and permanently: the primary key. In Bean & Leaf it’s the id column of each table, numbered automatically as rows are added.

The database enforces it: two rows can never have the same primary key, and the key can never be NULL. When something elsewhere needs to refer to this product or that customer, it uses the key.

Foreign keys: linking tables

An order belongs to a customer. Rather than copying the customer’s name and email into every order, the orders table stores just the customer’s id:

SQL
SELECT id, customer_id, ordered_at, status
FROM orders
WHERE id = 1;
Text
 id | customer_id |     ordered_at      |  status   
----+-------------+---------------------+-----------
  1 |           1 | 2026-01-05 09:14:00 | delivered
(1 row)

Order 1 was placed by customer 1. Look that customer up:

SQL
SELECT id, first_name, last_name, city
FROM customers
WHERE id = 1;
Text
 id | first_name | last_name | city 
----+------------+-----------+------
  1 | Asha       | Rao       | Pune
(1 row)

The customer_id column is a foreign key: a column that holds the primary key of a row in another table. The database checks it, too — you can’t create an order for customer 999 if there is no customer 999, and you can’t delete a customer who still has orders. This guarantee is called referential integrity.

Storing each fact once and linking with keys means that when Asha moves city, you update one row and every order is automatically correct. You’ll see why this matters in Normalization.

The Bean & Leaf schema

The set of tables, columns, types and keys is called the database’s schema. Here is the whole shop on one page — a picture like this is called an entity–relationship diagram (ERD), and it’s the map you’ll come back to throughout the course:

The Bean & Leaf shop database. customers (id PK, first_name, last_name, email unique, phone, city, country, signup_date) connects one-to-many to orders (id PK, customer_id FK, ordered_at, status, shipping_fee). orders connects one-to-many to order_items (order_id FK, product_id FK, quantity, unit_price). products (id PK, name, category_id FK, price, stock) connects one-to-many to order_items, and categories (id PK, name unique) connects one-to-many to products. employees (id PK, name, title, manager_id FK, salary, hired_on) has a self-reference: employees.manager_id points to employees.id, because each employee’s manager is another employee. Lines connect a foreign key to the primary key it refers to.

Read the lines as relationships:

  • One-to-many. One customer has many orders; each order has exactly one customer. One category has many products. This is by far the most common relationship, and it’s always stored the same way: the “many” side holds a foreign key to the “one” side.
  • Many-to-many. An order contains many products, and a product appears in many orders. A single foreign key can’t express that, so a linking table sits in between: order_items, where each row says “this order contains this product, in this quantity, at this price”.
  • Self-reference. Each employee’s manager is another employee, so employees.manager_id points back into the same table. The CEO, Maya Singh, has no manager — her manager_id is NULL.

Here’s the linking table in action, showing what order 1 contained:

SQL
SELECT * FROM order_items WHERE order_id = 1;
Text
 order_id | product_id | quantity | unit_price 
----------+------------+----------+------------
        1 |          1 |        2 |      14.50
        1 |          5 |        1 |       9.50
(2 rows)

Product 1 (Ethiopian Yirgacheffe) twice at 14.50, and product 5 (Assam Breakfast) once at 9.50. Notice unit_price is stored on the order item itself: prices change, but an old order must remember what the customer actually paid.

Rows have no order

One more rule that surprises newcomers: a table is a set of rows, not a list. The database may return them in any order — usually the order they were inserted, until one day it isn’t. If order matters, you say so with ORDER BY, which you’ll learn in Sorting and limiting.

Databases, servers and clients

A few more terms you’ll hear:

  • A database management system (DBMS) is the software — PostgreSQL, MySQL, SQLite.
  • A database server is a running copy of that software. One server can hold many separate databases; ours is called shop.
  • A client is anything that connects to the server and sends SQL: the psql command line, a graphical tool, or your application.

Tip: when you meet a new database at work, spend ten minutes drawing (or finding) its ERD before writing queries. Knowing which keys connect which tables is most of the work in writing a correct join.

Exercise

Follow a foreign key by hand

Every employee row has a manager_id that points at another row in the same employees table. Find out who Nina Berg's manager's manager is, by following the keys yourself. Write three queries: first list every employee's id, name and manager_id (all rows); then select the employee whose id equals Nina's manager_id; then select the employee whose id equals *that* person's manager_id. Use the values you read from each result to write the next query. (In *Self-joins and cross joins* you'll learn to do this in one query.)

SQL
-- 1. Every employee with their manager_id
SELECT id, name, manager_id
FROM employees;

-- 2. Nina's manager (replace ___ with Nina's manager_id)
SELECT id, name, title, manager_id
FROM employees
WHERE id = ___;

-- 3. That person's manager

Summary

  • A relational database stores data in tables; each table holds one kind of thing, each row is one item and each column is one fact about it.
  • Every column has a data type, and a missing or unknown value is NULL — which is not zero and not an empty string.
  • A primary key uniquely identifies each row; a foreign key stores another row's primary key to link the two.
  • Relationships are usually one-to-many (one customer, many orders); many-to-many needs a linking table such as order_items.
  • Rows in a table have no guaranteed order — you ask for one with ORDER BY.