Search

Search papers and lessons

Database Schema

Level 2 · 10 min read

A database schema is the written plan of a database: which tables exist, which columns each holds and of what type, and which rules keep the data consistent.

On this page

TL;DR

A database schema is the plan for the data a database will hold. It names the tables, lists the columns in each table with their types, and records the rules, such as "every order must point to a real customer", that the database enforces. The data changes every day, but the schema changes rarely, so it is the fixed part that the rest of the application is built around.

Where you'll see it: any relational database, from a small app's SQLite file to a large warehouse, where the schema is written as CREATE TABLE statements and changed through migrations.

Intuition

Think of a filing cabinet. Before anyone puts a single document in it, somebody decides how many drawers there are, what each drawer is labelled, and what goes in each folder. A folder labelled "customers" should hold one card per customer, with a name and an address on it. Nobody should be able to file a card with no name. The labels and the rules are the schema. The documents are the data.

The schema does two jobs at once. It tells people where to find things, and it stops bad data getting in. If the database knows that an order must refer to a customer who exists, then a half-finished order with a made-up customer is rejected at the moment it is written, not discovered months later in a report.

It also gives the rest of the system a shared vocabulary. The code that displays orders, the code that bills customers and the reports that count sales all depend on the same column names. A change to the schema is therefore a change to everything that reads it, which is why schemas are kept stable and changed carefully.

flowchart LR
  C[(customers<br/>id, name, address)] -->|customer_id| O[(orders<br/>id, customer_id, placed_on)]
  O -->|order_id| L[(order_lines<br/>order_id, product_id, quantity)]
  P[(products<br/>id, name, price)] -->|product_id| L

The diagram shows four tables and the links between them. Each arrow is a rule: an order line must belong to an order, and it must name a product that exists.

The math

A schema is a set of relations, each with a name, a list of attributes and their domains, and a set of constraints. In the Relational Model a table is a relation: a set of rows, each row being a tuple of values, one per attribute.

Write a relation schema as R(A1,A2,…,An)R(A_1, A_2, \dots, A_n), where RR is the table name and AiA_i is the name of an attribute. Each attribute AiA_i has a domain dom(Ai)\mathrm{dom}(A_i), the set of values it may take, such as integers or strings of at most 80 characters. A row is a tuple (a1,…,an)(a_1, \dots, a_n) with each ai∈dom(Ai)a_i \in \mathrm{dom}(A_i). A table with mm rows is a set of mm such tuples.

Three kinds of constraint do most of the work.

Primary key. A set of attributes KK such that no two rows agree on all of KK. Formally, for any two distinct rows rr and ss, r[K]≠s[K]r[K] \neq s[K]. A primary key identifies a row uniquely.

Foreign key. An attribute set FF in table RR that must match a primary key KK in table SS. For every row rr in RR, either r[F]r[F] is null or there is a row ss in SS with s[K]=r[F]s[K] = r[F]. This is the referential integrity rule.

Functional dependency. A statement X→YX \to Y between attribute sets: any two rows that agree on XX must agree on YY. The idea is developed in Functional Dependency. Schema design uses these dependencies to decide how to split tables.

Normalisation is the process of choosing table splits so that every non-key attribute depends only on the key. The first three normal forms, introduced in the early 1970s, correspond to removing repeated groups, partial dependencies and transitive dependencies. The aim is that each fact is stored in one place, so that an update changes it in one place only.

Worked examples

Example
A flat table and its update problem

Suppose a single table stores orders with the customer's address repeated on every row:

order_idcustomeraddresstotal
1Ada12 High St30
2Ada12 High St45
3Ada12 High St10
4Ben7 Mill Rd22
  1. Ada appears in three rows, each with the same address. The address is stored three times.
  2. Ada moves to 4 Park Ln. An update must change all three rows. If the update touches only rows 1 and 2, the table now says Ada lives at two addresses, and the data is wrong with no error raised.
  3. The fix is to split the table. Put the customer and address in a customers table with one row for Ada, and keep only a customer_id in orders. The address is now stored once, and a move is a single update.

The interpretation: the flat table violates the rule that every non-key attribute depends on the key of its table. Its address depends on the customer, not on the order, so it belongs in a table keyed by customer.

Example
Enforcing a foreign key by hand

