Lesson 15: Databases: Tables, Keys and Queries
A server that forgets everything when it restarts is not much use, so real applications store their data in a database, a program designed to keep information safe, organised and searchable. The most common kind is a relational database, which stores data in tables, like spreadsheets with strict rules, and lets you ask questions in a language called SQL, Structured Query Language. This lesson introduces tables, the keys that link them, and the four basic queries that read, create, change and delete data, using a small library example you can follow along with, and it shows how a server talks to a database to answer API requests.
Tables, rows and columns
A table holds one kind of thing, such as books, and each row is one book, while each column is one fact about it, such as its title, its author and the year it was published. Every column has a type, such as text or a number, and the database refuses values that do not fit, which keeps the data clean in a way a spreadsheet does not. Each row also has a primary key, a column, usually called id, whose value is unique for every row, so the database can always tell two books apart, even if they share a title. When you design a table, choose the columns before you add any data, keep each column to one fact, and do not store the same fact in two places, because the moment two copies disagree, nobody knows which is right.
Keys and relationships
Tables rarely stand alone. A library has books and members and loans, and a loan needs to say which book and which member it belongs to, which it does with foreign keys: columns that hold the id of a row in another table. A loan row with book_id 3 and member_id 7 means member 7 borrowed book 3, and the database can use those keys to join the tables, pulling the book's title and the member's name into one answer. There are three kinds of relationship: one-to-many, such as one member having many loans; many-to-many, such as books having many authors and authors having many books, which needs a linking table in between; and one-to-one, which is rare and usually means the tables should be one. Sketching these relationships on paper before writing any SQL is the most valuable hour in a database project.
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER
);
SELECT title, author FROM books WHERE year >= 2000;
INSERT INTO books (title, author, year)
VALUES ('The Midnight Library', 'Matt Haig', 2020);
UPDATE books SET year = 2021 WHERE id = 1;
DELETE FROM books WHERE id = 1;
The four basic queries
Almost everything a database does is built from four operations, often called CRUD: Create, Read, Update and Delete. SELECT reads rows, and you choose the columns, the table, and a WHERE clause to filter, as in SELECT title, author FROM books WHERE year >= 2000;, which returns the title and author of books published since 2000. INSERT adds a row, UPDATE changes rows that match a condition, and DELETE removes them, and the condition matters enormously: UPDATE books SET year = 2021 without a WHERE would change every book in the table, which is the kind of mistake that ends careers, so always write the WHERE first and test it with a SELECT before running the change. Most database tools let you practise safely, and SQLite, a small database that lives in a single file, is a good place to start because it needs no server and no setup.
From database to API
In a real application, the API and the database work as a team: a request arrives at a route, the route asks the database a question, and the answer is sent back as JSON. For example, GET /api/courses/french might run SELECT * FROM courses WHERE id = 'french', and the row that comes back becomes the JSON response. The database does the hard work of searching, sorting and filtering, and the server's job is to ask the right question, check the answer, and present it safely. One safety rule matters above all: never build a query by pasting visitor input directly into the SQL text, because a visitor who types SQL of their own can read or destroy your data, an attack called SQL injection, which the cybersecurity course covers in detail. Instead, use parameterised queries, where the database treats the input as a value and never as code, and the whole class of attack disappears.
Key Terms
- Database
- A program that stores information safely, organised and searchable, such as a list of books and loans.
- Table
- A set of rows and columns holding one kind of thing, such as books.
- Primary key
- A column, usually id, whose value is unique for every row, so each row can be identified.
- Foreign key
- A column holding the id of a row in another table, linking the two tables together.
- SQL
- Structured Query Language, the language used to ask a database questions and change its data.
- CRUD
- Create, Read, Update, Delete, the four basic operations on data.
- Parameterised query
- A query where visitor input is passed as a value, never pasted into the SQL text, which prevents SQL injection.
Discussion Questions
- Why is it a problem to store the same fact in two places? What happens when the copies disagree?
- An UPDATE without a WHERE clause changes every row in the table. How would you protect yourself from that mistake?
- Why should a server never paste visitor input directly into an SQL query?
Practice Questions
- What is a primary key, and why does every table need one?
- What does SELECT title FROM books WHERE year >= 2000 do?
- How does a foreign key link two tables?
- What do the letters in CRUD stand for?
- What is a parameterised query, and why does it matter?
Show answers
- It is a column whose value is unique for every row, usually id. It lets the database tell rows apart, even when two rows share a title or a name.
- It returns the titles of books published in or after 2000. SELECT chooses the columns, FROM chooses the table, and WHERE filters the rows.
- It holds the id of a row in another table. A loan with book_id 3 refers to the book whose id is 3, so the database can join them.
- Create, Read, Update, Delete. In SQL they are INSERT, SELECT, UPDATE and DELETE.
- It passes visitor input as a value, never as part of the SQL text. That stops SQL injection, where typed-in SQL would otherwise be run as code.