Digital University Kerala

SQL Lab Notes

PostgreSQL for Data Analytics

Course Instructor:Dr. Ajith Kumar
Academic Year: 2026-2028
Class Notes/Module 2
Module 2 Β· CO2 Β· Lecture notes: Module II Β· Labs 2, 3, 5

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.

🎯 After this module you can
  • β–Έ 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
🏫 Examples use

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.

Set up the database first β†’

2.1 Data Models: Conceptual, Logical, Physical

πŸ“– Definition Β· Data model
A collection of concepts for describing the structure of a database β€” what data it holds, how the data is related, and the rules it must obey. Data models give us the levels of abstraction we use to design a database.

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:

ConceptualLogicalPhysical
AnswersWHAT the system containsHOW it is structured β€” independent of any DBMSHOW it is built in a specific DBMS
Created byBusiness stakeholders, data architectsData architects, business analystsDBAs 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 3NFInherited from the logical model
Conceptual
STUDENT β€”enrolls inβ€” COURSE OFFERING
Only the things and how they relate. No attributes, no keys.
Logical
Student(student_id, name, email)
Enrollment(enrollment_id, student_id β†’ Student, offering_id β†’ Offering, enrolled_on)
Offering(offering_id, room, capacity)
Attributes and keys, still DBMS-independent.
Physical (PostgreSQL)
inter.students(student_id SERIAL PRIMARY KEY, full_name VARCHAR(100) NOT NULL, email VARCHAR(120) UNIQUE …)
Real types, constraints, indexes, schema name.
Figure 2.1 β€” The same part of CampusDB in the three data models
🏫 Example · the physical model is what the DBMS stores

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:

Physical model of inter.courses, read from the catalogsql
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
βœ… Remember
  • β–Έ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

πŸ“– Definition
Record-based models describe the database as fixed-format records of several types. The three classic ones are the hierarchical, network and relational models. (The E-R model, by contrast, is an object-based conceptual model.)
ModelStructureRelationshipsExample systemsMain weakness
HierarchicalTree: each child record has exactly one parentOnly 1:N (parent β†’ children)IBM IMS (1960s)M:N needs duplicated records; access only from the root down
NetworkGraph: records linked by owner–member sets1:N and M:N (through link records)CODASYL / IDMSPrograms navigate pointers; structure changes break programs
RelationalTables of rows and columnsAny, through matching key valuesPostgreSQL, Oracle, MySQLJoins cost work at query time (solved by optimisers and indexes)
Hierarchical (tree)
Computer Science
 β”” CS201 Database Systems
    β”” 2024-Odd, LH-1
       β”œ Aarav
       β”œ Diya
       β”” Kevin
 β”” CS101 Intro to Programming
    β”” 2024-Odd, LH-3
       β”” Aarav   ← stored again
Network (graph)
STUDENT Aarav ─┐
               β”œβ”€β–Ί ENROLLMENT ◄─┐
               └─► ENROLLMENT ◄─┼─ OFFERING CS101
                                β”‚
STUDENT Diya ───► ENROLLMENT ◄──┴─ OFFERING CS201

Each arrow is a stored pointer
(an owner–member set).
Relational (tables)
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.
Figure 2.2 β€” CampusDB enrollments in the three record-based models
βœ… Remember
  • β–Έ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

πŸ“– Definition Β· E-R model
The Entity-Relationship model (Peter Chen, 1976) describes the real world as entities, their attributes, and the relationships among them. It is the standard tool for conceptual design and is drawn as an E-R diagram.
  • 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 typeMeaningExample (student)
SimpleCannot be divided further (atomic)email
CompositeMade of several simple attributesname = first_name + last_name
Single-valuedHolds one value per entitydate_of_birth
Multi-valuedCan hold several values per entityphone β€” a student may have two numbers
DerivedNot stored; calculated from other attributesage, from date_of_birth
KeyUniquely identifies each entitystudent_id
STUDENTstudent_idemailphonedate_of_birthagenamefirst_namelast_name
underlined = keydouble ellipse = multi-valueddashed ellipse = derivedbranching ellipses = composite
Figure 2.3 β€” The STUDENT entity with every kind of attribute (Chen notation)
SymbolMeansSymbolMeans
Entity setWeak entity set
AttributeKey attribute
Multi-valued attributeDerived attribute
Relationship setIdentifying relationship (of a weak entity)
Partial participationTotal participation
🏫 Example · design choices in inter.students

