electronics engineering
Course handbook · Fifth year
Information Systems
Information systems: databases, SQL, data modelling, client-server applications and enterprise software.
- 8Topics
- 0Solved exercises
- 1Formula sheet
Free handbook generated from the lessons of the site and updated often, every time a lesson or an exercise changes: the latest version is always at www.electronics-engineering.com/handbook/informative-systems. Links work in the PDF too.
1Information systems and architectures
An information system is the set of data, procedures, people and technologies with which an organisation collects, stores, processes and distributes the information it needs: a company’s orders and invoices, a hospital’s medical records, a university’s exams. The automated part, the computer system, is its technical heart. In this lesson we look at the functions and types of information systems, layered architectures, the calculation of availability with the proof of the formulas for components in series and in parallel and an example, and the relation between systems and business processes.
What an information system does
Tasks are divided by level of decision:
- operational (transactional) systems record daily events: an order, a payment, an enrolment. They must be fast, reliable and consistent;
- management systems integrate the data of the departments: ERP systems (enterprise resource planning) manage accounting, purchasing, warehouse, production and staff in a single database; CRM systems manage customer relationships; SCM systems the supply chain;
- executive systems (business intelligence) analyse large amounts of historical data to support decisions, with dashboards and reports (lesson on distributed data and data warehouses).
At the centre of them all there is a database: the following lessons look at its design, its language, indexes and transaction management.
Layered architectures
A modern information system is divided into three logical tiers:
- presentation: the user interface, nowadays almost always a web or phone application;
- application logic: the organisation’s rules (how a discount is computed, when an order can be shipped), on one or more application servers;
- data: the database management system (DBMS), which guarantees persistence and integrity.
Separating the tiers makes it possible to change one without touching the others, to scale each independently by adding machines, and to protect the data, which is never directly exposed to users. Microservice architectures push the division further: many small independent applications, each with its own data, communicating over the network through documented interfaces (APIs). The cloud provides the tiers as pay-per-use services, from virtual machines to managed databases.

Availability
A system handling sales or a hospital’s emergencies must always work. Availability is the fraction of time the system works, related to the mean time between failures (MTBF) and the mean time to repair (MTTR) by
. It is often expressed as a “number of nines”: 99.9 % means about 8.8 hours of downtime a year, 99.99 % about 53 minutes.
Theorem. For components failing independently, with availabilities
:
- if the system works only when all of them work (components in series),
; - if the system works when at least one works (components in parallel, redundant),
.
Proof. Availability is the probability that the component works at any given instant. For independent events the probability that all occur is the product of the probabilities: this gives the series case. The parallel system is down only if all the components have failed, an event of probability
; availability is the complement. ∎
Example. An application server with availability 99.5 % and a database with 99.9 %, in series:
, i.e. about 52 hours of downtime a year. Doubling both tiers, as in the figure: the application tier becomes
, the data tier
, and the system
: about 14 minutes a year. A series is always worse than its weakest link; redundancy improves availability enormously, provided failures are really independent. Two servers in the same room, with the same power supply and the same faulty update, are not: that is why critical systems are spread over several data centres.
Systems and processes
An information system is not designed starting from technology, but from the organisation’s processes: the sequences of activities producing a result for a customer, internal or external (receiving an order, fulfilling it, invoicing it, collecting payment). They are described with graphical notations such as BPMN (Business Process Model and Notation), with activities, events, decisions and flows between roles. Process analysis shows where data originates, who uses it and which steps can be automated or eliminated. The experience of corporate IT projects is that failures rarely come from technology and much more often from misunderstood requirements and processes nobody rethought.
2Conceptual design
Before creating tables one must understand what is to be represented: which objects, which links, which rules. Conceptual design produces a schema independent of the system that will host it, understandable even to non-specialists. The most widely used model is the entity-relationship (E-R) model, proposed by Peter Chen in 1976. In this lesson we look at entities, attributes and identifiers, relationships and their cardinalities, generalisations, a complete example, and the rules for translating the schema into tables, with the proof of why many-to-many relationships require a table of their own.
Entities and attributes
An entity is a class of objects with independent existence and common properties: students, courses, lecturers. Each concrete object is an instance. The properties are the attributes: student number, name, date of birth. An identifier is a set of attributes that distinguishes each instance from all others: for the student, the student number. In diagrams entities are drawn as rectangles, attributes as small circles, filled if they belong to the identifier.
Relationships and cardinalities
A relationship (or association) is a link between entities: a student takes an exam for a course. Relationships too can have attributes: the mark and the date belong to the link between that student and that course, not to either one.

