Skip to content

Lesson 1 of 29Querying basics

Tables, Rows and the Relational Model

What a relational database really is, where Postgres, MySQL and SQLite fit at work, and the shop dataset you will query all course.

15 min read0/4 questions

On your first week in a new job, a product manager asks a simple question: "How many customers in London placed an order last month?" The answer is not in the code. It lives in a database, spread across several tables that point at each other, and you need to know how those tables fit together before you can ask anything sensible. Every backend, every analytics dashboard and most SQL interview screens rest on the same small idea, the relational model. You already know enough Python from the Python course to read every runnable block here, so the only new language is SQL. This lesson gives you that model, shows you where the main databases fit at work, and introduces the shop dataset you will query for the rest of the course.

What a relational database is

A relational database stores data in tables. The theory calls a table a relation, which is where the name comes from. Each table holds one kind of thing: customers, orders, products.

  • A row is one instance of that thing: one customer.
  • A column is one fact about every row: the customer's email. Each column has a type and, optionally, rules.
  • A primary key is the column (or set of columns) that identifies each row uniquely. In the shop dataset, customers.id is the primary key of customers.
  • A foreign key is a column whose values must match a primary key in another table. orders.customer_id is a foreign key to customers.id. It is how one table points at another.

Two properties of tables surprise people coming from spreadsheets or Python lists. First, rows have no built-in order. The database is free to return them in any order unless you ask for one with ORDER BY, and the order it happens to use today can change after an upgrade or a new index. Second, a well-designed table has no duplicate rows, because the primary key makes every row distinct.

Relations are linked through values, not through pointers or nesting. An order does not "contain" a customer. It stores the customer's id, and you combine the two tables at query time with a join. That is the core trade: data is stored once, in one place, and you pay a small cost to bring it back together when you read it. Updating a customer's email means changing one row, not hunting through every order that mentions them.

SQL is declarative

SQL (Structured Query Language, pronounced "S-Q-L" or "sequel", both are fine) is how you talk to a relational database. It is declarative: you describe the result you want, and the database decides how to compute it.

Compare that with Python, where you write the algorithm yourself:

london = []
for c in customers:
    if c["city"] == "London":
        london.append((c["id"], c["name"]))

The SQL version says what, not how:

SELECT id, name FROM customers WHERE city = 'London';

A part of the database called the query planner (or optimiser) reads that statement and picks a strategy. On a small table it reads every row. If there is an index on city, it may jump straight to the London rows. For a join of three tables, it chooses which table to read first and which join algorithm to use. The same query can run a thousand times faster after someone adds the right index, without a single change to your SQL.

This is why SQL has lasted for fifty years. Your query stays the same while data grows from a hundred rows to a hundred million. It is also why a slow query is usually fixed by changing the indexes or the data model rather than the code. Later lessons on indexes and EXPLAIN show you how to read the plan the database picked.

The database landscape at work

You will meet a handful of relational databases in your career. They all speak SQL, with different dialects at the edges.

DatabaseModelWhere you meet it
PostgreSQLClient/server, open sourceThe default for new backends and SaaS products. Every cloud offers it managed.
MySQL / MariaDBClient/server, open sourceOlder web stacks, WordPress, many large consumer sites. MariaDB is a community fork.
SQLiteEmbedded library, one fileInside every phone, every browser, desktop apps, tests and local scripts.
SQL ServerClient/server, commercialMicrosoft and .NET shops, banks, large enterprises.
OracleClient/server, commercialLarge enterprises, finance, government, legacy ERP systems.

This course teaches PostgreSQL syntax, because it is the database you are most likely to use on a new team and it follows the SQL standard closely. The runnable examples execute on SQLite, because SQLite runs inside your browser with no server. Where the two differ, you will see a short Dialect note.

Match the pairs0/4 matched

Match each project to the database that fits it best.

Choose an item, then its match on the other side.

Client/server versus embedded

The biggest difference between Postgres and SQLite is not the SQL. It is where the database runs.

Postgres is a server. It runs as its own set of processes, usually on another machine. Your application opens a network connection, sends SQL as text, and gets rows back. Many application servers can connect at once, and Postgres coordinates them: it handles concurrent writers, user accounts and permissions, replication to standby servers and backups. That power costs you operations work: something has to run, patch and monitor that server, which is why most teams pay a cloud provider to do it.