The real inter.students table made simple choices for each kind of attribute:

Attribute kindWhat we did in university_lab
Keystudent_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.
DerivedNot stored. Example: seats_left in v_seat_availability is calculated each time from capacity and enrollments.
βœ… Remember
  • β–Έ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

πŸ“– Definition Β· Relationship
An association among entities β€” for example, Diya enrolls in CS201 (2024-Odd). A relationship set is all associations of the same type, drawn as a diamond.
  • 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).
DEPARTMENTSTUDENTFACULTYCOURSECOURSE OFFERINGSEMESTERbelongs toworks inownsenrolls inteachesoffered asruns inrequires1N1N1NMN1N1NN1MN
Double line = total participation (every offering has a course and a semester). Numbers and letters on the lines = cardinality.
Figure 2.4 β€” E-R diagram of CampusDB (attributes omitted for clarity)
🏫 Example · every relationship in the inter schema
RelationshipBetweenDegreeCardinalityParticipation
belongs toSTUDENT – DEPARTMENTBinaryN:1Partial (dept_id may be NULL)
works inFACULTY – DEPARTMENTBinaryN:1Partial
ownsCOURSE – DEPARTMENTBinaryN:1Partial
requiresCOURSE – COURSEUnary (recursive)M:NPartial β€” not every course has a prerequisite
offered asCOURSE – COURSE OFFERINGBinary1:NTotal for offerings (course_id NOT NULL)
runs inCOURSE OFFERING – SEMESTERBinaryN:1Total for offerings (semester_id NOT NULL)
teachesFACULTY – COURSE OFFERINGBinary1:NPartial (faculty_id may be NULL)
enrolls inSTUDENT – COURSE OFFERINGBinaryM:NPartial β€” 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.

βœ… Remember
  • β–Έ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

πŸ“– Definition
Logical design converts each part of the E-R diagram into relations (tables) using a fixed set of mapping rules. This is the work of Lab 2.
E-R constructBecomesIn university_lab
Strong entityA table; its key attribute becomes the PRIMARY KEYSTUDENT β†’ students(student_id PK, …)
Simple attributeA columnemail β†’ email VARCHAR(120)
Composite attributeOne column per component (or one combined column)name β†’ full_name (combined)
Multi-valued attributeA new table: owner key + value, both in the primary keyphone β†’ student_phones(student_id, phone)
Derived attributeNot stored; calculated in a query or viewseats_left in v_seat_availability
Weak entityA table holding the owner's key as a foreign key; owner key + partial key = primary keyassessments(offering_id, name) β€” in the Advanced lab
1:N relationshipA foreign key on the N sidecourse_offerings.semester_id β†’ semesters
1:1 relationshipA foreign key on either side, made UNIQUEe.g. departments.head_faculty_id UNIQUE β†’ faculty
M:N relationshipA junction table with both foreign keys; together they identify a rowenrollments(student_id, offering_id)
Recursive relationshipForeign key(s) back to the same tableprerequisites(course_id, prereq_course_id)
🏫 Example · a recursive M:N and a multi-valued attribute
The recursive 'requires' relationship, read back from prerequisitessql
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  | CS201
Mapping the multi-valued attribute 'phone' to its own tablesql
CREATE 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
βœ… Remember
  • β–Έ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

πŸ“– Definition
The relational model (E. F. Codd, 1970) stores all data in relations β€” tables of rows and columns β€” and is based on set theory and first-order predicate logic. It is the most widely used data model.
Formal termEveryday termMeaningIn inter.students
RelationTableA set of tuples with the same attributesinter.students
TupleRow / recordOne entity’s dataDiya’s row
AttributeColumn / fieldOne named propertyemail
DomainData type + rulesThe set of allowed values of an attributejoin_year: integers
DegreeNumber of columnsHow many attributes a relation has5
CardinalityNumber of rowsHow many tuples it holds right now6
Relation schemaTable definitionThe name and attributes: students(student_id, full_name, email, join_year, dept_id)\d inter.students
Relation instanceTable contentsThe set of tuples at a given momentSELECT * FROM inter.students
Relation keyKeyAttribute(s) that identify each tuple uniquelystudent_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.