Cardinalities say how many times an instance takes part in the relationship, at minimum and at maximum. (0,N) for the student in the relationship with courses means that they may not have taken any exams yet and may take many; (1,1) for a car in the relationship with its owner means it has exactly one. Looking at the maxima, binary relationships are classified as one-to-one, one-to-many and many-to-many. Cardinalities are rules of the real world, and must be asked of those who know it: “can an order contain products from several suppliers?” changes the schema.
Generalisations
When some entities are special cases of another, a generalisation is used: lecturers and students are persons, with common attributes (name, tax code) inherited from the parent entity and attributes of their own (the student number for the student, the field for the lecturer). A generalisation can be total (every person is a lecturer or a student) or partial, disjoint (one cannot be both) or overlapping.
An example
The registry of a degree course. Entities: Student (student number, first name, surname, date of birth), Course (code, title, credits), Lecturer (code, first name, surname). Relationships: Exam between Student (0,N) and Course (0,N), with attributes mark and date; Teaching between Lecturer (0,N) and Course (1,1), because every course has exactly one lecturer in charge. The rules the schema does not express, such as “the mark is between 18 and 30” or “a student cannot take an exam they have already passed”, are written separately as integrity constraints.
From concept to tables
Logical design translates the E-R schema into tables of the relational model (lesson on the relational model). The main rules:
- every entity becomes a table, with its identifier as primary key;
- a one-to-many relationship does not become a table: a foreign key referring to the key of the other side is added to the table on the “many” side. Course receives the column with the code of its lecturer;
- a one-to-one relationship is translated in the same way, placing the foreign key on the side with mandatory participation;
- a many-to-many relationship becomes a table of its own, with the keys of the two entities and the attributes of the relationship: Exam(student_number, course_code, mark, date);
- generalisations are translated with a single table with a field indicating the type, or with separate tables for the child entities.
Theorem. A many-to-many relationship cannot be represented with a foreign key in one of the two entity tables without repeating data or breaking the one-value-per-cell rule.
Proof. Suppose a column with the course code is put in Student. A student linked to two courses would require two values in the same cell, forbidden in the relational model (every cell holds an atomic value), or two rows for the same student, which would repeat first name, surname and date of birth and make the student number lose its role as key. The same happens putting the column in Course, for a course with several students. Since in a many-to-many relationship both sides can have several partners, neither placement avoids the problem: a table is needed in which each row represents a single link. ∎
Conceptual design done well avoids most of the redundancy problems that normalisation (dedicated lesson) would otherwise have to correct.
3The relational model
In 1970 Edgar Codd, an IBM researcher, proposed representing data as simple tables and querying them with mathematical operations, instead of navigating among pointers as in the systems of the time. The relational model is still the basis of almost every information system. In this lesson we look at relations and keys with the proof that every relation has at least one, integrity constraints, relational algebra with selection, projection and join, the proof of the bounds on the size of a join, and the link with SQL.
Relations, tuples and attributes
A relation is a table with a name, named columns (the attributes) and rows (the tuples). Mathematically it is a set of tuples: the order of rows does not matter and no two rows are equal. Each attribute takes values in a domain (integers, dates, strings), and each cell contains a single atomic value. The relation’s schema is the name with the attributes, Student(number, first_name, surname, birth); the instance is the content at a given moment.
Keys
A superkey is a set of attributes that never takes the same value in two different tuples. A key is a minimal superkey: removing any attribute it is no longer a superkey.
Theorem. Every relation has at least one key.
Proof. The set of all attributes is a superkey: two tuples with all values equal would be the same tuple, and a relation is a set, so it has no duplicates. If this superkey is not minimal, remove an attribute that leaves it a superkey, and repeat. There are finitely many attributes, so the procedure terminates, and the set it reaches is a superkey from which nothing can be removed: a key. ∎
Among the keys one is chosen as primary key, on which null values are not allowed. An artificial code (a sequential number) is often used even when a natural key exists, because it is more stable and more compact.
Integrity constraints
The model does not accept just any data: constraints express the rules of the real world and the DBMS enforces them.
- Domain and tuple constraints: the mark is between 18 and 30, the end date does not precede the start date.
- Key constraint: no duplicates on the primary key, no null values.
- Referential integrity: a foreign key must refer to an existing tuple. Every exam refers to a student present in the Student table. When the student is deleted, the DBMS can refuse the deletion, delete their exams too (cascade) or set the reference to null, according to how the constraint was declared.
Relational algebra
Queries are built with operators that take relations and return relations, and can therefore be composed:
- selection
: the tuples satisfying a condition, i.e. a subset of the rows; - projection
: only some columns, eliminating the resulting duplicates; - union, difference, intersection of relations with the same schema;
- renaming of attributes;
- natural join
: combines the tuples of the two relations that have equal values on the common attributes.