SQLite is a library. There is no server process. The database is a single file, and the SQLite code runs inside your own program and reads that file directly. There is nothing to install or configure, and a query is a function call, not a network round trip, so it is extremely fast for one process. The limit is concurrency: many readers can work at once, but only one writer at a time can change the file. That is perfect for a phone app, a test suite or a desktop tool, and a poor fit for fifty web servers writing orders at the same time.

The course dataset

Every lesson uses the same small shop, so you can build intuition instead of learning a new schema each time. It has seven tables.

The shop dataset and its foreign keys
events: 18 rowsevents18 rowscategories: parent_id: selfcategoriesparent_id: selfproducts: 10 rowsproducts10 rowscustomers: 8 rowscustomers8 rowsorders: 10 rowsorders10 rowsorder_items: 17 rowsorder_items17 rowsemployees: manager_id: selfemployeesmanager_id: selfcustomer_idorder_idproduct_idcategory_iduser_id

Each order stores a customer_id that must match a customers.id. One customer has many orders; each order has exactly one customer. The arrow points from the table holding the foreign key to the table it references.

1/5

Here is the schema. Notice the conventions, because they repeat in real codebases: every table has an id primary key, foreign keys are named <table>_id, and money is stored as integer cents so no rounding ever creeps in.

shop schema
CREATE TABLE customers  (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE,
                         city TEXT, created_at TEXT NOT NULL);
CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT NOT NULL,
                         parent_id INTEGER REFERENCES categories(id));
CREATE TABLE products   (id INTEGER PRIMARY KEY, name TEXT NOT NULL,
                         category_id INTEGER REFERENCES categories(id),
                         price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
                         stock INTEGER NOT NULL DEFAULT 0);
CREATE TABLE orders     (id INTEGER PRIMARY KEY,
                         customer_id INTEGER NOT NULL REFERENCES customers(id),
                         status TEXT NOT NULL CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled')),
                         created_at TEXT NOT NULL);
CREATE TABLE order_items (order_id INTEGER NOT NULL REFERENCES orders(id),
                          product_id INTEGER NOT NULL REFERENCES products(id),
                          quantity INTEGER NOT NULL CHECK (quantity > 0),
                          unit_price_cents INTEGER NOT NULL,
                          PRIMARY KEY (order_id, product_id));
CREATE TABLE employees  (id INTEGER PRIMARY KEY, name TEXT NOT NULL, title TEXT NOT NULL,
                         department TEXT NOT NULL, manager_id INTEGER REFERENCES employees(id),
                         salary INTEGER NOT NULL, hired_at TEXT NOT NULL);
CREATE TABLE events     (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES customers(id),
                         kind TEXT NOT NULL, created_at TEXT NOT NULL);

Dates are stored as ISO-8601 text such as '2025-06-01 09:00' because SQLite has no date type. In Postgres you would use timestamptz and date, and the column types lesson explains why.

Get the dataset on your own machine

On this site the dataset is preloaded as a module called shopdb, so every example starts with from shopdb import connect, show. To run the examples locally, save the file below as shopdb.py next to your script. It only needs Python's standard library.

shopdb.py
import sqlite3
 