The schema says orders.customer_id is a foreign key to customers.id. The customers table has ids 1, 2 and 3. Now a request arrives to insert an order with customer_id = 5.

  1. Look for a row in customers with id = 5.
  2. There is none, so the value 55 is not in the set of ids {1,2,3}\{1, 2, 3\}.
  3. The database refuses the insert, and the order is not written.

A sales report run later never sees a sale attached to a customer who does not exist, so no clean-up is needed. The check costs one lookup on each insert, and a Database Index on customers.id makes that lookup fast. The interpretation: the schema moves a rule from the application code, where it can be forgotten, into the database, where every writer is checked.

Tradeoffs and failure modes

Normalised schemas keep each fact in one place and make updates safe. They also force reads to join several tables, and joins cost time. Pick the design by looking at what the system does most often.

SituationWhat goes wrongBetter choice
Heavy writes, lots of updatesA repeated fact is updated in several places and falls out of stepNormalise to third normal form, so each fact has one home
Reporting dashboards that read the same joins over and overMany joins make each query slowDenormalise a summary table, and rebuild it on a schedule
Frequent schema changes during early developmentEach change is a migration that touches live dataKeep the schema small and migrate in reversible steps
Data whose shape varies from record to recordForcing it into fixed columns leaves most cells emptyUse a schema-less store, or a column type for flexible fields, and accept weaker checks
A column that stores a list, such as tags in one stringQueries cannot use the list, and checks cannot see inside itSplit into a separate table with one row per item
Schemas that are never written downEach developer guesses the meaning of a columnKeep the schema in version-controlled migration files and document each table

The common failure is a schema that reflects the first screen of the app rather than the data's own structure. Such a schema has to be reworked when the next feature arrives.

History

Edgar F. Codd, working at IBM, described the relational model in a 1970 paper, arguing that data should be stored as tables of facts and queried by content rather than by stored paths. The paper was about data independence: the way the data is organised should not be tied to how programs read it. Codd introduced the first normal forms in the early 1970s, giving designers a method for splitting tables. The separation of a logical schema from physical storage, which is the basis of data independence, was made explicit in the mid-1970s by the ANSI/SPARC study group, which described a three-level architecture.

SQL, which turned the relational model into a working language for creating and querying schemas, was developed at IBM in the 1970s and standardised by ANSI in 1986. Its CREATE TABLE statement is still the usual way a schema is written down. The idea caught on because it gave a single, checkable description of the data that many programs could share.

Check yourself

QuestionName the two kinds of constraint that a schema uses to keep data consistent across tables, and say what each one guarantees.Show answer

A primary key guarantees that no two rows in a table agree on the key, so each row can be identified uniquely. A foreign key guarantees that a value in one table either is null or matches an existing key in another table, so references never point at nothing. Both are enforced by the database on every write.

QuestionA table stores 6 orders across 2 customers, and each row repeats the customer's 40-character address. How many characters of address are stored, and how many after splitting the address into a customers table with one row per customer?Show answer

Each order row stores the address once, so the flat table stores 6×40=2406 \times 40 = 240 characters of address. After splitting, the address is stored once per customer, so 2×40=802 \times 40 = 80 characters. The split cuts storage by two thirds here, and more importantly it means an address change is one update rather than as many as there are orders.

QuestionWhy does a schema move rules such as 'an order must have a customer' into the database rather than leaving them to the application code?Show answer

Application code can be bypassed. Another program, a script or a manual edit can write a row that the application never checks, and once the bad row is stored, every later report and program must work around it. A constraint in the schema applies to every writer at the moment of the write, so the rule holds whatever wrote the data.

QuestionA table has columns (student_id, course_id, instructor), with the rule that each course has exactly one instructor. Is (student_id, course_id) a primary key, and what problem does the instructor column cause?Show answer

Yes, a student takes a given course at most once, so (student_id, course_id) identifies a row. The instructor column depends only on course_id, which is a partial dependency on part of the key. If a course changes instructor, every row for that course must be updated. The fix is a separate courses table with course_id and instructor, leaving the enrolment table with only (student_id, course_id).

QuestionA reporting job runs the same four-table join every hour and it is slow. The data changes only a few times a day. What is a sensible change to the schema, and what does it cost?Show answer

Keep the normalised tables for writes, and add a summary table that holds the joined result, rebuilt on a schedule, perhaps hourly. Reports then read one table. The cost is that the summary is stale between rebuilds and that the rebuild uses resources. Because the data changes only a few times a day, staleness of up to an hour is usually acceptable, and the trade is worth it.

Sources