Theorem. The natural join of
and
has a number of tuples between 0 and
. If the common attributes contain a key of
, the result has at most
tuples; if moreover there is a referential integrity constraint from
to
on those attributes, it has exactly
.
Proof. Every tuple of the result comes from a pair of tuples, one of
and one of
, and the possible pairs are
: this is the maximum, reached when all have the same value on the common attributes. The minimum 0 occurs when no value matches. If the common attributes contain a key of
, for every tuple of
there is at most one tuple of
with those values, so every tuple of
contributes at most one tuple to the result. With the referential constraint that tuple of
always exists, and the contribution is exactly one. ∎
It is the most common case: joining exams (with the foreign key) to students (with the key) gives one row per exam, enriched with the student’s data. Knowing this helps to understand when a query returns “too many rows”: usually the join was on attributes that are not a key.
From algebra to SQL
SQL, the language of all relational DBMSs (lesson on SQL), is a declarative language built on these operations: one says what is wanted, not how to get it.
SELECT s.surname, e.mark
FROM Student s JOIN Exam e ON s.number = e.number
WHERE e.mark >= 28;corresponds to
. The DBMS translates the request into an algebra expression and optimises it with algebraic equivalences: for instance it performs the selection before the join, so that fewer tuples are joined. This independence between the question and the way of answering it, made possible by the model’s mathematical basis, is the main reason for its success.
4Normalisation
A table that mixes information about different objects works until it has to be modified: then repeated data must be updated everywhere, and sooner or later someone forgets. Normalisation is the theory that says when a schema is well made and how to fix it. In this lesson we look at anomalies with an example, functional dependencies and Armstrong’s axioms, the closure of a set of attributes and the key test, Heath’s theorem with proof, Boyce-Codd normal form and third normal form.
Anomalies
Consider the table Exams(number, name, code, title, mark), which records exams with the student’s name and the course title. A student’s name appears in every one of their exams, a course’s title in every exam of that course. Three anomalies arise:
- update: to correct a course title hundreds of rows must be modified, and if one is skipped the data become inconsistent;
- insertion: a new course cannot be recorded until someone has taken its exam, because the key (number, code) requires a student number;
- deletion: deleting the last exam of a course also loses its title.
The cause is that the table represents three concepts (students, courses, exams) in one. The theory of functional dependencies makes this precise.
Functional dependencies
Given two sets of attributes
and
of a relation,
(
determines
) if two tuples equal on
are always equal on
too. In the example: number → name, code → title, (number, code) → mark. Functional dependencies are rules of the real world, like the cardinalities of the E-R model, and a key
is exactly a set of attributes such that
all attributes, minimally.
From some dependencies others are deduced with Armstrong’s axioms:
- reflexivity: if
, then
; - augmentation: if
, then
; - transitivity: if
and
, then
.
They are sound (they deduce only true dependencies) and complete (they deduce all those following from the initial ones).
Closure and the key test
The closure
of a set of attributes is the set of all attributes determined by
. It is computed starting from
and adding, while possible, the right-hand side of every dependency
whose left-hand side
is already contained in
.
is a superkey if and only if
contains all the attributes.
In the example,
: start from {number, code}, add name (from number), title (from code), mark (from the third dependency): all attributes, so it is a superkey, and since neither number nor code alone suffices, it is a key.
Decomposing without losing information
Normalising means decomposing a relation into smaller relations. But the decomposition must be lossless: putting the parts back together with the natural join must give exactly the original relation, with no spurious tuples.