SEED = """
CREATE TABLE customers (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT UNIQUE,
  city TEXT,
  created_at TEXT NOT NULL
);
CREATE TABLE categories (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  parent_id INTEGER REFERENCES categories(id)
);
CREATE TABLE products (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  category_id INTEGER REFERENCES categories(id),
  price_cents INTEGER NOT NULL CHECK (price_cents >= 0),
  stock INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE orders (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  status TEXT NOT NULL CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled')),
  created_at TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id INTEGER NOT NULL REFERENCES orders(id),
  product_id INTEGER NOT NULL REFERENCES products(id),
  quantity INTEGER NOT NULL CHECK (quantity > 0),
  unit_price_cents INTEGER NOT NULL,
  PRIMARY KEY (order_id, product_id)
);
CREATE TABLE employees (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  title TEXT NOT NULL,
  department TEXT NOT NULL,
  manager_id INTEGER REFERENCES employees(id),
  salary INTEGER NOT NULL,
  hired_at TEXT NOT NULL
);
CREATE TABLE events (
  id INTEGER PRIMARY KEY,
  user_id INTEGER NOT NULL REFERENCES customers(id),
  kind TEXT NOT NULL,
  created_at TEXT NOT NULL
);
 
INSERT INTO customers VALUES
  (1, 'Ada Lovelace', 'ada@example.com', 'London', '2025-01-04'),
  (2, 'Grace Hopper', 'grace@example.com', 'New York', '2025-01-19'),
  (3, 'Alan Turing', 'alan@example.com', 'London', '2025-02-02'),
  (4, 'Katherine Johnson', NULL, 'Hampton', '2025-02-27'),
  (5, 'Linus Torvalds', 'linus@example.com', 'Portland', '2025-03-15'),
  (6, 'Margaret Hamilton', 'margaret@example.com', NULL, '2025-04-08'),
  (7, 'Tim Berners-Lee', 'tim@example.com', 'Geneva', '2025-05-21'),
  (8, 'Barbara Liskov', 'barbara@example.com', 'Boston', '2025-06-30');
 
INSERT INTO categories VALUES
  (1, 'Electronics', NULL),
  (2, 'Computers', 1),
  (3, 'Laptops', 2),
  (4, 'Accessories', 2),
  (5, 'Audio', 1),
  (6, 'Books', NULL);
 
INSERT INTO products VALUES
  (1, 'Laptop Pro 14', 3, 189900, 12),
  (2, 'Laptop Air 13', 3, 109900, 30),
  (3, 'USB-C Hub', 4, 4900, 150),
  (4, 'Mechanical Keyboard', 4, 12900, 45),
  (5, 'Wireless Mouse', 4, 3900, 200),
  (6, 'Noise-Cancelling Headphones', 5, 29900, 25),
  (7, 'Bluetooth Speaker', 5, 7900, 0),
  (8, 'Designing Data-Intensive Applications', 6, 4500, 60),
  (9, 'The Pragmatic Programmer', 6, 3900, 40),
  (10, 'SQL Performance Explained', 6, 3500, 15);
 
INSERT INTO orders VALUES
  (1, 1, 'shipped', '2025-02-01'),
  (2, 2, 'shipped', '2025-02-14'),
  (3, 1, 'paid', '2025-03-03'),
  (4, 3, 'cancelled', '2025-03-10'),
  (5, 5, 'shipped', '2025-04-02'),
  (6, 2, 'paid', '2025-05-11'),
  (7, 6, 'pending', '2025-06-05'),
  (8, 1, 'shipped', '2025-06-20'),
  (9, 7, 'paid', '2025-07-01'),
  (10, 5, 'pending', '2025-07-15');
 
INSERT INTO order_items VALUES
  (1, 1, 1, 189900), (1, 3, 2, 4900),
  (2, 8, 1, 4500), (2, 9, 1, 3900),
  (3, 6, 1, 29900),
  (4, 2, 1, 109900),
  (5, 4, 1, 12900), (5, 5, 2, 3900), (5, 3, 1, 4900),
  (6, 2, 1, 109900), (6, 10, 2, 3500),
  (7, 8, 3, 4500),
  (8, 5, 1, 3900), (8, 9, 1, 3900),
  (9, 6, 2, 29900), (9, 4, 1, 12900),
  (10, 1, 1, 189900);
 
INSERT INTO employees VALUES
  (1, 'Priya Shah', 'CTO', 'Engineering', NULL, 310000, '2019-03-01'),
  (2, 'Marcus Lee', 'Engineering Manager', 'Engineering', 1, 210000, '2020-06-15'),
  (3, 'Sofia Rossi', 'Engineering Manager', 'Engineering', 1, 205000, '2021-01-11'),
  (4, 'Jamal Brown', 'Senior Engineer', 'Engineering', 2, 175000, '2021-09-01'),
  (5, 'Mei Chen', 'Engineer', 'Engineering', 2, 135000, '2023-02-20'),
  (6, 'Oliver Smith', 'Engineer', 'Engineering', 3, 130000, '2023-08-07'),
  (7, 'Ana Garcia', 'Senior Engineer', 'Engineering', 3, 180000, '2022-04-18'),
  (8, 'Noah Kim', 'Head of Sales', 'Sales', NULL, 190000, '2020-02-03'),
  (9, 'Emma Wilson', 'Account Executive', 'Sales', 8, 95000, '2024-01-15');
 
INSERT INTO events VALUES
  (1, 1, 'login', '2025-06-01 09:00'),
  (2, 1, 'view_product', '2025-06-01 09:02'),
  (3, 1, 'add_to_cart', '2025-06-01 09:05'),
  (4, 1, 'checkout', '2025-06-01 09:07'),
  (5, 2, 'login', '2025-06-01 10:15'),
  (6, 2, 'view_product', '2025-06-01 10:16'),
  (7, 3, 'login', '2025-06-02 08:30'),
  (8, 3, 'view_product', '2025-06-02 08:31'),
  (9, 3, 'add_to_cart', '2025-06-02 08:40'),
  (10, 5, 'login', '2025-06-02 12:00'),
  (11, 1, 'login', '2025-06-03 09:10'),
  (12, 6, 'login', '2025-06-03 18:45'),
  (13, 6, 'view_product', '2025-06-03 18:47'),
  (14, 2, 'login', '2025-06-04 11:00'),
  (15, 2, 'add_to_cart', '2025-06-04 11:03'),
  (16, 2, 'checkout', '2025-06-04 11:06'),
  (17, 7, 'login', '2025-06-05 07:55'),
  (18, 1, 'login', '2025-06-06 09:05');
"""
 
 
def connect(path=":memory:"):
    db = sqlite3.connect(path)
    db.execute("PRAGMA foreign_keys = ON")
    db.executescript(SEED)
    return db
 
 