🏫 Example · degree and cardinality
Degree = columns, cardinality = rowssql
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
βœ… Remember
  • β–Έ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

πŸ“– Definition Β· Key
An attribute, or set of attributes, whose values identify each tuple of a relation uniquely.
KeyDefinitionIn university_lab
Super keyAny set of attributes that identifies rows uniquely (may contain extra attributes)(student_id), (email), (student_id, email), (email, full_name)…
Candidate keyA minimal super key β€” remove any attribute and it stops being uniquestudent_id and email in students
Primary keyThe candidate key chosen to identify rows; it can never be NULLstudent_id
Alternate keyA candidate key that was not chosen as primary β€” enforced with UNIQUEemail (UNIQUE)
Composite keyA key made of two or more attributes(course_id, prereq_course_id) in prerequisites
Foreign keyAttribute(s) that refer to the primary key of another (or the same) relationenrollments.student_id β†’ students
Surrogate keyAn artificial key with no business meaning, usually generatedstudent_id (SERIAL)
Natural keyA key that exists in the real worldcourse_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).

🏫 Example · every primary and alternate key in the inter schema
Keys, read from the catalogsql
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).

βœ… Remember
  • β–Έ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

πŸ“– Definition
Integrity constraints are conditions every relation instance must satisfy for the data to be valid. The DBMS checks them on every INSERT, UPDATE and DELETE and rejects any change that would break one.
Integrity ruleStates that…Enforced in SQL by
Domain integrityEvery value comes from its attribute’s domainData types, NOT NULL, CHECK, DEFAULT
Entity integrity (key constraint)Every row is uniquely identified; no part of a primary key may be NULLPRIMARY KEY, UNIQUE
Referential integrityA foreign key value must match an existing primary key value β€” or be NULLFOREIGN KEY … REFERENCES, with ON DELETE / ON UPDATE actions
🏫 Example · the database rejects every kind of invalid data
Domain integritysql
-- 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"
Entity integritysql
-- 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 constraint

Referential integrity also decides what happens to the children when a parent row is deleted. Our schema uses two actions β€” SET NULL and CASCADE:

ON DELETE SET NULL β€” the student stays, without a departmentsql
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;
ON DELETE CASCADE β€” the children are deleted toosql
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;
A CHECK on a recursive relationship β€” a course can't require itselfsql
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 actionWhat happens to child rows
NO ACTION / RESTRICT (default)The delete is refused while children exist
CASCADEThe child rows are deleted too
SET NULLThe foreign key in the child rows becomes NULL
SET DEFAULTThe foreign key becomes its default value
βœ… Remember
  • β–Έ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

πŸ“– Definition
Schema objects belong to a schema, so they are named schema.object. Non-schema objects are global β€” they belong to the whole database server, not to any schema.
Examples in PostgreSQLCreated with
Schema objectsTables, views, materialized views, sequences, indexes, functions and procedures, triggers, typesCREATE TABLE / VIEW / SEQUENCE / INDEX / FUNCTION …
Non-schema (global) objectsDatabases, roles (users and groups), tablespacesCREATE DATABASE / ROLE / TABLESPACE
🏫 Example · what lives inside the inter schema, and what doesn't
Schema objects in intersql
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              |        3
Non-schema objects β€” global to the serversql
SELECT 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
βœ… Remember
  • β–Έ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

πŸ“– Definition Β· Functional dependency (FD)
In a relation R, 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).

The register and the rules it followstext
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 value

Types of functional dependency

TypeMeaningExample
TrivialY is a subset of X β€” true in every relationstudent_email, course_code β†’ course_code
Non-trivialY has at least one attribute not in Xstudent_email β†’ student_name
FullY 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
PartialA non-prime attribute depends on only part of a candidate key β€” removed by 2NFcourse_title depends on course_code, only part of the register's key
TransitiveX β†’ Y and Y β†’ Z, where Y is not a key, give X β†’ Z β€” removed by 3NFstudent_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).