Theorem (Heath). If a relation
satisfies
, then the decomposition into
and
is lossless:
.
Proof. *
.* Every tuple
of
has projection
in
and
in
, which combine again into
. *
.* Let
be a tuple of the join. It comes from
, projection of a tuple
of
, and from
, projection of a tuple
of
. The two tuples of
are equal on
, so by the dependency
they are equal on
:
. Then
belongs to
. ∎
Without the dependency the decomposition can create false tuples: if
corresponded to both
and
, the join would combine every
with every
of
, even those never seen together.
Normal forms
A relation is in Boyce-Codd normal form (BCNF) if, for every non-trivial dependency
,
is a superkey. In words: every fact the table records depends on the key, the whole key and nothing else. The Exams table is not in BCNF, because number → name and number is not a superkey. Applying Heath’s theorem twice gives Students(number, name), Courses(code, title) and Exams(number, code, mark): all in BCNF, and the anomalies disappear. It is the same schema that E-R design would have produced directly (lesson on the E-R model).
Decomposition into BCNF is always possible without loss, but sometimes it loses a dependency: it can no longer be checked within a single table. The typical case: in Lessons(student, subject, teacher), each teacher teaches a single subject (teacher → subject) and each student has a single teacher per subject ((student, subject) → teacher). Bringing it to BCNF separates (teacher, subject) from (student, teacher), and the rule linking student and subject to the teacher can no longer be checked in one table. Third normal form (3NF) is somewhat more permissive: it allows
even if
is not a superkey, provided
is part of a key. It can be proved that every schema can always be brought into 3NF losslessly while preserving all dependencies.
In practice one normalises up to 3NF or BCNF, and denormalises deliberately only where read speed is needed, as in data warehouses (lesson on distributed data), accepting redundancy in exchange for fewer joins.
5SQL
SQL is the language for talking to every relational database, from the one in a phone to those of banks. It was born at IBM in the 1970s and is an international standard. In this lesson we look at queries with selection, join and ordering, grouping, subqueries, the null value and three-valued logic with the proof of a classic mistake, views, and how to defend against SQL injection. The examples use the Students, Courses and Exams schema of the lesson on normalisation.
Defining and modifying data
Tables are created by declaring columns, types and constraints:
CREATE TABLE Exams (
number INT REFERENCES Students(number),
code CHAR(6) REFERENCES Courses(code),
mark INT CHECK (mark BETWEEN 18 AND 30),
date DATE NOT NULL,
PRIMARY KEY (number, code)
);Data is modified with INSERT, UPDATE and DELETE, and the DBMS rejects operations that violate the constraints (lesson on the relational model).
Queries
The basic form is SELECT (what to show) FROM (from which tables) WHERE (under which conditions), corresponding to projection, join and selection in relational algebra:
SELECT s.surname, c.title, e.mark
FROM Exams e
JOIN Students s ON s.number = e.number
JOIN Courses c ON c.code = e.code
WHERE e.mark >= 28
ORDER BY e.mark DESC, s.surname;The inner join (JOIN) keeps only the rows that find a match. The outer join (LEFT JOIN) keeps all the rows of the left table, filling the other table’s columns with nulls when there is no match: it is used, for instance, to list students without exams too.
Grouping
Aggregate functions (COUNT, SUM, AVG, MIN, MAX) summarise groups of rows. GROUP BY forms the groups, HAVING filters them after aggregation:
SELECT s.number, s.surname, AVG(e.mark) AS average, COUNT(*) AS exams
FROM Students s JOIN Exams e ON e.number = s.number
GROUP BY s.number, s.surname
HAVING COUNT(*) >= 5
ORDER BY average DESC;WHERE filters rows before grouping them, HAVING filters groups after: the condition on the average goes in HAVING, because the average exists only after grouping.
Subqueries
A query can contain another: “the students who have a mark above the average of all marks”.
SELECT DISTINCT s.surname
FROM Students s JOIN Exams e ON e.number = s.number
WHERE e.mark > (SELECT AVG(mark) FROM Exams);With IN, EXISTS and NOT EXISTS membership and existence are expressed, for instance the students who have never taken a certain exam.
The null value and three-valued logic
NULL represents an unknown or non-existent value: a mark not yet recorded, a middle name that does not exist. A comparison with a null value is neither true nor false, but unknown (U): SQL uses a three-valued logic.