def show(db, sql, params=()):
    cur = db.execute(sql, params)
    cols = [d[0] for d in cur.description]
    rows = [["NULL" if v is None else str(v) for v in r] for r in cur.fetchall()]
    widths = [max(len(c), *(len(r[i]) for r in rows)) if rows else len(c) for i, c in enumerate(cols)]
    line = lambda vals: " | ".join(v.ljust(w) for v, w in zip(vals, widths)).rstrip()
    print(line(cols))
    print("-+-".join("-" * w for w in widths))
    for r in rows:
        print(line(r))
    print(f"({len(rows)} row{'s' if len(rows) != 1 else ''})")

How the runnable blocks work

Each runnable block is a short Python program that uses the sqlite3 module from the standard library. Blocks do not share state: every one builds a fresh database in memory, so you can change, delete and break things freely. Press run and edit the city:

Python
from shopdb import connect, showdb = connect()show(db, """SELECT id, name, cityFROM customersWHERE city = ?""", ("London",))
Output
Press Run (⌘ Enter) to see what happens.

connect() creates an in-memory database, turns foreign keys on and loads the seed data. show(db, sql, params) runs one query and prints an aligned table with a row count. NULL values print as NULL.

Underneath, show uses the plain sqlite3 API, which is worth knowing because it is the same shape as every Python database driver (psycopg for Postgres follows the same DB-API standard):

Python
import sqlite3from shopdb import connectdb = connect() cur = db.execute("SELECT id, name FROM products WHERE price_cents < ? ORDER BY id", (4000,))print(cur.fetchone()) # the next row, as a tupleprint(cur.fetchall()) # all remaining rows, as a list of tuples db.row_factory = sqlite3.Row # rows you can index by column namerow = db.execute("SELECT name, price_cents FROM products WHERE id = ?", (6,)).fetchone()print(row["name"], row["price_cents"] / 100) try: db.execute("SELECT 1; SELECT 2")except sqlite3.ProgrammingError as err: print("ProgrammingError:", err) db.executescript("""CREATE TABLE notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL);INSERT INTO notes (body) VALUES ('first'), ('second');""")print(db.execute("SELECT count(*) FROM notes").fetchone()[0])
Output
Press Run (⌘ Enter) to see what happens.

The rules from that block:

  • execute runs exactly one statement and returns a cursor. Two statements in one string raise an error.
  • executescript runs many statements, which is handy for setup, but it takes no parameters. Never put user input in it.
  • fetchone returns the next row or None; fetchall returns a list. On a huge result, loop over the cursor instead, so you do not load millions of rows into memory.
  • ? is a placeholder. The value travels separately from the SQL text, so the database never mistakes data for code. Postgres drivers such as psycopg use %s instead, and SQLAlchemy uses :name, but the idea is identical.

Never build SQL with f-strings or string concatenation, not even "just for a quick script". A name like O'Brien breaks the query, and a malicious value can rewrite it. You saw why in Databases with SQLAlchemy, so this course simply uses parameters everywhere.

Predict the outputPython

How many rows does the last line print?

db = connect()
db.execute("DELETE FROM events WHERE kind = 'login'")
show(db, "SELECT kind FROM events WHERE user_id = 1")
Need a nudge? Hints walk you through it.

Keys and constraints do real work

Constraints are not documentation. They are rules the database enforces on every write, from every service, forever. That matters at work, because the application code that checks an email is unique will one day be bypassed: by a second service, a migration script, a race between two requests or a teammate fixing data by hand. A constraint cannot be bypassed.

Run these writes and read each error:

Python
import sqlite3from shopdb import connect, SEEDdb = connect() attempts = [ ("unknown customer", "INSERT INTO orders (customer_id, status, created_at) VALUES (99, 'paid', '2025-08-01')"), ("bad status", "INSERT INTO orders (customer_id, status, created_at) VALUES (1, 'refunded', '2025-08-01')"), ("duplicate line", "INSERT INTO order_items VALUES (1, 1, 1, 189900)"), ("missing name", "INSERT INTO customers (email, created_at) VALUES ('x@example.com', '2025-08-01')"), ("valid order", "INSERT INTO orders (customer_id, status, created_at) VALUES (8, 'pending', '2025-08-01')"),]for label, sql in attempts: try: db.execute(sql) print(f"{label}: ok") except sqlite3.IntegrityError as err: print(f"{label}: {err}") loose = sqlite3.connect(":memory:") # no PRAGMA foreign_keys = ONloose.executescript(SEED)loose.execute("INSERT INTO orders (customer_id, status, created_at) VALUES (99, 'paid', '2025-08-01')")print("without the pragma, the order for customer 99 was accepted")
Output
Press Run (⌘ Enter) to see what happens.

The foreign key stopped an order for a customer who does not exist. The CHECK rejected a status the business does not have. The composite primary key on order_items refused a second line for the same product in the same order (you would update the quantity instead). NOT NULL refused a customer with no name. Notice that the valid order did not need an id: an INTEGER PRIMARY KEY gets the next number automatically, like GENERATED ALWAYS AS IDENTITY in Postgres.

The last three lines are a real trap. SQLite ignores foreign keys unless each connection runs PRAGMA foreign_keys = ON, so a plain connection happily stored an orphan order. Postgres always enforces them. If you ever use SQLite in production or in tests, turn the pragma on in the code that opens connections.

Quick check
Why is the primary key of order_items the pair (order_id, product_id) rather than a single column?
Need a nudge? A hint rules out a wrong answer.

Reading a schema you did not write

On a real team, the first thing you do with an unfamiliar database is look at its tables and their columns. In Postgres you use psql, the command-line client covered later in PostgreSQL for Developers:

psql commandWhat it showsSQLite equivalent
\dtAll tablesSELECT name FROM sqlite_schema WHERE type = 'table'
\d ordersColumns, types, keys, indexes of one tablePRAGMA table_info(orders)
\xExpanded output, one column per line.mode line in the sqlite3 shell
\timingHow long each query took.timer on in the sqlite3 shell

Both databases also describe themselves with SQL. Postgres exposes the standard information_schema views and its own pg_catalog; SQLite has the sqlite_schema table and pragma functions you can query like tables:

Python
from shopdb import connect, showdb = connect()show(db, "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name")show(db, 'SELECT name, type, "notnull", pk FROM pragma_table_info(?)', ("order_items",))show(db, 'SELECT "table", "from", "to" FROM pragma_foreign_key_list(?)', ("order_items",))
Output
Press Run (⌘ Enter) to see what happens.

The last query lists the foreign keys of order_items, the same arrows as in the diagram. When you join a team, sketching that diagram for the ten most important tables is one of the most useful things you can do in your first week.

How this course is laid out

  • Querying basics: SELECT, filtering, NULL, column types and changing data safely.
  • Joining and aggregating: joins, GROUP BY, subqueries, CTEs, recursion and window functions.
  • Designing schemas: modelling entities, normal forms and constraints.
  • Indexes and query performance: how indexes work, reading EXPLAIN and patterns that scale.
  • Transactions and concurrency, then Postgres in production: ACID, isolation, locks, migrations, JSON, search, pooling and replicas.
  • Beyond relational, and interviews: NoSQL families and the classic SQL interview questions.

By the end you can design, query, speed up and safely change a real Postgres database. The course closes with a wrap-up that uses every unit on one feature.

Put it in order5 steps

Order these steps from the moment your API code sends a query to Postgres until it has the rows.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
relation
The formal name for a table: a set of rows that all have the same columns.
primary key
The column or columns that uniquely identify each row. Never NULL, one per table.
foreign key
A column whose values must match a key in another table, enforced by the database on every write.
junction table
A table that links two others in a many-to-many relationship, such as order_items between orders and products.
declarative
Describing the result you want and letting the system choose how to compute it.
query planner
The part of the database that turns a SQL statement into an execution strategy.
embedded database
A database that runs as a library inside your program and stores data in a local file, like SQLite.