RuleStatementOn the register
ReflexivityIf Y βŠ† X, then X β†’ Ystudent_email, course_code β†’ course_code
AugmentationIf X β†’ Y, then XZ β†’ YZF3 gives course_code, semester β†’ course_title, credits, semester
TransitivityIf X β†’ Y and Y β†’ Z, then X β†’ ZF1 and F2 give student_email β†’ dept_name
Union (derived)If X β†’ Y and X β†’ Z, then X β†’ YZcourse_code β†’ course_title and course_code β†’ credits give F3
Decomposition (derived)If X β†’ YZ, then X β†’ Y and X β†’ ZF1 gives student_email β†’ dept_code
Pseudo-transitivity (derived)If X β†’ Y and WY β†’ Z, then WX β†’ ZIf 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

πŸ“– Definition Β· Attribute closure X⁺
The set of all attributes that X determines, using the FDs in F.

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.

Worked example: is (student_email, course_code) a key of the register?text
{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
ShortcutAn 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.

🏫 Example · testing FDs against the data

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:

course_code β†’ title: does any course code have two titles?sql
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 data
semester β†’ faculty: does each semester have only one faculty member?sql
SELECT 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 hold

In 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:

A second student with the same email is refusedsql
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.

βœ… Remember
  • β–Έ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)

πŸ“– Definition
Normalization is the process of organising tables so that each table holds facts about one thing. It removes redundancy and the update anomalies that redundancy causes, by splitting tables according to their functional dependencies.

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:

🏫 Example · anomalies in a denormalised register
One wide table (TEMP β€” your real tables are untouched)sql
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:

Insertion anomaly β€” students with no course can't be recordedsql
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_code
Modification (update) anomaly β€” change one copy, and the copies disagreesql
UPDATE 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 titles
Deletion anomaly β€” delete an enrollment, lose the studentsql
DELETE 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_code
  • dept_code β†’ dept_name
  • course_code β†’ course_title, credits

The normal forms

Normal formRuleRemoves
1NFEvery cell holds one atomic value; no repeating groups; the table has a primary keyMulti-valued and composite cells
2NFIn 1NF, and no non-prime attribute depends on only part of a candidate keyPartial dependencies
3NFIn 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 primeTransitive dependencies
BCNFFor every non-trivial FD X β†’ Y, X is a super keyAny dependency whose determinant is not a key

Worked example: register β†’ university_lab

