Prerequisites: Data Modelling, the Relational Model & SQL
The database background TIS assumes on day one and never re-teaches — ER and UML conceptual modelling, the relational model and its constraints, the ER to relational translation, functional dependencies and normal forms, relational algebra, and the SQL needed to query a star schema — each tied to the exact chapter and Part II exercise that will demand it.
Why this chapter exists
TIS is a second database course. Its first lecture already draws ER schemas, writes views over
relational sources, and assumes you can read a GROUP BY. None of that is taught anywhere in the
2025/26 decks — it is inherited from the Bachelor’s Databases and Software Engineering
courses. This chapter is the inheritance, collected in one place and pointed at the exact TIS
chapter that will spend it. It carries no exam weight of its own: no past paper tests it
directly, and every past paper depends on it.
01 · Motivation
What TIS assumes you already know
The TIS exam is two parts: three open theory questions (15 pts) and a design exercise (17 pts). The design exercise is always either a data-integration design or a data-warehouse design — and both of them open by handing you a relational or ER schema and expecting you to read it fluently. Marks are lost on the prerequisites far more often than on the TIS material itself.
Here is the ledger. Every row is something TIS uses without introducing, together with the first chapter that needs it and the concrete skill the exam tests.
| Prerequisite | First needed in | You must be able to |
|---|---|---|
| ER model, cardinalities | Ch 01 — source-schema analysis | Read two source schemas and spot the same concept modelled twice |
| UML class diagrams | Ch 04 — wrappers and ontologies | Move between UML and ER without dropping a constraint |
| Relational model, keys | Ch 01, Ch 02 — global schema, views | Say what a key is, and why a foreign key can dangle across sources |
| Intensional vs extensional | Ch 02 — GAV and LAV mappings | Distinguish a mapping between schemas from a mapping between data |
| ER to relational | Ch 04 — XML or JSON to relational | Turn a reverse-engineered conceptual schema into tables |
| Functional dependencies | Ch 07 — the attribute tree | Follow an FD outward from a fact’s primary key |
| Normal forms | Ch 08 — star vs snowflake | Explain why a star schema is denormalized on purpose |
| Relational algebra | Ch 02 — GAV views | Write a global relation as a union of projections over sources |
| SQL with grouping | Ch 08 — OLAP queries | Write a correct GROUP BY over a fact joined to its dimensions |
The three prerequisite errors that cost the most marks
- Reading (min,max) on the wrong side of a relationship — half of a mis-drawn integration schema traces back to this single slip. Section 02 fixes it.
- Forgetting that a many-to-many relationship becomes its own table. In chapter 07 a many-to-many between a fact and a dimension is precisely what forces a multiple edge and a bridge table; if you cannot see the many-to-many, you cannot see the bridge.
- Writing a
GROUP BYwhoseSELECTlist contains an ungrouped, unaggregated column. Chapter 08 grades a full OLAP query in every DW session — this is the fastest way to lose those points.
The running example: PoliBooks
One example runs through the whole chapter, chosen because it grows into both TIS exam exercises. It is a small bookshop chain: shops in cities, books by authors in genres, and a sales record.
PoliBooks — the operational (transactional) world
AUTHOR ──< WRITTEN_BY >── BOOK ──> GENRE
│
│ sold in
▼
REGION <── CITY <── STORE ──< SALE >
(date, quantity, unit price, discount)By the end of the chapter you will have drawn this in ER, in UML, translated it to tables, checked its normal form, queried it in algebra and in SQL — and seen exactly where chapter 07 will pick it up to build a fact schema.
02 · Conceptual model
The Entity-Relationship model
The ER model describes what the world contains, independently of any DBMS. It has six constructs worth memorising.
Entity
A class of objects with autonomous existence — BOOK, STORE. Drawn as a rectangle. An
instance (occurrence) is one member of that class.
Attribute
An elementary property of an entity or relationship — title, price. Composite attributes
group sub-attributes; multivalued attributes have cardinality greater than one.
Relationship
A logical link among two or more entities — WRITTEN_BY between BOOK and AUTHOR. Drawn as a
diamond. It may carry its own attributes.
Cardinality
A pair (min, max) on each participation of an entity in a relationship. Constrains how many
times one instance of that entity may appear.
Identifier (key)
The attributes that distinguish instances. Internal when made of the entity’s own attributes; external when it borrows the identifier of another entity through a relationship.
Generalization
An IS-A hierarchy: EMPLOYEE generalises MANAGER and ENGINEER. Children inherit every
attribute and relationship of the parent.
Cardinality — read it on the entity’s own side
This is the single most misread piece of notation in the whole prerequisite set, so state it precisely. Given a relationship between entities and , the pair written next to answers:
The pair constrains the entity it is written beside — not the one across the diamond.
So min is a participation constraint (0 means optional, 1 means mandatory), and max is a
multiplicity constraint (1 means at most one, N means unbounded). For PoliBooks:
| Participation | Pair | Read as |
|---|---|---|
BOOK in WRITTEN_BY | (1,N) | Every book has at least one author, possibly many |
AUTHOR in WRITTEN_BY | (0,N) | An author may have written no books yet, or many |
BOOK in BELONGS_TO | (1,1) | Every book is in exactly one genre |
GENRE in BELONGS_TO | (0,N) | A genre may hold any number of books, including none |
STORE in LOCATED_IN | (1,1) | Every store sits in exactly one city |
CITY in LOCATED_IN | (0,N) | A city may host any number of stores |
The type of a relationship is named from the two max values: WRITTEN_BY is many-to-many
(N:M), BELONGS_TO and LOCATED_IN are many-to-one (N:1).
Chen notation goes the other way
Some textbooks (and some past-paper figures) use plain Chen notation, writing a single 1 or N
on each edge — and there the label sits on the side opposite the entity it constrains. Whenever
a diagram shows a bare 1/N rather than a (min,max) pair, check which convention it uses
before you translate. Getting this backwards turns a many-to-one into a one-to-many and silently
corrupts every foreign key you derive from it.
Weak entities and external identifiers
An entity that cannot be identified on its own borrows an identifier through a relationship. A
SALE line is only identified by its receipt and its line number:
SALE identifier: (lineNo, RECEIPT via ISSUED_ON)
i.e. lineNo alone repeats across receipts; receipt + lineNo is uniqueThe rule to remember for the translation in section 05: an external identifier always turns into a composite primary key containing the owner’s key.
Generalizations
A generalization is described by two orthogonal flags:
- Total (every parent instance is in some child) versus partial.
- Exclusive (a parent instance is in at most one child) versus overlapping.
The four combinations lead to different translation strategies — section 05 covers them, and the choice is examinable in any course that grades a logical schema.
A relationship SUPERVISES between EMPLOYEE and PROJECT shows (0,1) beside PROJECT and (0,N) beside EMPLOYEE. What kind of relationship is it, and where will the foreign key go?
03 · Notation
UML class diagrams, and the ER dictionary
Polimi teaches conceptual modelling in both notations, and TIS mixes them: integration papers tend to show ER, while wrapper and ontology material (chapter 04) and any industrial deck lean on UML. They express nearly the same information, so the safe move is to keep a translation table in your head.
| ER construct | UML class-diagram construct | Notes |
|---|---|---|
| Entity | Class | UML classes may also carry operations; conceptual data models omit them |
| Attribute | Attribute | UML types them explicitly, e.g. price : Decimal |
| Relationship (binary) | Association | UML names the association and may name a role at each end |
Cardinality (min,max) | Multiplicity min..max | Written on the opposite end — see the warning below |
| Relationship with attributes | Association class | The dashed-line class hanging off the association |
| Identifier | No native construct | Marked with a stereotype or a constraint, e.g. {id} |
| Generalization | Generalization | Same hollow-triangle arrow; UML adds {complete} / {disjoint} |
| Weak entity + external identifier | Composition | The filled diamond implies existence dependency |
| Ternary relationship | N-ary association (diamond) | Rare in UML practice; often reified into a class |
UML multiplicity sits on the far end — the exact opposite of (min,max)
In an ER schema, (1,N) beside BOOK constrains BOOK. In a UML class diagram, the multiplicity
1..* written at the AUTHOR end of an association constrains how many authors one book has.
The two notations put the same number on opposite ends of the line. When a question hands you a
UML diagram and asks for an ER schema, flip every multiplicity across its association before you
copy it.
The UML totality and disjointness flags map straight onto the ER generalization flags:
| UML constraint | ER equivalent |
|---|---|
{complete} | Total |
{incomplete} | Partial |
{disjoint} | Exclusive |
{overlapping} | Overlapping |
PoliBooks in UML
Book and Author become classes joined by a writtenBy association carrying 1..* at the
Author end and 0..* at the Book end. Sale becomes an association class on the association
between Store and Book, holding date, quantity, unitPrice and discount. Store and
City are joined by a plain association, 1 at the City end. Every constraint survives the
round trip — which is the point of keeping the dictionary.
04 · Logical model
The relational model
Where ER describes the world, the relational model describes what a relational DBMS actually stores. TIS lives at the seam between the two, so be precise about the vocabulary.
- Domain
A set of atomic values, e.g. the integers, or strings of length at most 60.
- Relation schema
A name plus a set of typed attributes, written
BOOK(isbn, title, price, genreCode). This is the intensional level — it does not change as data arrives.- Relation instance
A finite set of tuples over that schema. The extensional level — it changes with every insert. Because it is a set, there are no duplicate tuples and no tuple order.
- Tuple
- One row;
t[A]denotes the value of tupleton attributeA. - Superkey
Any attribute set whose values are unique across the instance, for every legal instance.
- Candidate key
- A minimal superkey — remove any attribute and uniqueness is lost.
- Primary key
- The candidate key the designer picks; it may not contain NULL.
- Foreign key
An attribute set in one relation constrained to appear as a key value in another (or be NULL).
Intensional and extensional — remember these two words
Chapter 02 defines GAV and LAV as mappings at the intensional level (schema to schema), and then asks what they imply at the extensional level (which tuples the global relation actually contains, under a sound, complete or exact reading of the source). The whole GAV/LAV distinction is stated in this vocabulary, so it is worth over-learning here rather than mid-chapter.
Integrity constraints
A schema is not just structure; it is structure plus the constraints a legal instance must satisfy.
- Domain constraint — every value lies in its attribute’s domain.
- Key constraint — no two tuples agree on the primary key.
- Entity integrity — no primary-key attribute is NULL.
- Referential integrity — every non-NULL foreign-key value matches an existing key value in the
referenced relation. Violations are handled with
CASCADE,SET NULL, or rejection. - Check constraints — arbitrary tuple-level predicates, e.g.
quantity > 0.
Where referential integrity breaks in TIS
Inside one database, referential integrity is enforced by the DBMS. Across autonomous sources — the entire premise of chapters 01 to 04 — nothing enforces it. A customer id in source A may reference a customer that source B has deleted, and no engine will complain. This is exactly why chapter 03 needs record linkage and data fusion, and why chapter 05 treats referential integrity as a measurable data-quality dimension rather than a guarantee.
NULL and three-valued logic
NULL means no value here, and it is neither zero nor the empty string. Any comparison against
NULL yields unknown, not true or false. The consequences bite in every SQL exercise:
WHERE price = NULLnever matches; you must writeWHERE price IS NULL.WHERE price <> 10silently drops rows wherepriceis NULL.COUNT(*)counts rows;COUNT(price)counts rows wherepriceis not NULL.SUM,AVG,MIN,MAXignore NULLs — soAVGover a column with NULLs is notSUM(col) / COUNT(*).
A table ORDERS has 100 rows; 20 of them have a NULL in the column discount. What do COUNT(*), COUNT(discount) and AVG(discount) return?
05 · The bridge
Translating ER to a relational schema
This is the mechanical bridge between the two previous sections, and chapter 04 asks you to run it after reverse-engineering an XML DTD or a JSON document into a conceptual schema. Four rules cover almost everything.
Rule 1 · Entity
Each entity becomes a relation. Its attributes become columns; its internal identifier becomes the primary key.
Rule 2 · Many-to-one
A relationship whose max is 1 on one side needs no new table. Add the key of the max-N side as a foreign key inside the max-1 side. Nullable if that side’s min is 0.
Rule 3 · Many-to-many
A relationship with max N on both sides becomes its own relation, whose primary key is the pair of foreign keys, plus any attributes the relationship carried.
Rule 4 · One-to-one
Merge the two entities into one relation, or — if participation is optional on one side — keep
both and put a foreign key with a UNIQUE constraint on the mandatory side.
Weak entities follow from rule 2 with one addition: the borrowed foreign key becomes part of the primary key rather than a plain column.
1 · Entities become relations
Six entities, six relations. Identifiers underlined here as PK:
AUTHOR(authorId PK, name, country)
GENRE (genreCode PK, genreName, section)
BOOK (isbn PK, title, price, pages)
REGION(regionCode PK, regionName)
CITY (cityCode PK, cityName, population)
STORE (storeId PK, storeName, address) 2 · Many-to-one relationships become foreign keys
BELONGS_TO is (1,1) on BOOK, so the FK goes in BOOK and is NOT NULL. Likewise
LOCATED_IN puts cityCode in STORE, and the city-to-region link puts regionCode in CITY:
BOOK (isbn PK, title, price, pages, genreCode FK -> GENRE NOT NULL)
STORE(storeId PK, storeName, address, cityCode FK -> CITY NOT NULL)
CITY (cityCode PK, cityName, population, regionCode FK -> REGION NOT NULL)Notice the chain STORE -> CITY -> REGION. Hold on to it: in section 06 it is the transitive
dependency that decides star versus snowflake, and in chapter 07 it is a dimension hierarchy.
3 · The many-to-many becomes its own relation
WRITTEN_BY is N:M, so rule 3 applies. Its key is the pair:
WRITTEN_BY(isbn FK -> BOOK, authorId FK -> AUTHOR, role)
PK = (isbn, authorId)This table has a name in the warehouse world: chapter 07 calls the structure it creates a multiple edge, and chapter 08 implements it as a bridge table with a weight column. Same construct, two vocabularies.
4 · The sale: a weak entity with a composite key
A sale line is identified by its receipt plus its line number, and it references both the store and the book:
SALE(receiptNo, lineNo, saleDate, quantity, unitPrice, discount,
storeId FK -> STORE, isbn FK -> BOOK)
PK = (receiptNo, lineNo) 5 · Read back the result
Seven relations, six foreign keys, one bridge table. This is a textbook operational schema — the kind chapter 07 hands you as the starting point of a DW design exercise, and the kind chapter 01 hands you twice, from two different companies, as the starting point of an integration exercise.
Deep dive Translating generalizations — the three strategies
Given a parent PERSON(ssn, name) with children STUDENT(matricola) and EMPLOYEE(salary):
(a) Collapse into the parent. One relation PERSON(ssn, name, matricola, salary, type). The
child-specific columns are nullable and a discriminator column records the subtype. Simple and
join-free; wastes space and cannot enforce “a student must have a matricola” declaratively. This is
the strategy to prefer when the children add few attributes and queries usually span the hierarchy.
(b) Collapse into the children. Drop the parent relation; STUDENT(ssn, name, matricola) and
EMPLOYEE(ssn, name, salary) each replicate the parent’s attributes. Only legal when the
generalization is total — otherwise a parent instance in no child has nowhere to live — and
awkward when it is overlapping, since a person who is both is stored twice.
(c) Keep all three. PERSON(ssn, name), STUDENT(ssn FK, matricola), EMPLOYEE(ssn FK, salary). No redundancy, no NULLs, but every query about a student pays for a join. Preferred when
the children are queried separately and carry many attributes of their own.
The exam-relevant point is that totality and exclusivity decide which strategies are even available, not just which is nicest.
An ER schema has a relationship ENROLLED between STUDENT (0,N) and COURSE (0,N), carrying an attribute grade. How many relations does the translation produce, and where does grade live?
06 · Dependencies
Functional dependencies and normal forms
This section is short but it is the highest-leverage part of the chapter, because chapter 07’s attribute tree is nothing but a functional-dependency graph and chapter 08’s star versus snowflake decision is nothing but a normalization trade-off.
The definition
A functional dependency holds on relation when any two tuples that agree on the attributes also agree on the attributes :
Read it as “X determines Y” — X’s value fixes Y’s value.
An FD is a statement about every legal instance, not about the rows you happen to see. It comes from the meaning of the data, so you infer it from the domain, never from a sample.
Keys fall straight out of the definition: is a superkey of exactly when , and a candidate key when no proper subset of also determines . In PoliBooks:
isbn -> title, price, pages, genreCode
genreCode -> genreName, section
storeId -> storeName, address, cityCode
cityCode -> cityName, population, regionCode
regionCode -> regionName
(receiptNo, lineNo) -> saleDate, quantity, unitPrice, discount, storeId, isbnThis list IS the attribute tree
Chapter 07 builds the DFM attribute tree by rooting it at the fact’s primary key and following the
functional dependencies outward — “each node functionally determines its descendants”. Root the
list above at (receiptNo, lineNo) and follow the arrows: you get storeId, then cityCode,
then regionCode, then regionName. That chain is the store dimension hierarchy, and you
just built it with nothing but FDs.
Anomalies and the normal forms
Denormalized tables suffer three classic anomalies: update (change Milan’s population in one row and not the others), insertion (cannot record a city with no store), and deletion (removing the last store erases the city). The normal forms exist to eliminate them.
| Form | Requirement |
|---|---|
| 1NF | Every attribute is atomic; no repeating groups or nested tables |
| 2NF | 1NF, and no non-prime attribute depends on only part of a candidate key |
| 3NF | 2NF, and for every FD X -> A, either X is a superkey or A is prime (in some key) |
| BCNF | For every non-trivial FD X -> A, X is a superkey — no exceptions for prime attributes |
An attribute is prime when it belongs to some candidate key. BCNF is strictly stronger than 3NF; the two differ only when a schema has overlapping candidate keys, which is rare in practice and common in exams.
Worked Worked normalization: the denormalized store table
Suppose someone hands you a single flattened table:
STOREFLAT(storeId PK, storeName, address, cityCode, cityName,
population, regionCode, regionName)The only candidate key is storeId. But two FDs hold whose left side is not a superkey:
cityCode -> cityName, population, regionCode
regionCode -> regionNameSo regionName depends on storeId only transitively, through cityCode and regionCode. That
is a 3NF violation (and a BCNF violation). Decompose along each offending FD:
STORE (storeId PK, storeName, address, cityCode FK)
CITY (cityCode PK, cityName, population, regionCode FK)
REGION(regionCode PK, regionName)Every FD’s left side is now the primary key of its own relation, so the schema is in BCNF, and the decomposition is lossless because each split happens on a key of the new relation.
And then chapter 08 undoes all of it — deliberately
A star schema stores exactly STOREFLAT: one wide, denormalized dimension table per
dimension, transitive dependencies and all. That is not an error. Operational databases normalize
because they are write-heavy and cannot afford update anomalies; a data warehouse is
read-only and bulk loaded, so the anomalies cannot arise, and flattening buys back the joins
that dominate an OLAP query’s cost. A snowflake schema partially re-normalizes the dimensions
— trading query speed for storage and, occasionally, for a genuinely reusable sub-dimension. When
chapter 08 asks you to justify star over snowflake, this paragraph is the answer, and “the star is
denormalized” is only half of it — the other half is why that is safe here.
Relation R(A, B, C) has candidate key A and the functional dependency B -> C, where B is not a key. What is the highest normal form R satisfies?
07 · Query semantics
Relational algebra
Relational algebra is the mathematical query language whose operators consume relations and produce relations. TIS needs it for one specific reason: a GAV mapping defines each global relation as an algebraic view over the sources, and chapter 02 grades exactly that.
- σ (selection)
- Keeps the tuples satisfying a predicate.
σpicks rows. - π (projection)
Keeps the listed attributes, then removes duplicates (the result is a set).
πpicks columns.- ρ (rename)
Renames a relation or its attributes — the operator that resolves the name conflicts chapter 01 asks you to detect.
- × (product)
Every pairing of tuples from two relations; almost always followed by a selection.
- ∪ − ∩ (set operators)
Union, difference, intersection — defined only for union-compatible relations, i.e. same arity and matching domains.
- ⋈ (join)
A product followed by a selection. The natural join equates all same-named attributes; a theta join takes an explicit predicate.
- Outer join
Like a join, but tuples with no match are kept and padded with NULL — left, right, or full. Indispensable when integrating sources that do not fully overlap.
- γ (grouping)
Partitions by the grouping attributes and applies aggregates; the algebraic form of SQL’s
GROUP BY.
Only six of these are primitive — selection, projection, rename, product, union, difference — and everything else is derived. That is worth knowing because a theory question may ask you to express one operator in terms of others.
PoliBooks in algebra
“Titles of books priced above 20 in the Science genre”:
“Total quantity sold per store”:
Why chapter 02 needs this
A GAV mapping writes each global relation as a view over sources — literally an algebra expression, most often a union of projections:
Query answering is then unfolding: substitute the definition into the user’s query and evaluate. LAV inverts the direction — each source is a view over the global schema — and query answering becomes the harder problem of answering queries using views. You cannot follow either argument without being fluent in the algebra above.
Two sources both list books. S1(isbn, title, price) covers only Italian publishers; S2(isbn, title, price, publisher) covers everything. A GAV view defines the global Book as the union of projections over both. Why must a projection appear before the union?
08 · Query language
The SQL you must be able to write cold
Chapter 08 grades a full OLAP query in most DW sessions. These are the shapes it assumes.
The evaluation order that explains everything
Written order and evaluation order are different, and almost every SQL confusion dissolves once you internalise the second:
written: SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ...
evaluated: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BYThree consequences follow immediately:
WHEREfilters rows,HAVINGfilters groups.WHEREruns before grouping exists, so it cannot mention an aggregate;HAVINGruns after, so it can.- A
SELECTalias is not visible inWHEREorGROUP BY, becauseSELECTis evaluated later. It is visible inORDER BY. - Every column in
SELECTmust be grouped or aggregated. AfterGROUP BYeach group is one output row, so an ungrouped, unaggregated column has no single value to show.
Joins
-- inner: only matching pairs survive
SELECT B.title, G.genreName
FROM BOOK B JOIN GENRE G ON B.genreCode = G.genreCode;
-- left outer: every book survives, genre columns NULL when unmatched
SELECT B.title, G.genreName
FROM BOOK B LEFT OUTER JOIN GENRE G ON B.genreCode = G.genreCode;Use an outer join whenever the question says “including those with none” — books with no sales, stores with no staff. An inner join silently deletes exactly the rows such a question is asking about.
Grouping and aggregation
SELECT C.cityName, COUNT(*) AS numSales, SUM(S.quantity) AS totalQty
FROM SALE S
JOIN STORE T ON S.storeId = T.storeId
JOIN CITY C ON T.cityCode = C.cityCode
WHERE S.saleDate >= DATE '2025-01-01'
GROUP BY C.cityName
HAVING SUM(S.quantity) > 500
ORDER BY totalQty DESC;That is the canonical warehouse query shape: fact joined to its dimensions, filtered, grouped by a
dimension attribute, aggregated over a measure. Chapter 08 varies it — WITH CUBE, WITH ROLLUP,
window functions, greatest-per-group — but the skeleton never changes.
Subqueries and views
-- scalar subquery: books priced above average
SELECT title FROM BOOK
WHERE price > (SELECT AVG(price) FROM BOOK);
-- correlated EXISTS: genres that have at least one book over 50
SELECT G.genreName FROM GENRE G
WHERE EXISTS (SELECT 1 FROM BOOK B
WHERE B.genreCode = G.genreCode AND B.price > 50);
-- a view: a named query, and the mechanism behind GAV
CREATE VIEW ExpensiveBooks AS
SELECT isbn, title, price FROM BOOK WHERE price > 50;A view is the conceptual tool of the whole integration half
Chapter 01 introduces views as the device for expressing the relationship between a global schema and its sources, and chapter 02 builds GAV and LAV entirely out of them. A view is a query with a name — no data of its own, resolved at query time. That “no data of its own” is precisely what makes virtual integration virtual, and its opposite, a materialized view, is precisely what makes a data warehouse materialized. One SQL construct, both halves of the course.
NOT IN with a NULL returns nothing
If the subquery in x NOT IN (SELECT y FROM T) returns even one NULL, the whole predicate
evaluates to unknown for every x and the outer query returns the empty set. Use NOT EXISTS
instead — it is NULL-safe. This trap appears in real exam data far more often than in textbook
data, because real sources are full of NULLs.
Which clause correctly returns only the cities whose total sold quantity exceeds 500?
09 · Practice
Exercises
Work each one on paper before opening its solution. They are ordered to mirror the chapter, and the last three are deliberately in the shape TIS will use them.
Try it Exercise 1 — Read the cardinalities
Task. A hospital schema has DOCTOR and PATIENT joined by TREATS, with (1,N) beside
DOCTOR and (0,N) beside PATIENT. State the relationship type, say whether either participation
is optional, and give the relations the translation produces.
Solution. Both maxima are N, so TREATS is many-to-many. DOCTOR has min 1, so every doctor
treats at least one patient — mandatory participation. PATIENT has min 0, so a patient may be
registered without any treating doctor — optional. Rule 3 gives three relations:
DOCTOR(doctorId, ...), PATIENT(patientId, ...), and TREATS(doctorId, patientId, ...) with
primary key (doctorId, patientId). Note that the min values constrain instances and cannot be
expressed by the translation — a mandatory participation on the many-to-many side needs a trigger or
an application check, which is a standard follow-up question.
Try it Exercise 2 — UML to ER
Task. A UML class diagram shows Course and Student joined by an association attends, with
1..* at the Student end and 0..* at the Course end, plus an association class Attendance
holding grade. Draw the equivalent ER fragment.
Solution. Flip each multiplicity to the opposite end. 1..* at the Student end says a course
has one or more students, which in ER is (1,N) written beside COURSE. 0..* at the Course
end says a student attends zero or more courses, which is (0,N) beside STUDENT. The
association class becomes an attribute on the relationship: ATTENDS(grade). The relationship is
many-to-many, so it will translate to its own table keyed by (courseId, studentId) with grade as
a column.
Try it Exercise 3 — Find the candidate key
Task. R(A, B, C, D) with FDs AB -> C, C -> D, D -> A. Find a candidate key and the
highest normal form.
Solution. Start from AB: AB -> C (given), then C -> D, then D -> A, so
AB determines A, B, C, D — AB is a superkey, and neither A nor B alone determines
everything, so AB is a candidate key. It is not the only one: from BC you get D then A,
so BC is also a candidate key; likewise BD gives A then C. So the prime attributes are
A, B, C, D — all of them.
Because every attribute is prime, no 3NF violation is possible and R is in 3NF. But C -> D has
a non-superkey left side, so R is not in BCNF. This is the classic case where 3NF and BCNF
diverge, and it only arises because the candidate keys overlap.
Try it Exercise 4 — Star or snowflake
Task. You are designing a product dimension with the hierarchy
product -> subcategory -> category -> department. Give one concrete argument for storing it as a
single flat table and one for normalizing it, and say which you would defend in an exam.
Solution. Flat (star): a query grouping by department touches one table instead of four, and
because the warehouse is bulk-loaded and read-only, the update anomalies that normally justify
normalization cannot occur. Star is the default answer and the one the course teaches.
Normalized (snowflake): the department table is small and stable, so the storage saved is real if
the dimension is very large or very sparse, and a normalized sub-dimension can be shared by
several fact tables as a conformed dimension. Defend the star unless the question explicitly
raises dimension size, sparsity, or reuse across facts — and say why the anomalies are harmless
here, because that reasoning is what earns the mark.
Try it Exercise 5 — Write the algebra, then the SQL
Task. Over the PoliBooks relational schema, express “for each region, the total quantity sold in 2025, including regions that sold nothing” first in relational algebra, then in SQL.
Solution. The phrase including regions that sold nothing forces an outer join — the whole point of the exercise.
Algebra, reading right to left: restrict the sales, join the chain, then group.
SQL:
SELECT R.regionName, COALESCE(SUM(S.quantity), 0) AS totalQty
FROM REGION R
LEFT OUTER JOIN CITY C ON C.regionCode = R.regionCode
LEFT OUTER JOIN STORE T ON T.cityCode = C.cityCode
LEFT OUTER JOIN SALE S ON S.storeId = T.storeId
AND S.saleDate >= DATE '2025-01-01'
AND S.saleDate < DATE '2026-01-01'
GROUP BY R.regionName;Two details carry the marks. The date filter sits in the ON clause, not WHERE: moving it to
WHERE would discard the NULL-padded rows and quietly turn the outer join back into an inner one.
And COALESCE turns the resulting NULL sum into a 0, because SUM over zero rows is NULL, not 0.
Try it Exercise 6 — Spot the prerequisite in a TIS question
Task. A Part II data-warehouse exercise says: “Given the operational schema below, identify the fact, build the attribute tree, and prune it.” Which prerequisites from this chapter are you being tested on before you write a single DFM symbol?
Solution. Three. (1) Reading the relational schema and its foreign keys, to see which tables are transactional events (candidates for the fact) and which are lookups (candidates for dimensions). (2) Functional dependencies, because the attribute tree is rooted at the fact’s primary key and every edge is an FD — you build it by following FDs and foreign keys outward. (3) Recognising many-to-many relationships, because each one you overlook is a multiple edge you will fail to draw, and later a bridge table you will fail to create. The DFM notation itself is the easy half; these three are what actually decide the mark.
10 · Recap
Chapter 00 — load-bearing ideas
- ER cardinality
(min,max)constrains the entity it is written beside; UML multiplicity constrains the entity at the opposite end. Flip every multiplicity when converting, and check which convention a bare1/Ndiagram is using. - The relational model is schema plus constraints. Schema is the intensional level, instance the
extensional level — the exact vocabulary chapter 02 states GAV and LAV in.
NULLis unknown, not zero, and it propagates through comparisons,COUNT(col), andNOT IN. - Four translation rules cover ER to relational: entity to relation; many-to-one to a foreign key
on the max-1 side; many-to-many to its own relation keyed by the pair; one-to-one merged or keyed
with
UNIQUE. Generalization totality and exclusivity decide which of the three strategies are legal. - A functional dependency is the atom of everything downstream. Keys are FDs (
K -> R), normal forms are restrictions on which FDs may exist, and chapter 07’s attribute tree is an FD graph rooted at the fact’s primary key. - Normalization removes anomalies that a data warehouse cannot suffer, which is why the star schema denormalizes on purpose and the snowflake partially undoes it. Knowing why that is safe is the answer chapter 08 wants, not just that it happens.
- Relational algebra is the language of a GAV view — a global relation as a union of projections over union-compatible sources — and unfolding is substitution into that expression.
- SQL’s evaluation order (
FROM,WHERE,GROUP BY,HAVING,SELECT,ORDER BY) explains every rule you were told to memorise: whyWHEREcannot see aggregates, whyHAVINGcan, why an alias works inORDER BYbut notWHERE, and why an outer join’s filter belongs inON. - Exam radar: this chapter is never asked about directly and is assumed in every Part II. If a design exercise feels impossible, the missing piece is usually on this page rather than in the TIS material — most often a misread cardinality or an unnoticed many-to-many.
Next: chapter 01 picks up exactly here, handing you two operational schemas of this kind and asking what it takes to merge them into one.