The WHERE clause keeps only the rows for which the condition is true: those with a false or unknown result are discarded.
Theorem. If the subquery contains at least one null value, the condition x NOT IN (subquery) is never true, and the query returns no rows.
Proof. x NOT IN (v1, ..., vn) is equivalent to x <> v1 AND ... AND x <> vn. If one of the values is null, the corresponding comparison x <> NULL is U. An AND containing a U term can be F (if another term is false, i.e.
is in the list) or U (if all the others are true), but never T, as the table shows. So no row satisfies the condition. ∎
It is one of the most treacherous mistakes in SQL: a query that “finds nothing” without raising any error. It is avoided by using NOT EXISTS, which does not have this problem, or by explicitly excluding nulls. For the same reason the null test is written IS NULL, not = NULL, which is always U. Aggregate functions also ignore nulls: COUNT(*) counts the rows, COUNT(mark) only those with a non-null mark, and AVG averages only the values present.
Views
A view is a query that is given a name and used like a table:
CREATE VIEW Averages AS
SELECT number, AVG(mark) AS average FROM Exams GROUP BY number;Views simplify repeated queries, hide the complexity of the schema and are used to grant limited permissions: a user can have access to the view of averages without seeing the individual marks.
SQL injection
Building a query by pasting in text written by the user is the most classic security mistake on the web. If a program executes "SELECT * FROM Users WHERE name = '" + name + "'" and someone types as name ' OR '1'='1, the condition becomes always true and returns all users; with variants whole tables can be read or deleted. The defence is always to use prepared statements with parameters:
SELECT * FROM Users WHERE name = ?the value is passed separately and the DBMS treats it as data, never as code. To this are added the principle of least privilege (the application connects with a user that can do only what it needs) and validation of input data.
6Indexes and query optimisation
A table with a billion rows can be read in full, but it takes minutes. Finding the customer with a given code in a few milliseconds requires an index, like that of a book. In this lesson we look at how a database organises data on disk, B+ trees with the proof of their height and a numerical example, hash indexes, composite indexes and the prefix rule, the cost of indexes on writes and the work of the optimiser.
Pages and accesses
The DBMS reads and writes data in pages (blocks) of a few kilobytes, typically 4-16 KB. The cost of a query is measured in pages read, because a disk access is thousands of times slower than an operation in memory: about 10 ms on a magnetic disk, 0.1 ms on an SSD. A buffer in memory keeps the most frequently used pages. Without indexes, looking for a value requires a scan of the whole table: for a billion 100-byte rows, 100 GB.
B+ trees
The most used index is the B+ tree: a balanced tree in which each node occupies a page and contains many sorted keys with pointers to the children. The leaves contain the keys with references to the rows (or the rows themselves) and are linked in a sorted list. Every node except the root is at least half full, and all leaves are at the same depth.