StepTablesWhy
Unnormalisedstudent(email, name, dept_code, dept_name, courses = β€œCS201 Database Systems 4; DA301 Data Analytics 4”)The courses cell holds a list β€” a repeating group
1NFregister(student_email, course_code, semester, student_name, dept_code, dept_name, course_title, credits)One course per row; every cell atomic
2NFstudent(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
3NFstudent(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.

βœ… Remember
  • β–Έ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

πŸ“– Definition
In 1985 E. F. Codd published thirteen rules (numbered 0 to 12) that a DBMS must satisfy to be called fully relational. No commercial product meets all of them; PostgreSQL meets most.
#RuleMeaningIn PostgreSQL
0Foundation ruleThe system must manage its databases entirely through its relational capabilitiesEverything is done with SQL on tables
1Information ruleAll information β€” including metadata β€” is stored as values in tablesEven the catalog is tables: pg_class, information_schema
2Guaranteed accessEvery value is reachable by table name + primary key value + column nameSELECT email FROM inter.students WHERE student_id = 3;
3Systematic treatment of NULLNULL (missing / unknown / not applicable) is handled uniformly, distinct from 0 or empty textNULL = NULL is NULL; use IS NULL
4Active online catalogThe database’s description is stored in tables that authorised users query with the same languageinformation_schema.tables
5Comprehensive data sub-languageOne language supports data definition, manipulation, integrity, authorisation and transactionsSQL: DDL, DML, DCL, TCL
6View updatingEvery view that is theoretically updatable can be updated by the systemSingle-table views are updatable automatically
7High-level insert, update, deleteInsert, update and delete work on sets of rows, not just one row at a timeOne UPDATE changes many rows; UNION, INTERSECT, EXCEPT
8Physical data independenceChanging storage does not affect applicationsAdd an index or move a tablespace β€” queries unchanged (Module 1, 1.4)
9Logical data independenceChanging the logical structure does not affect applicationsAdd a column β€” views keep working (Module 1, 1.4)
10Integrity independenceIntegrity constraints are defined in the catalog, not in application programsCHECK, PRIMARY KEY, FOREIGN KEY
11Distribution independenceUsers need not know whether the data is distributedPartly β€” foreign data wrappers, replicas (Module 4A)
12Non-subversionA low-level interface must not bypass the integrity and security rulesConstraints and privileges apply to every client
🏫 Example · rules 3, 4 and 6 in action
Rule 3 β€” NULL is not a value, so = cannot match itsql
SELECT NULL = NULL AS equals_null, NULL IS NULL AS is_null;

 equals_null | is_null
-------------+---------
             | t            <- the comparison gives NULL ("unknown"), not true
Rule 4 β€” the catalog is queried with ordinary SQLsql
SELECT 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 | VIEW
Rule 6 β€” a single-table view is updatable; a multi-table view is not (automatically)sql
CREATE 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;
βœ… Remember
  • β–Έ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

TopicOne-line answer
Data modelsConceptual (what) β†’ logical (structure, keys) β†’ physical (DBMS-specific).
Record-based modelsHierarchical (tree), network (graph), relational (tables).
E-R modelEntities, attributes (6 kinds), relationships with degree, cardinality and participation.
E-R β†’ tablesEntity β†’ table; 1:N β†’ FK on the N side; M:N β†’ junction table; multi-valued β†’ own table.
Relational modelRelation = table, tuple = row, attribute = column; degree = columns, cardinality = rows.
KeysSuper βŠ‡ candidate β†’ primary (+ alternate); foreign keys refer to primary keys.
IntegrityDomain, entity (key), referential β€” enforced by types, CHECK, PK, FK.
Schema objectsTables, views, sequences, indexes… vs global databases, roles, tablespaces.
Functional dependencyX β†’ Y: equal X means equal Y. Armstrong’s axioms derive FDs; X⁺ finds keys.
Normalization1NF atomic β†’ 2NF no partial β†’ 3NF no transitive β†’ BCNF every determinant a key.
Codd’s rules13 rules (0–12) defining a fully relational DBMS.

Practice on university_lab

1

Degree and cardinality

Easy
Find the degree and the cardinality of inter.courses.
2

Spot the candidate keys

Medium
List the candidate keys of inter.departments and say which one is the primary key and which are alternate keys. Check your answer against the catalog.
3

Follow a cascade

Medium
Inside a transaction, delete the semester '2024-Odd'. How many offerings and enrollments are left, and why? Roll back at the end.
4

Closure and candidate keys

Medium
R(A, B, C, D, E) has the FDs A β†’ B, B β†’ C and CD β†’ E. Find {A, D}⁺. Is AD a candidate key? Is it the only one?
5

Normalize it yourself

Hard
A faculty table is stored as faculty(email, full_name, dept_code, dept_name, courses_taught), where courses_taught holds a list such as 'CS101, CS201'. Which normal forms does it break? Write the 3NF tables.

Exam-style questions

Short answer (2 marks)
  1. Define entity, attribute and relationship.
  2. Differentiate a candidate key and a primary key.
  3. What is a weak entity? Give an example.
  4. Define functional dependency. Give one trivial and one non-trivial FD.
  5. State Armstrong's axioms.
  6. State the referential integrity rule.
  7. What are the degree and cardinality of a relation?
Long answer (5–10 marks)
  1. Compare conceptual, logical and physical data models.
  2. Draw an E-R diagram for a university and convert it into tables.
  3. Explain the types of attributes with an E-R diagram.
  4. Explain the types of functional dependency. Find the attribute closure and candidate keys of a given relation.
  5. Explain 1NF, 2NF, 3NF and BCNF with an example.
  6. Explain insertion, deletion and modification anomalies.
  7. Explain Codd's rules.