Module 2 Β· Data Modeling
How a database is designed before any table is created: data models, E-R diagrams and how they become tables, the relational model, keys and integrity rules, functional dependencies and normalization. Every idea is shown on the design of our own university_lab.
- βΈ Compare conceptual, logical and physical data models
- βΈ Draw an E-R diagram and convert it into tables
- βΈ Use the vocabulary of the relational model correctly
- βΈ Identify super, candidate, primary, alternate and foreign keys
- βΈ Explain domain, entity and referential integrity
- βΈ Find functional dependencies, closures and candidate keys
- βΈ Normalize a table step by step from 1NF to BCNF
The inter schema of university_lab, loaded with the sample rows. Examples that change data run inside a transaction and end with ROLLBACK, so your data stays as it was.
2.1 Data Models: Conceptual, Logical, Physical
A good data model:
- Represents every data object the system needs β a missing object means faulty reports.
- Gives a clear picture of the data that developers can turn into a physical database.
- Defines the tables, primary and foreign keys, and constraints.
- Exposes missing and redundant data early, when it is cheap to fix.
There are three kinds, each more detailed than the last:
| Conceptual | Logical | Physical | |
|---|---|---|---|
| Answers | WHAT the system contains | HOW it is structured β independent of any DBMS | HOW it is built in a specific DBMS |
| Created by | Business stakeholders, data architects | Data architects, business analysts | DBAs and developers |
| Entities / tables | β entity names | β entities | β table names |
| Relationships | β | β | β (as foreign keys) |
| Attributes / columns | β | β attributes | β column names |
| Primary and foreign keys | β | β | β |
| Data types | β | Generic (text, number, date) | Exact DBMS types (VARCHAR(120), INTEGER) |
| Indexes, storage, triggers | β | β | β |
| Normalization | β | Applied, usually up to 3NF | Inherited from the logical model |
Enrollment(enrollment_id, student_id β Student, offering_id β Offering, enrolled_on)
Offering(offering_id, room, capacity)
Only the physical model exists inside PostgreSQL β and you can read it back. Module 1 (1.5) showed the CREATE TABLE; here PostgreSQL reports the physical types it actually uses:
SELECT column_name, data_type, character_maximum_length AS max_len, is_nullable
FROM information_schema.columns
WHERE table_schema = 'inter' AND table_name = 'courses'
ORDER BY ordinal_position;
column_name | data_type | max_len | is_nullable
-------------+-------------------+---------+-------------
course_id | integer | | NO
course_code | character varying | 10 | NO
title | character varying | 120 | NO
credits | integer | | NO
dept_id | integer | | YES- βΈConceptual = WHAT (entities, relationships). Logical = HOW, DBMS-independent (attributes, keys). Physical = HOW in a specific DBMS (types, indexes).
- βΈEach model adds detail to the one before it.
- βΈOnly the physical model depends on the DBMS product.
2.2 Record-Based Models
| Model | Structure | Relationships | Example systems | Main weakness |
|---|---|---|---|---|
| Hierarchical | Tree: each child record has exactly one parent | Only 1:N (parent β children) | IBM IMS (1960s) | M:N needs duplicated records; access only from the root down |
| Network | Graph: records linked by ownerβmember sets | 1:N and M:N (through link records) | CODASYL / IDMS | Programs navigate pointers; structure changes break programs |
| Relational | Tables of rows and columns | Any, through matching key values | PostgreSQL, Oracle, MySQL | Joins cost work at query time (solved by optimisers and indexes) |
Computer Science
β CS201 Database Systems
β 2024-Odd, LH-1
β Aarav
β Diya
β Kevin
β CS101 Intro to Programming
β 2024-Odd, LH-3
β Aarav β stored againSTUDENT Aarav ββ
βββΊ ENROLLMENT βββ
βββΊ ENROLLMENT βββΌβ OFFERING CS101
β
STUDENT Diya ββββΊ ENROLLMENT ββββ΄β OFFERING CS201
Each arrow is a stored pointer
(an ownerβmember set).students enrollments
student_id name student_id offering_id
1 Aarav 1 1
2 Diya 2 1
1 3
Links are just matching values
β no pointers.- βΈHierarchical = tree (1:N only). Network = graph of linked records (allows M:N). Relational = tables linked by values.
- βΈHierarchical and network systems are navigational: programs follow pointers record by record.
- βΈThe relational model replaced them because it is simpler and gives data independence.
2.3 E-R Model: Entities & Attributes
- Entity β a real-world object that can be distinctly identified: a particular student, course or department.
- Entity set β a collection of entities of the same type: all students. In a diagram the rectangle stands for the entity set.
- Attribute β a property that describes an entity: a student's name or email.
- Domain β the set of allowed values of an attribute: a name is text; a year is a positive number.
- Weak entity β an entity that cannot be identified by its own attributes alone and depends on an owner entity. Example: an assessment (βQuiz 1β) exists only within a particular course offering.
| Attribute type | Meaning | Example (student) |
|---|---|---|
| Simple | Cannot be divided further (atomic) | |
| Composite | Made of several simple attributes | name = first_name + last_name |
| Single-valued | Holds one value per entity | date_of_birth |
| Multi-valued | Can hold several values per entity | phone β a student may have two numbers |
| Derived | Not stored; calculated from other attributes | age, from date_of_birth |
| Key | Uniquely identifies each entity | student_id |
| Symbol | Means | Symbol | Means |
|---|---|---|---|
| Entity set | Weak entity set | ||
| Attribute | Key attribute | ||
| Multi-valued attribute | Derived attribute | ||
| Relationship set | Identifying relationship (of a weak entity) | ||
| Partial participation | Total participation |
The real inter.students table made simple choices for each kind of attribute:
| Attribute kind | What we did in university_lab |
|---|---|
| Key | student_id β the primary key |
| Composite (name) | Kept as one column, full_name. Splitting into first/last is also correct; it depends on how the data is searched. |
| Multi-valued (phone) | Not stored yet. It would need its own table β see 2.5. |
| Derived | Not stored. Example: seats_left in v_seat_availability is calculated each time from capacity and enrollments. |
- βΈEntity = a thing; entity set = all things of that type; attribute = a property; domain = allowed values.
- βΈSix attribute types: simple, composite, single-valued, multi-valued, derived, key.
- βΈA weak entity depends on an owner entity for its identity.
2.4 E-R Model: Relationships & Cardinality
- Degree β the number of entity sets taking part: unary (recursive), binary or ternary.
- Cardinality ratio (mapping cardinality) β how many entities on one side can relate to one entity on the other: 1:1, 1:N, N:1 or M:N.
- Participation β total if every entity must take part (double line); partial if some may not (single line).
| Relationship | Between | Degree | Cardinality | Participation |
|---|---|---|---|---|
| belongs to | STUDENT β DEPARTMENT | Binary | N:1 | Partial (dept_id may be NULL) |
| works in | FACULTY β DEPARTMENT | Binary | N:1 | Partial |
| owns | COURSE β DEPARTMENT | Binary | N:1 | Partial |
| requires | COURSE β COURSE | Unary (recursive) | M:N | Partial β not every course has a prerequisite |
| offered as | COURSE β COURSE OFFERING | Binary | 1:N | Total for offerings (course_id NOT NULL) |
| runs in | COURSE OFFERING β SEMESTER | Binary | N:1 | Total for offerings (semester_id NOT NULL) |
| teaches | FACULTY β COURSE OFFERING | Binary | 1:N | Partial (faculty_id may be NULL) |
| enrolls in | STUDENT β COURSE OFFERING | Binary | M:N | Partial β a student may have no enrollments yet |
A course offering itself is the meeting point of three things β a course, a semester and a faculty member. That is a ternary association, which we modeled as an entity with three relationships.
- βΈDegree: unary, binary, ternary. Cardinality: 1:1, 1:N, N:1, M:N.
- βΈTotal participation (double line) = every entity must take part; partial (single line) = optional.
- βΈA recursive relationship links an entity set to itself β course requires course.
2.5 From E-R Diagram to Tables
| E-R construct | Becomes | In university_lab |
|---|---|---|
| Strong entity | A table; its key attribute becomes the PRIMARY KEY | STUDENT β students(student_id PK, β¦) |
| Simple attribute | A column | email β email VARCHAR(120) |
| Composite attribute | One column per component (or one combined column) | name β full_name (combined) |
| Multi-valued attribute | A new table: owner key + value, both in the primary key | phone β student_phones(student_id, phone) |
| Derived attribute | Not stored; calculated in a query or view | seats_left in v_seat_availability |
| Weak entity | A table holding the owner's key as a foreign key; owner key + partial key = primary key | assessments(offering_id, name) β in the Advanced lab |
| 1:N relationship | A foreign key on the N side | course_offerings.semester_id β semesters |
| 1:1 relationship | A foreign key on either side, made UNIQUE | e.g. departments.head_faculty_id UNIQUE β faculty |
| M:N relationship | A junction table with both foreign keys; together they identify a row | enrollments(student_id, offering_id) |
| Recursive relationship | Foreign key(s) back to the same table | prerequisites(course_id, prereq_course_id) |
SELECT c.course_code AS course, p.course_code AS requires
FROM inter.prerequisites r
JOIN inter.courses c ON c.course_id = r.course_id
JOIN inter.courses p ON p.course_id = r.prereq_course_id
ORDER BY 1, 2;
course | requires
--------+----------
CS201 | CS101
CS201 | CS210
DA301 | CS201CREATE TABLE inter.student_phones (
student_id INTEGER NOT NULL REFERENCES inter.students(student_id) ON DELETE CASCADE,
phone VARCHAR(15) NOT NULL,
PRIMARY KEY (student_id, phone) -- one row per student per number
);
INSERT INTO inter.student_phones (student_id, phone)
SELECT student_id, p
FROM inter.students, (VALUES ('9847011111'), ('9847022222')) AS v(p)
WHERE email = 'diya@duk.ac.in';
SELECT s.full_name, sp.phone
FROM inter.student_phones sp JOIN inter.students s USING (student_id);
full_name | phone
-----------+------------
Diya Nair | 9847011111
Diya Nair | 9847022222
DROP TABLE inter.student_phones; -- tidy up when you are done- βΈEntity β table. 1:N β foreign key on the N side. M:N β junction table.
- βΈMulti-valued attribute β its own table. Derived attribute β not stored.
- βΈWeak entity β table whose primary key includes the ownerβs key.
2.6 The Relational Model
| Formal term | Everyday term | Meaning | In inter.students |
|---|---|---|---|
| Relation | Table | A set of tuples with the same attributes | inter.students |
| Tuple | Row / record | One entityβs data | Diyaβs row |
| Attribute | Column / field | One named property | email |
| Domain | Data type + rules | The set of allowed values of an attribute | join_year: integers |
| Degree | Number of columns | How many attributes a relation has | 5 |
| Cardinality | Number of rows | How many tuples it holds right now | 6 |
| Relation schema | Table definition | The name and attributes: students(student_id, full_name, email, join_year, dept_id) | \d inter.students |
| Relation instance | Table contents | The set of tuples at a given moment | SELECT * FROM inter.students |
| Relation key | Key | Attribute(s) that identify each tuple uniquely | student_id |
Properties every relation has:
- Each cell holds a single, atomic value.
- Each column holds values from one domain, and each column has a unique name.
- No two rows are identical β a relation is a set.
- The order of rows and of columns does not matter.
Schema vs instance β for the whole database too
The database schema is the skeleton: all table definitions, views and constraints. It is designed first and rarely changes. The database instance is the data in it at one moment β a snapshot that changes with every INSERT, UPDATE and DELETE. The DBMS keeps every instance valid by enforcing the constraints in the schema.
SELECT COUNT(*) AS degree
FROM information_schema.columns
WHERE table_schema = 'inter' AND table_name = 'students'; -- 5
SELECT COUNT(*) AS cardinality FROM inter.students; -- 6- βΈRelation = table, tuple = row, attribute = column, domain = allowed values.
- βΈDegree = number of attributes; cardinality = number of tuples.
- βΈSchema = structure (changes rarely); instance = data at a moment (changes constantly).
2.7 Keys
| Key | Definition | In university_lab |
|---|---|---|
| Super key | Any set of attributes that identifies rows uniquely (may contain extra attributes) | (student_id), (email), (student_id, email), (email, full_name)β¦ |
| Candidate key | A minimal super key β remove any attribute and it stops being unique | student_id and email in students |
| Primary key | The candidate key chosen to identify rows; it can never be NULL | student_id |
| Alternate key | A candidate key that was not chosen as primary β enforced with UNIQUE | email (UNIQUE) |
| Composite key | A key made of two or more attributes | (course_id, prereq_course_id) in prerequisites |
| Foreign key | Attribute(s) that refer to the primary key of another (or the same) relation | enrollments.student_id β students |
| Surrogate key | An artificial key with no business meaning, usually generated | student_id (SERIAL) |
| Natural key | A key that exists in the real world | course_code (CS201), email |
A candidate key's attributes are called prime attributes; all others are non-prime. These terms matter in functional dependency (2.10) and normalization (2.11).
SELECT conrelid::regclass AS table_name,
CASE contype WHEN 'p' THEN 'PRIMARY KEY' ELSE 'UNIQUE' END AS key_type,
pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE connamespace = 'inter'::regnamespace AND contype IN ('p', 'u')
ORDER BY conrelid::regclass::text, contype, conname;
table_name | key_type | definition
------------------------+-------------+---------------------------------------------
inter.course_offerings | PRIMARY KEY | PRIMARY KEY (offering_id)
inter.course_offerings | UNIQUE | UNIQUE (course_id, semester_id, faculty_id)
inter.courses | PRIMARY KEY | PRIMARY KEY (course_id)
inter.courses | UNIQUE | UNIQUE (course_code)
inter.departments | PRIMARY KEY | PRIMARY KEY (dept_id)
inter.departments | UNIQUE | UNIQUE (dept_code)
inter.departments | UNIQUE | UNIQUE (dept_name)
inter.enrollments | PRIMARY KEY | PRIMARY KEY (enrollment_id)
inter.enrollments | UNIQUE | UNIQUE (student_id, offering_id)
inter.faculty | PRIMARY KEY | PRIMARY KEY (faculty_id)
inter.faculty | UNIQUE | UNIQUE (email)
inter.prerequisites | PRIMARY KEY | PRIMARY KEY (course_id, prereq_course_id)
inter.semesters | PRIMARY KEY | PRIMARY KEY (semester_id)
inter.semesters | UNIQUE | UNIQUE (name)
inter.students | PRIMARY KEY | PRIMARY KEY (student_id)
inter.students | UNIQUE | UNIQUE (email)Every UNIQUE line is an alternate key. enrollments has a surrogate primary key, enrollment_id, plus the natural composite candidate key (student_id, offering_id).
- βΈSuper key β candidate key (minimal) β one chosen as primary key; the rest are alternate keys.
- βΈPrimary key: unique and never NULL. Foreign key: refers to a primary key.
- βΈSurrogate key = generated (SERIAL); natural key = real-world (email, course_code).
2.8 Integrity Constraints & Integrity Rules
INSERT, UPDATE and DELETE and rejects any change that would break one.| Integrity rule | States that⦠| Enforced in SQL by |
|---|---|---|
| Domain integrity | Every value comes from its attributeβs domain | Data types, NOT NULL, CHECK, DEFAULT |
| Entity integrity (key constraint) | Every row is uniquely identified; no part of a primary key may be NULL | PRIMARY KEY, UNIQUE |
| Referential integrity | A foreign key value must match an existing primary key value β or be NULL | FOREIGN KEY β¦ REFERENCES, with ON DELETE / ON UPDATE actions |
-- CHECK: credits must be between 1 and 6
INSERT INTO inter.courses (course_code, title, credits) VALUES ('CS999', 'Capstone', 9);
ERROR: new row for relation "courses" violates check constraint "courses_credits_check"
-- data type: join_year is an integer
INSERT INTO inter.students (full_name, email, join_year) VALUES ('Test', 'test@duk.ac.in', 'twenty');
ERROR: invalid input syntax for type integer: "twenty"
-- NOT NULL: every student needs an email
INSERT INTO inter.students (full_name, join_year) VALUES ('No Email', 2024);
ERROR: null value in column "email" of relation "students" violates not-null constraint
-- CHECK across columns: a semester must end after it starts
INSERT INTO inter.semesters (name, start_date, end_date) VALUES ('2025-Odd', '2025-11-30', '2025-07-01');
ERROR: new row for relation "semesters" violates check constraint "semesters_check"-- duplicate primary key
INSERT INTO inter.departments (dept_id, dept_name, dept_code) VALUES (1, 'Physics', 'PH');
ERROR: duplicate key value violates unique constraint "departments_pkey"
DETAIL: Key (dept_id)=(1) already exists.
-- NULL in part of a primary key
INSERT INTO inter.prerequisites (course_id, prereq_course_id) VALUES (NULL, 1);
ERROR: null value in column "course_id" of relation "prerequisites" violates not-null constraintReferential integrity also decides what happens to the children when a parent row is deleted. Our schema uses two actions β SET NULL and CASCADE:
BEGIN;
DELETE FROM inter.departments WHERE dept_code = 'MA';
SELECT full_name, dept_id FROM inter.students WHERE full_name = 'Fatima Rahman';
full_name | dept_id
---------------+---------
Fatima Rahman | <- NULL: students.dept_id is ON DELETE SET NULL
ROLLBACK;BEGIN;
DELETE FROM inter.courses WHERE course_code = 'DA301';
SELECT (SELECT COUNT(*) FROM inter.course_offerings) AS offerings,
(SELECT COUNT(*) FROM inter.enrollments) AS enrollments,
(SELECT COUNT(*) FROM inter.prerequisites) AS prerequisites;
offerings | enrollments | prerequisites
-----------+-------------+---------------
3 | 4 | 2 <- was 4, 6 and 3
ROLLBACK;INSERT INTO inter.prerequisites (course_id, prereq_course_id)
SELECT course_id, course_id FROM inter.courses WHERE course_code = 'CS101';
ERROR: new row for relation "prerequisites" violates check constraint "prerequisites_check"| ON DELETE action | What happens to child rows |
|---|---|
| NO ACTION / RESTRICT (default) | The delete is refused while children exist |
| CASCADE | The child rows are deleted too |
| SET NULL | The foreign key in the child rows becomes NULL |
| SET DEFAULT | The foreign key becomes its default value |
- βΈThree integrity rules: domain, entity (key), referential.
- βΈEntity integrity: a primary key is unique and never NULL. Referential integrity: a foreign key matches an existing key or is NULL.
- βΈON DELETE CASCADE / SET NULL / RESTRICT decide what happens to children.
2.9 Database Objects: Schema & Non-schema
schema.object. Non-schema objects are global β they belong to the whole database server, not to any schema.| Examples in PostgreSQL | Created with | |
|---|---|---|
| Schema objects | Tables, views, materialized views, sequences, indexes, functions and procedures, triggers, types | CREATE TABLE / VIEW / SEQUENCE / INDEX / FUNCTION β¦ |
| Non-schema (global) objects | Databases, roles (users and groups), tablespaces | CREATE DATABASE / ROLE / TABLESPACE |
SELECT CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view'
WHEN 'm' THEN 'materialized view'
WHEN 'S' THEN 'sequence' WHEN 'i' THEN 'index' END AS object_type,
COUNT(*) AS how_many
FROM pg_class c
WHERE c.relnamespace = 'inter'::regnamespace
GROUP BY 1
ORDER BY 1;
object_type | how_many
-------------------+----------
index | 16 <- one behind every PRIMARY KEY and UNIQUE
materialized view | 1
sequence | 7 <- one behind every SERIAL column
table | 8
view | 3SELECT datname FROM pg_database WHERE NOT datistemplate; -- databases: postgres, university_lab, β¦
SELECT rolname FROM pg_roles WHERE rolname NOT LIKE 'pg\_%'; -- roles: postgres, β¦
SELECT spcname FROM pg_tablespace; -- tablespaces: pg_default, pg_global- βΈSchema objects: tables, views, sequences, indexes, functions, triggers β named schema.object.
- βΈNon-schema objects: databases, roles, tablespaces β shared by the whole server.
2.10 Functional Dependency
X β Y (βX functionally determines Yβ) holds when any two rows that have the same value of X also have the same value of Y. X is the determinant; Y is the dependent.FDs come from the meaning of the data β the rules of the university β not from the rows that happen to be stored today. Sample data can show that an FD is broken (one counter-example is enough), but it can never prove that an FD holds.
Our running example is the enrollment register: all enrollment data kept in one wide table (you build it in 2.11).
register(student_email, student_name, dept_code, dept_name,
course_code, course_title, credits, semester)
F1: student_email β student_name, dept_code each student has one name and one department
F2: dept_code β dept_name each department code has one name
F3: course_code β course_title, credits each course has one title and one credit valueTypes of functional dependency
| Type | Meaning | Example |
|---|---|---|
| Trivial | Y is a subset of X β true in every relation | student_email, course_code β course_code |
| Non-trivial | Y has at least one attribute not in X | student_email β student_name |
| Full | Y depends on the whole of X; drop any attribute of X and the FD fails | (student_id, offering_id) β enrolled_on in enrollments β neither the student nor the offering alone fixes the date |
| Partial | A non-prime attribute depends on only part of a candidate key β removed by 2NF | course_title depends on course_code, only part of the register's key |
| Transitive | X β Y and Y β Z, where Y is not a key, give X β Z β removed by 3NF | student_email β dept_code β dept_name |
Armstrong's axioms
Given some FDs, which others must also hold? Armstrong's axioms are the rules for deriving them. They are sound (they derive only FDs that really hold) and complete (they derive every FD that holds).
| Rule | Statement | On the register |
|---|---|---|
| Reflexivity | If Y β X, then X β Y | student_email, course_code β course_code |
| Augmentation | If X β Y, then XZ β YZ | F3 gives course_code, semester β course_title, credits, semester |
| Transitivity | If X β Y and Y β Z, then X β Z | F1 and F2 give student_email β dept_name |
| Union (derived) | If X β Y and X β Z, then X β YZ | course_code β course_title and course_code β credits give F3 |
| Decomposition (derived) | If X β YZ, then X β Y and X β Z | F1 gives student_email β dept_code |
| Pseudo-transitivity (derived) | If X β Y and WY β Z, then WX β Z | If each department had one advisor per semester, dept_code, semester β advisor; with F1 (student_email β dept_code) this gives student_email, semester β advisor |
The first three are the axioms; union, decomposition and pseudo-transitivity are proved from them. The set of every FD that can be derived from a set F is the closure of F, written FβΊ.
Attribute closure and finding keys
Algorithm: start with result = X. Repeat: for every FD A β B in F, if A is already inside result, add B to result. Stop when a full pass adds nothing.
{student_email, course_code}βΊ
start {student_email, course_code}
F1 adds student_name, dept_code
F2 adds dept_name (dept_code is now in the set)
F3 adds course_title, credits
result every attribute except semester -> NOT a super key
{student_email, course_code, semester}βΊ
result all 8 attributes -> a super key
Is it minimal? student_email, course_code and semester never appear on the
right of any FD, so nothing else can produce them: every key must contain
all three. (student_email, course_code, semester) is the only candidate key.| Use of XβΊ | How |
|---|---|
| Does X β Y follow from F? | Yes if Y β XβΊ β no need to list all of FβΊ |
| Is X a super key? | Yes if XβΊ contains every attribute |
| Is X a candidate key? | X is a super key, and no proper subset of X is one |
| Shortcut | An attribute that is on the right of no FD must be in every candidate key |
A minimal (canonical) cover of F is a smallest set of FDs with the same closure: each right side has one attribute, no FD can be derived from the others, and no left side has an unnecessary attribute. Adding student_email β dept_name to F would change nothing β it follows from F1 and F2 by transitivity β so a minimal cover leaves it out.
An FD X β Y is broken if some value of X appears with more than one value of Y. Group by X and count the distinct values of Y. The view v_offering_roster joins courses, semesters, faculty and students, so it repeats values the way the register does:
SELECT course_code
FROM inter.v_offering_roster
GROUP BY course_code
HAVING COUNT(DISTINCT title) > 1;
course_code
-------------
(0 rows) <- no counter-example in the dataSELECT semester, COUNT(DISTINCT faculty) AS faculty_count,
string_agg(DISTINCT faculty, ', ') AS faculty
FROM inter.v_offering_roster
GROUP BY semester
HAVING COUNT(DISTINCT faculty) > 1;
semester | faculty_count | faculty
----------+---------------+----------------------------------
2024-Odd | 2 | Dr. Nisha Varma, Dr. Rajesh Iyer <- one counter-example: the FD does not holdIn a well-designed table, every FD has a key as its determinant, so the DBMS enforces it with a PRIMARY KEY or UNIQUE constraint. email is UNIQUE in students, so email β full_name, join_year, dept_id can never be broken:
INSERT INTO inter.students (full_name, email, join_year)
VALUES ('Aarav M.', 'aarav@duk.ac.in', 2025);
ERROR: duplicate key value violates unique constraint "students_email_key"
DETAIL: Key (email)=(aarav@duk.ac.in) already exists.An FD whose determinant is not a key β like dept_code β dept_name inside the register β has no constraint to enforce it. Normalization (2.11) fixes that by splitting the table until every determinant is a key.
- βΈX β Y: rows that agree on X agree on Y. FDs come from the rules of the data; the data can only disprove one.
- βΈTypes: trivial / non-trivial; full / partial (removed by 2NF) / transitive (removed by 3NF).
- βΈArmstrongβs axioms: reflexivity, augmentation, transitivity; derived: union, decomposition, pseudo-transitivity.
- βΈXβΊ = everything X determines. X is a super key if XβΊ is all attributes; a candidate key if it is also minimal.
2.11 Normalization (1NF β BCNF)
Why: the three anomalies
Suppose all enrollment data were kept in one wide table β an βenrollment registerβ. You can build exactly that as a temporary table, which disappears when you disconnect:
CREATE TEMP TABLE register AS
SELECT s.email AS student_email, s.full_name AS student_name,
d.dept_code, d.dept_name,
c.course_code, c.title AS course_title, c.credits,
sem.name AS semester
FROM inter.enrollments e
JOIN inter.students s ON s.student_id = e.student_id
LEFT JOIN inter.departments d ON d.dept_id = s.dept_id
JOIN inter.course_offerings o ON o.offering_id = e.offering_id
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters sem ON sem.semester_id = o.semester_id;
SELECT student_name, dept_name, course_code, course_title, credits
FROM register ORDER BY student_name, course_code;
student_name | dept_name | course_code | course_title | credits
-----------------+------------------+-------------+-----------------------------+---------
Aarav Menon | Computer Science | CS101 | Introduction to Programming | 4
Aarav Menon | Computer Science | CS201 | Database Systems | 4
Ananya Krishnan | Data Analytics | DA301 | Data Analytics | 4
Diya Nair | Data Analytics | CS201 | Database Systems | 4
Diya Nair | Data Analytics | DA301 | Data Analytics | 4
Kevin Thomas | Computer Science | CS201 | Database Systems | 4βDatabase Systemsβ is stored three times and βComputer Scienceβ three times. Now watch what goes wrong:
SELECT full_name FROM inter.students
WHERE email NOT IN (SELECT student_email FROM register)
ORDER BY 1;
full_name
---------------
Fatima Rahman <- not in the register at all:
Rohan Pillai a row needs a course_codeUPDATE register SET course_title = 'Database Management Systems'
WHERE course_code = 'CS201' AND student_email = 'aarav@duk.ac.in';
SELECT DISTINCT course_code, course_title FROM register WHERE course_code = 'CS201';
course_code | course_title
-------------+-----------------------------
CS201 | Database Management Systems
CS201 | Database Systems <- one course, two titlesDELETE FROM register WHERE student_email = 'kevin@duk.ac.in';
SELECT COUNT(*) AS rows_about_kevin FROM register WHERE student_name = 'Kevin Thomas'; -- 0
-- Kevin's only enrollment is gone, and with it his name and department.The register's functional dependencies
As worked out in 2.10, the register's only candidate key is (student_email, course_code, semester), and its functional dependencies are:
student_email β student_name, dept_codedept_code β dept_namecourse_code β course_title, credits
The normal forms
| Normal form | Rule | Removes |
|---|---|---|
| 1NF | Every cell holds one atomic value; no repeating groups; the table has a primary key | Multi-valued and composite cells |
| 2NF | In 1NF, and no non-prime attribute depends on only part of a candidate key | Partial dependencies |
| 3NF | In 2NF, and no non-prime attribute depends on another non-prime attribute. Formally: for every FD X β A, X is a super key or A is prime | Transitive dependencies |
| BCNF | For every non-trivial FD X β Y, X is a super key | Any dependency whose determinant is not a key |
Worked example: register β university_lab
| Step | Tables | Why |
|---|---|---|
| Unnormalised | student(email, name, dept_code, dept_name, courses = βCS201 Database Systems 4; DA301 Data Analytics 4β) | The courses cell holds a list β a repeating group |
| 1NF | register(student_email, course_code, semester, student_name, dept_code, dept_name, course_title, credits) | One course per row; every cell atomic |
| 2NF | student(email, name, dept_code, dept_name)course(course_code, title, credits)enrollment(email, course_code, semester) | name and dept depend only on email; title and credits only on course_code β partial dependencies removed |
| 3NF | student(email, name, dept_code)department(dept_code, dept_name)course(course_code, title, credits)enrollment(email, course_code, semester) | email β dept_code β dept_name was transitive β removed |
These are exactly the tables of university_lab: students, departments, courses and enrollments. (Our real schema adds course_offerings because a course in a semester also has its own faculty, room and capacity.) Every determinant in these tables is a key, so they are also in BCNF.
3NF but not BCNF β the classic case
Rules: each faculty member teaches only one course, and a student takes a given course from only one faculty member. In teaches(student, course_code, faculty) the FDs are (student, course_code) β faculty and faculty β course_code.
Every attribute is prime, so the table is in 3NF. But faculty β course_code has a determinant that is not a super key, so it breaks BCNF. Fix: faculty_course(faculty, course_code) and student_faculty(student, faculty).
Finding the highest normal form of a table: list all candidate keys; mark prime and non-prime attributes; then test 1NF, 2NF, 3NF and BCNF in order. If the table fails normal form n, its highest normal form is n β 1.
Denormalization is the reverse β deliberately joining tables back together for faster reads. Views give you the joined picture without storing it twice: v_offering_roster is the register, rebuilt on demand.
- βΈAnomalies: insertion (canβt add), modification (copies disagree), deletion (lose other facts).
- βΈ1NF: atomic values. 2NF: no partial dependency. 3NF: no transitive dependency. BCNF: every determinant is a super key.
- βΈEach step splits a table along a functional dependency; the joins rebuild the original.
2.12 Codd's 12 Rules
| # | Rule | Meaning | In PostgreSQL |
|---|---|---|---|
| 0 | Foundation rule | The system must manage its databases entirely through its relational capabilities | Everything is done with SQL on tables |
| 1 | Information rule | All information β including metadata β is stored as values in tables | Even the catalog is tables: pg_class, information_schema |
| 2 | Guaranteed access | Every value is reachable by table name + primary key value + column name | SELECT email FROM inter.students WHERE student_id = 3; |
| 3 | Systematic treatment of NULL | NULL (missing / unknown / not applicable) is handled uniformly, distinct from 0 or empty text | NULL = NULL is NULL; use IS NULL |
| 4 | Active online catalog | The databaseβs description is stored in tables that authorised users query with the same language | information_schema.tables |
| 5 | Comprehensive data sub-language | One language supports data definition, manipulation, integrity, authorisation and transactions | SQL: DDL, DML, DCL, TCL |
| 6 | View updating | Every view that is theoretically updatable can be updated by the system | Single-table views are updatable automatically |
| 7 | High-level insert, update, delete | Insert, update and delete work on sets of rows, not just one row at a time | One UPDATE changes many rows; UNION, INTERSECT, EXCEPT |
| 8 | Physical data independence | Changing storage does not affect applications | Add an index or move a tablespace β queries unchanged (Module 1, 1.4) |
| 9 | Logical data independence | Changing the logical structure does not affect applications | Add a column β views keep working (Module 1, 1.4) |
| 10 | Integrity independence | Integrity constraints are defined in the catalog, not in application programs | CHECK, PRIMARY KEY, FOREIGN KEY |
| 11 | Distribution independence | Users need not know whether the data is distributed | Partly β foreign data wrappers, replicas (Module 4A) |
| 12 | Non-subversion | A low-level interface must not bypass the integrity and security rules | Constraints and privileges apply to every client |
SELECT NULL = NULL AS equals_null, NULL IS NULL AS is_null;
equals_null | is_null
-------------+---------
| t <- the comparison gives NULL ("unknown"), not trueSELECT table_name, table_type
FROM information_schema.tables
WHERE table_schema = 'inter'
ORDER BY 1;
table_name | table_type
---------------------+------------
course_offerings | BASE TABLE
courses | BASE TABLE
departments | BASE TABLE
enrollments | BASE TABLE
faculty | BASE TABLE
myfirstview | VIEW
prerequisites | BASE TABLE
semesters | BASE TABLE
students | BASE TABLE
v_offering_roster | VIEW
v_seat_availability | VIEWCREATE VIEW inter.v_cs_courses AS
SELECT course_id, course_code, title, credits
FROM inter.courses
WHERE dept_id = (SELECT dept_id FROM inter.departments WHERE dept_code = 'CS');
UPDATE inter.v_cs_courses SET credits = 4 WHERE course_code = 'CS210';
-- UPDATE 1 <- the change goes through to inter.courses
UPDATE inter.v_offering_roster SET faculty = 'Someone' WHERE offering_id = 1;
-- ERROR: cannot update view "v_offering_roster"
-- DETAIL: Views that do not select from a single table or view are not automatically updatable.
-- tidy up
UPDATE inter.courses SET credits = 3 WHERE course_code = 'CS210';
DROP VIEW inter.v_cs_courses;- βΈRules 0β12: foundation, information, guaranteed access, NULLs, catalog, sub-language, view updating, set-level operations, physical / logical / integrity / distribution independence, non-subversion.
- βΈRule 1 and Rule 4 together: everything, even the description of the database, is a table you can query.
Module 2 at a glance
| Topic | One-line answer |
|---|---|
| Data models | Conceptual (what) β logical (structure, keys) β physical (DBMS-specific). |
| Record-based models | Hierarchical (tree), network (graph), relational (tables). |
| E-R model | Entities, attributes (6 kinds), relationships with degree, cardinality and participation. |
| E-R β tables | Entity β table; 1:N β FK on the N side; M:N β junction table; multi-valued β own table. |
| Relational model | Relation = table, tuple = row, attribute = column; degree = columns, cardinality = rows. |
| Keys | Super β candidate β primary (+ alternate); foreign keys refer to primary keys. |
| Integrity | Domain, entity (key), referential β enforced by types, CHECK, PK, FK. |
| Schema objects | Tables, views, sequences, indexes⦠vs global databases, roles, tablespaces. |
| Functional dependency | X β Y: equal X means equal Y. Armstrongβs axioms derive FDs; XβΊ finds keys. |
| Normalization | 1NF atomic β 2NF no partial β 3NF no transitive β BCNF every determinant a key. |
| Coddβs rules | 13 rules (0β12) defining a fully relational DBMS. |
Practice on university_lab
Degree and cardinality
EasySpot the candidate keys
MediumFollow a cascade
MediumClosure and candidate keys
MediumNormalize it yourself
HardExam-style questions
- Define entity, attribute and relationship.
- Differentiate a candidate key and a primary key.
- What is a weak entity? Give an example.
- Define functional dependency. Give one trivial and one non-trivial FD.
- State Armstrong's axioms.
- State the referential integrity rule.
- What are the degree and cardinality of a relation?
- Compare conceptual, logical and physical data models.
- Draw an E-R diagram for a university and convert it into tables.
- Explain the types of attributes with an E-R diagram.
- Explain the types of functional dependency. Find the attribute closure and candidate keys of a given relation.
- Explain 1NF, 2NF, 3NF and BCNF with an example.
- Explain insertion, deletion and modification anomalies.
- Explain Codd's rules.