Theorem. A B+ tree with
keys in its leaves, in which each internal node has at most
children and at least
(the root at least 2), has a height
satisfying
![]()
Proof. *Lower bound.* Each level multiplies the number of nodes by at most
, so a tree of height
has at most
leaf positions: to hold
keys one needs
, i.e.
. *Upper bound.* The root has at least 2 children and every other internal node at least
: at the leaf level there are at least
nodes, hence (with leaves at least half full) at least as many portions of keys. From
it follows that
. ∎
The point is the fan-out
: with 8 KB pages and 40-byte keys with pointers,
is about 200. Example. With
keys,
: 4 levels suffice, and even in the worst case, with half-full nodes, 5 are needed. The first two or three levels, a few thousand pages, always sit in the buffer: finding one row among a billion costs one or two disk reads. Insertions and deletions keep the tree balanced by splitting full nodes and merging underfull ones, at a cost that is logarithmic too.
The linked leaves also make range searches efficient (“marks between 25 and 28”, “March’s orders”) as well as sorting: find the first value and walk the list.
Hash indexes
A hash index computes from each key, with a hash function, the number of the bucket in which to look for it: on average a single access, regardless of table size. But it works only for equality searches: keys are scattered randomly among the buckets, and it is no use for ranges and sorting. That is why DBMSs almost always use B+ trees, and hash indexes in particular cases, such as in-memory joins.
Primary, secondary and composite indexes
A primary (or clustered) index determines the physical order of the rows in the table: rows with nearby keys are in the same pages, and a range is read with a few consecutive pages. There can be only one. Secondary indexes contain references to scattered rows: reading many rows through a secondary index can cost more than a scan, a different page for each row.
A composite index on several columns, for instance (surname, first_name), is sorted first by surname and, for equal surnames, by first name. It serves searches by surname, or by surname and first name, but not those by first name alone, which is scattered throughout the index: this is the leftmost prefix rule.
The price of indexes
Every index speeds up reads but slows down writes: every insertion, update or deletion must update all the table’s indexes, and every index takes space. So the columns actually used in search conditions and joins are indexed, in particular foreign keys, and not every column “just in case”.
The optimiser
For every query the DBMS evaluates many equivalent execution plans (which index to use, in what order to join the tables, with which join algorithm) and chooses the one with the lowest estimated cost, using statistics on the data: number of rows, distinct values, distribution. An index pays off when the condition is selective, i.e. it selects a small fraction of the rows, typically less than 5-10 %; otherwise a sequential scan is faster. The EXPLAIN command shows the chosen plan, and it is the first tool when a query is slow: often one discovers a full scan where an index was expected, because of an unindexed column or a condition written in a way that prevents the index from being used, such as a function applied to the column.
7Transactions and concurrency
A bank transfer takes money from one account and adds it to another: if the system stops halfway, or if two transfers on the same account interleave, money can vanish or multiply. Transactions are the mechanism by which a DBMS guarantees this does not happen, even with thousands of simultaneous users and with failures. In this lesson we look at the ACID properties, concurrency anomalies, serialisability and the conflict graph with the proof of the fundamental theorem, two-phase locking with the proof that it guarantees serialisability, deadlock, isolation levels and recovery after a failure.
The ACID properties
A transaction is a sequence of operations treated as a unit, ending with a COMMIT or a ROLLBACK. It must guarantee:
- atomicity: either all operations take effect, or none does;
- consistency: starting from a state that satisfies the constraints, it reaches a state that satisfies them;
- isolation: each transaction behaves as if it were alone, without seeing the partial results of others;
- durability: once committed, the transaction survives any later failure.
Concurrency anomalies
Executing transactions one at a time would be correct but too slow. Interleaving them freely gives rise to anomalies:
- lost update: two transactions read the same balance of 100, each adds 10 and writes 110: the result should be 120;
- dirty read: a transaction reads data written by another that is then rolled back, i.e. a value that never existed;
- non-repeatable read: reading the same data twice gives different values, because another transaction modified it in between;
- phantoms: re-running a query, new rows inserted by others appear.
Serialisability
A schedule is an interleaving of the operations of several transactions. It is serial if the transactions are executed one after the other, and serialisable if it produces the same effect as a serial schedule. Two operations of different transactions are in conflict if they concern the same data item and at least one is a write: their order matters. A schedule is conflict-serialisable if it can be turned into a serial one by swapping adjacent non-conflicting operations.
The conflict graph has a node for every transaction and an edge
if an operation of
precedes a conflicting operation of
.

