Sub topic 4
Tables, Rows, Columns, and the Schema
This chapter assumes you know what a relational database is at a high level, and that you can read short SQL statements. You should also be comfortable with spreadsheets. By the end you will be able to read a table definition, say what each part means, and explain what the schema is. You will also see how a schema changes over time.
Tables as the unit of storage
A relational database stores all data in tables. A table holds one kind of thing, such as customers, orders, or products. If you can describe a thing with the same set of facts every time, it probably deserves its own table.
A table has two dimensions:
- Columns are the named facts you record about every item. A
customerstable might havecustomer_id,name, andemail. - Rows are the individual items. Each row holds one customer, with one value for each column.
The following table maps the terms used in different contexts.
| Everyday term | Formal relational term | SQL term |
|---|---|---|
| Sheet or list | Relation | Table |
| Entry or record | Tuple | Row |
| Field or heading | Attribute | Column |
The SQL words are the ones you will see in documentation and error messages, so this tutorial uses them. The formal terms matter because they explain the rules. A relation is a set of tuples, and that has consequences covered below.
Differences from a spreadsheet
A table looks like a spreadsheet, but the rules are stricter. The strictness is what lets the database protect your data.
- Each column has one type. A column declared as a date holds only dates. A spreadsheet cell can hold anything.
- Every row has the same columns. You cannot add a column to one row alone. A column that does not apply to a row holds
NULL(a marker for a missing value, covered in a later chapter). - Row order is not guaranteed. Rows have no position. If you run
SELECTwithoutORDER BY, the database may return rows in any order, and that order can change between runs. Never depend on insertion order. - Cells hold single values. A cell holds one value, not a list. Storing
'red, green, blue'in one cell defeats the database's ability to search and constrain it. Multiple values belong in rows of a related table. - Rows are addressed by value, not by position. You do not ask for "row 7". You ask for the rows where a column has a given value.
Column order is also mostly cosmetic. SQL lets you name columns explicitly, and you should, because that keeps your statements correct if the column order ever changes.
What the schema is
The schema is the definition of the structure: which tables exist, which columns each has, each column's type, and the constraints that apply. The data is the rows. The schema is the shape the rows must fit.
Here is a schema for two tables, using SQL's CREATE TABLE statement.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
order_date DATE NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0)
);Reading the first table line by line:
CREATE TABLE customersnames the table.- Each line inside the parentheses defines one column: a name, a type, and optional constraints.
customer_id INTEGER PRIMARY KEYsays each row is identified by a whole number that cannot repeat.name VARCHAR(100) NOT NULLsays the name is text of up to 100 characters, and it must be present.email ... UNIQUEsays no two customers can share an email address.
The orders table adds a foreign key (REFERENCES customers) and a CHECK rule. Later chapters cover those in detail. For now, notice that the schema is a contract. The database refuses any row that breaks it.
Two meanings of "schema"
The word has two common uses, and mixing them up causes confusion.
- The general meaning is the overall structure of a database: all its tables, columns, and rules. This is the meaning used in this chapter.
- The namespace meaning is a named container for tables inside one database. PostgreSQL has a default schema called
public, and a database can hold several schemas, such assales.ordersandsupport.orders. MySQL treats "schema" and "database" as synonyms. SQLite has no schemas in this sense.
When someone says "which schema is that table in?", they mean the namespace. When they say "the schema changed", they usually mean the structure.
Inserting rows
A new table is empty. It has structure but no rows. The INSERT statement adds rows.
INSERT INTO customers (customer_id, name, email)
VALUES (1, 'Ada Lovelace', '[email protected]');
INSERT INTO customers (customer_id, name, email)
VALUES (2, 'Grace Hopper', '[email protected]');
SELECT name, email
FROM customers
WHERE customer_id = 1;The first two statements each add one row. The SELECT returns only the row where customer_id is 1. Naming the columns after the table name, as (customer_id, name, email) does, ties each value to a column by name rather than by position.
How the schema rejects bad rows
Because the schema is declared up front, the database checks every write against it. Each of the following attempts fails against the tables above:
- Inserting a customer with no
namefails, because ofNOT NULL. - Inserting a second customer with
[email protected]fails, because ofUNIQUE. - Inserting a customer with
customer_id1 again fails, because of the primary key. - Inserting an order with a
total_amountof -5 fails, because of theCHECKrule. - Inserting an order for a
customer_idthat does not exist fails, because of the foreign key. - Inserting text such as
'tomorrow'into aDATEcolumn fails, because of the type.
The exact error messages differ between systems, but the behavior is the same. A failed statement changes nothing, so a rejected insert does not leave a half-written row.
Inspecting a schema
You rarely have to guess at a schema, because the database stores it and lets you query it. The stored description is called the catalog or system tables. PostgreSQL and MySQL expose a standard view called information_schema.
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'customers'
ORDER BY ordinal_position;This lists each column of customers with its type and whether it allows NULL. SQLite does not provide information_schema. Use PRAGMA table_info(customers); there instead. Command-line clients also have shortcuts, such as \d customers in psql and DESCRIBE customers; in MySQL.
Changing a schema over time
Requirements change, so schemas change. The ALTER TABLE statement modifies an existing table without losing its rows.
ALTER TABLE customers ADD COLUMN phone VARCHAR(30);
SELECT customer_id, name, phone
FROM customers;The existing rows gain the new column, and each gets NULL in it, because no value was supplied. If you declared the new column NOT NULL with no default, many systems would reject the change on a table that already has rows. You would add a DEFAULT value or fill the data in stages.
Some changes are cheap and some are not. Adding a nullable column is usually quick. Changing a column's type or adding a constraint may require the database to scan or rewrite every row, which can lock a large table for a while. Teams usually keep schema changes in numbered migration scripts, stored in version control and applied in order. That way every environment, from a laptop to production, ends up with the same schema.
Common mistakes
- Treating row order as meaningful. Add
ORDER BYwhenever order matters. - Cramming a list into one column. Use a related table with one row per value.
- Skipping
NOT NULL. Columns are nullable unless you say otherwise, so missing data creeps in. Mark required columns explicitly. - Using names that need quoting. A column called
orderorusercollides with SQL keywords. Prefer names such asorder_date. - Making one wide table for everything. If rows repeat the same customer details, split the data into related tables. A later chapter on normalization explains why.
Summary
A table holds one kind of thing. Its columns define the facts recorded about each item, and its rows are the items. The schema is the declared structure of all tables, with types and constraints, and the database enforces it on every write. You can query the schema through the catalog and evolve it with ALTER TABLE, ideally through versioned migrations.
Exercise
A teammate runs INSERT INTO customers VALUES (3, 'Alan Turing', '[email protected]') on a table that later gets a new column. Why is this risky, and what is the safer form?
Show answer
The statement lists no column names, so it depends on the current number and order of columns. After a column such as phone is added, the value count no longer matches and the statement fails, or values could land in the wrong columns if the order changed. The safer form names the columns: INSERT INTO customers (customer_id, name, email) VALUES (3, 'Alan Turing', '[email protected]'). The new column then receives NULL or its default.
Exercise
You need to store several phone numbers for each customer. Why is a single phone column holding '555-0100, 555-0101' a poor design, and what would you do instead?
Show answer
A cell should hold one value. A comma-separated string cannot be typed, constrained, or searched reliably, and you cannot enforce uniqueness per number. Create a separate customerphones table with a customerid foreign key and one row per number. Each customer then has as many phone rows as needed.