Theorem. A schedule is conflict-serialisable if and only if its conflict graph is acyclic.
Proof. *If there is a cycle*
, in any equivalent serial schedule (which must preserve the order of every pair of conflicting operations)
would have to precede
,
precede
, and so on until
precedes itself: impossible. *If the graph is acyclic*, it admits a topological order: an order of the transactions in which every edge goes from a transaction to a later one. The serial schedule in that order preserves the order of all conflicting pairs, because every conflict is an edge and the edges respect the order; non-conflicting operations can be reordered freely. So the schedule is equivalent to the serial one. ∎
Two-phase locking
DBMSs do not build the graph after the fact: they use a protocol that guarantees serialisability by construction. Every transaction must obtain a lock on a data item before using it: shared to read (several transactions can read together), exclusive to write. The two-phase locking protocol (2PL) requires every transaction to acquire all the locks it needs before releasing any: there is a growing phase and a shrinking phase, separated by the lock point.
Theorem. Every schedule produced by transactions that obey two-phase locking is conflict-serialisable.
Proof. If the graph has an edge
, there is a data item
on which an operation of
precedes a conflicting operation of
. The two operations require incompatible locks on
, so
obtained the lock after
released it.
releases only after its own lock point, and
acquires only before its own: so the lock point of
precedes that of
. A cycle in the graph would require the lock point of
to precede itself. The graph is acyclic, and by the previous theorem the schedule is serialisable. ∎
In the strict version, used in practice, exclusive locks are held until COMMIT: so nobody reads data of transactions that might be rolled back, and dirty reads are avoided.
Deadlock
With locks it can happen that
waits for an item locked by
and
for an item locked by
: a deadlock. The DBMS detects it by looking for cycles in the wait-for graph and resolves it by rolling back one of the transactions, which the application will have to retry. That is why a well-written application retries transactions rolled back because of deadlock, and accesses data always in the same order to make deadlocks rare.
Isolation levels
Serialisability costs waiting. SQL provides four isolation levels, allowing progressively fewer anomalies: *read uncommitted*, *read committed* (the default in many systems, which avoids dirty reads), *repeatable read* and *serializable*. Many modern DBMSs use multiversion concurrency control (MVCC): writes create new versions of the data, and every transaction reads a consistent snapshot taken at its start, so reads never block writes and vice versa.
Recovery
For atomicity and durability the DBMS writes every change to a log on stable storage before applying it to the data (write-ahead logging): with the old value and the new one. After a failure, at restart it reads the log: it redoes the changes of committed transactions that might not have reached the data, and undoes those of uncommitted transactions. Periodically it writes a checkpoint so as not to have to reread the log from the beginning. A transaction’s COMMIT is complete when its record is in the log, even if the actual data is still in memory: this is what makes a fast and safe commit possible.
8Distributed data and data warehouses
Large information systems do not sit on a single server: data is copied to several machines so as not to stop when one fails, distributed over many nodes to handle huge volumes, and reorganised into separate stores for analysis. In this lesson we look at replication and the quorum condition with its proof, the CAP theorem with proof, eventual consistency and NoSQL databases, data warehouses with the star schema and OLAP analysis, and the protection of personal data.
Replication
Keeping several copies of the same data on different servers increases availability (lesson on architectures) and makes it possible to spread reads. The problem is keeping them aligned. In synchronous replication a write is acknowledged only when all copies have received it: the copies are always identical, but every write waits for the slowest node and blocks if one does not answer. In asynchronous replication the write is acknowledged at once and propagated later: fast, but for a moment a copy may return old data, and if the primary node fails before propagating, the last writes are lost.
Quorums
A middle way: with
copies, a write is acknowledged when
copies have received it, and a read queries
copies and takes the most recent value (every value carries a version number).
Theorem. If
, every read sees the last acknowledged write.
Proof. The last acknowledged write is on a set of at least
copies; the read queries a set of
copies. If the two sets were disjoint, together they would contain
distinct copies, more than exist: impossible. So at least one queried copy has the latest version, and the read, taking the most recent version, returns it. ∎
With
, the typical choice
tolerates the failure of one copy for both reads and writes;
makes reads fast and writes slow.
The CAP theorem
In a distributed system one would like three properties:
- consistency (C): every read returns the latest write, as if there were a single copy;
- availability (A): every request to a working node receives a response;
- partition tolerance (P): the system keeps working even if the network splits into parts that cannot communicate.
Theorem (CAP, Brewer, proved by Gilbert and Lynch). During a network partition a system cannot be both consistent and available.
Proof. Consider two nodes each with a copy of data item
, initially 0, separated by a partition: no message passes between them. A client writes
to the first node; if the system is available, the write receives a response. Then another client reads
from the second node; if the system is available, the read also receives a response. But the second node could not receive anything from the first, so it answers 0: consistency is violated. To be consistent the system must refuse or indefinitely delay the write or the read, giving up availability. ∎
Partitions do happen in real networks, so the real choice is between C and A when there is a partition: banks and booking systems choose consistency (better to refuse an operation than to sell the same seat twice), social networks and shopping carts choose availability.
Eventual consistency and NoSQL
Systems that favour availability offer eventual consistency: if no new writes arrive, sooner or later all copies converge to the same value. Many NoSQL databases, designed to spread data over hundreds of nodes, are based on this model:
- key-value (as in a distributed hash table), for sessions and caches;
- document stores, holding JSON objects with a flexible structure;
- column-family stores, for huge sparse tables;
- graph databases, for complex relationships such as social networks.
They partly give up joins and multi-object transactions in exchange for scalability. In recent years NewSQL and distributed databases (with consensus protocols such as Raft and Paxos) again offer ACID transactions across many nodes, paying for consistency with some latency.
The data warehouse
Operational systems are optimised for many small transactions; executive analyses (“sales by region and quarter over the last five years”) read millions of rows and would slow everything down. So a data warehouse is built: a separate store, fed periodically by an extract, transform and load (ETL) process that cleans and integrates the data from the various sources.

The typical schema is a star: a fact table with the measures (amounts, quantities) and the keys to the dimension tables (time, product, customer, place), deliberately not normalised so as to require few joins (lesson on normalisation). OLAP analysis navigates this data cube: rolling up (from months to years), drilling down into detail, slicing by a region. Modern systems store data by columns rather than by rows: a query that sums a single column of a billion rows reads only that column, compressed. Data lakes instead keep raw data, even unstructured, for future analyses and for machine learning.
Protection of personal data
An information system that handles people’s data must comply with data protection rules, in Europe the GDPR: collect only the data needed for a declared purpose (minimisation), keep it only as long as necessary, protect it with adequate measures (encryption, access control, logging of operations), allow people to consult it, correct it and ask for its erasure, and notify breaches. Protection must be designed in from the start (privacy by design), not added at the end: the database schema itself, separating identifying data from usage data and pseudonymising where possible, is part of it.
∑Formula sheet
Indexes and query optimisation
B+ trees
![]()