Digital University Kerala

SQL Lab Notes

PostgreSQL for Data Analytics

Course Instructor:Dr. Ajith Kumar
Academic Year: 2026-2028
Class Notes/Module 1
Module 1 Β· CO1 Β· Lecture notes: Module I Β· Lab 1

Module 1 Β· Introduction to Database Management Systems

What data, information and databases are; why we moved from files to a DBMS; how a DBMS is organised inside; what makes a transaction safe; and how clients talk to a database server. Every idea is shown on our class database, university_lab.

🎯 After this module you can
  • β–Έ Tell data from information, and a database from a DBMS
  • β–Έ List the problems of file systems and how a DBMS solves each
  • β–Έ Explain the three levels of abstraction and data independence
  • β–Έ State and demonstrate the ACID properties
  • β–Έ Compare file-server, 2-tier and 3-tier client-server models
  • β–Έ Name the components of a DBMS
🏫 Examples use

The inter schema of university_lab (8 tables + views), loaded with the Intermediate sample rows.

Set up the database first β†’

1.1 Data, Information, Database & DBMS

πŸ“– Definition Β· Data
Raw, unorganised facts β€” numbers, text, dates β€” that have no meaning on their own until they are processed. (From the Latin datum, β€œsomething given”.)
πŸ“– Definition Β· Information
Data that has been processed, organised or summarised in a context so that it is meaningful and useful for making decisions.
πŸ“– Definition Β· Database
An organised collection of inter-related data, stored so that it can be efficiently retrieved, inserted, updated and deleted. It is organised as tables, views, schemas and other objects.
πŸ“– Definition Β· DBMS
The software that creates and manages databases and controls every access to them β€” for example PostgreSQL, MySQL, Oracle and SQL Server.
TermSimple meaningIn our class database
DataA raw factthe value 2024 in the join_year column
InformationProcessed, meaningful dataβ€œ4 students joined in 2024”
DatabaseAn organised collection of related datauniversity_lab β€” schemas public, inter, event
DBMSSoftware that manages the databasePostgreSQL 17

A DBMS lets its users:

  • Define the structure of data β€” CREATE TABLE
  • Manipulate data β€” INSERT, UPDATE, DELETE
  • Retrieve data β€” SELECT
  • Control who may do what β€” GRANT, REVOKE
  • Administer the database β€” backup, restore, tuning
🏫 Example · data becomes information

Each row in inter.students is data β€” individual facts:

Data: the raw factssql
SELECT full_name, join_year
FROM inter.students
ORDER BY student_id;

    full_name    | join_year
-----------------+-----------
 Aarav Menon     |      2024
 Diya Nair       |      2024
 Rohan Pillai    |      2023
 Fatima Rahman   |      2024
 Kevin Thomas    |      2023
 Ananya Krishnan |      2024

Group and count the same rows and you get information an admissions office can act on:

Information: data processed into meaningsql
SELECT join_year, COUNT(*) AS students_admitted
FROM inter.students
GROUP BY join_year
ORDER BY join_year;

 join_year | students_admitted
-----------+-------------------
      2023 |                 2
      2024 |                 4

The v_seat_availability view goes one step further β€” it turns enrollment rows into a decision: CS201 and DA301 are full; open another section?

Information that supports a decisionsql
SELECT course_code, semester, capacity, enrolled, seats_left
FROM inter.v_seat_availability
ORDER BY offering_id;

 course_code | semester  | capacity | enrolled | seats_left
-------------+-----------+----------+----------+------------
 CS201       | 2024-Odd  |        3 |        3 |          0
 DA301       | 2024-Odd  |        2 |        2 |          0
 CS101       | 2024-Odd  |       40 |        1 |         39
 MA101       | 2024-Even |       30 |        0 |         30

And the database and DBMS themselves:

One database, three schemas β€” managed by PostgreSQLsql
-- the schemas inside university_lab   (psql shortcut: \dn)
SELECT schema_name FROM information_schema.schemata
WHERE schema_name IN ('public', 'inter', 'event')
ORDER BY schema_name;

 schema_name
-------------
 event
 inter
 public

-- the DBMS that manages it
SELECT version();
-- PostgreSQL 17.7 on x86_64-windows, compiled by msvc-19.44.35221, 64-bit
βœ… Remember
  • β–ΈData β†’ processing β†’ information.
  • β–ΈA database is the data; the DBMS is the software. university_lab is a database; PostgreSQL is the DBMS.
  • β–ΈOne database can hold many schemas; each schema holds tables, views and other objects.
  • β–ΈA DBMS lets users define, manipulate, retrieve and control data, and administer the database.

1.2 From File System to DBMS

πŸ“– Definition Β· File system approach
Each department stores its own data in its own files and uses its own programs to read them. There is no single shared copy and no central control.

Picture a university before it had a database. The Academics section, the Accounts section and the Hostel office each keep a spreadsheet with the student's roll number, name and phone number β€” plus their own columns such as fees paid or room number. This leads to six classic problems:

File system
academics.xlsx
Roll 102 Β· Diya Nair Β· 98470 11111 Β· CS201, DA301
accounts.xlsx
Roll 102 Β· Diya Nair Β· 98470 22222 Β· Fees paid
hostel.xlsx
Roll 102 Β· Diya N. Β· 98470 11111 Β· Room B-12

Three copies β†’ the phone numbers already disagree.

DBMS (one shared database)
inter.students β€” stored once
student_id 2 Β· Diya Nair Β· diya@duk.ac.in
enrollments
student_id 2
payments
student_id 2
hostel
student_id 2

One copy; everything else refers to it by key. (enrollments exists in university_lab; payments and hostel show how other sections would join in.)

Figure 1.1 β€” The same student in a file system (three copies) and in a DBMS (one copy, referenced by key)
ProblemIn a file systemHow the DBMS fixes it (university_lab)
Data redundancyDiya's phone number is stored in three files.Stored once in inter.students; other tables refer to her by student_id.
Data inconsistencyAccounts updates the phone; Hostel does not β€” the copies disagree.One copy means nothing to disagree with; constraints such as UNIQUE (email) reject bad data.
Difficult data accessYou must know which file holds the data and write a program to search 10,000 rows.One SQL query, by table name β€” the DBMS finds the data.
Unauthorised accessAnyone who can open the marks file can change it.Per-user permissions with GRANT / REVOKE (see 1.6).
No concurrent accessA file opened by one user is locked for everyone else.Many sessions read and write at the same time (PostgreSQL uses MVCC).
No backup and recoveryA deleted or corrupted file means the data is gone.pg_dump / pg_restore backups and automatic crash recovery.
🏫 Example · the DBMS refuses inconsistent data

A file would happily accept a second student with the same email, or an enrollment for a student who doesn't exist. The DBMS will not:

Duplicate email β†’ rejectedsql
INSERT INTO inter.students (full_name, email, join_year)
VALUES ('Aarav M', 'aarav@duk.ac.in', 2024);

ERROR:  duplicate key value violates unique constraint "students_email_key"
DETAIL:  Key (email)=(aarav@duk.ac.in) already exists.
Enrollment for a student who doesn't exist β†’ rejectedsql
INSERT INTO inter.enrollments (student_id, offering_id)
VALUES (999, 1);

ERROR:  insert or update on table "enrollments" violates foreign key constraint "enrollments_student_id_fkey"
DETAIL:  Key (student_id)=(999) is not present in table "students".
βœ… Remember
  • β–ΈSix file-system problems: redundancy, inconsistency, difficult access, unauthorised access, no concurrency, no backup/recovery.
  • β–ΈRedundancy causes inconsistency: many copies of the same fact drift apart.
  • β–ΈA DBMS keeps one integrated copy of the data and controls every access to it.

1.3 Three Levels of Data Abstraction

πŸ“– Definition Β· Data abstraction
Hiding the complex details of how data is stored, by describing the database at three levels β€” physical, logical and view. This is the ANSI/SPARC three-schema architecture, where the levels are called internal, conceptual and external.
View 1 Β· Faculty
v_offering_roster
View 2 Β· Admissions
v_seat_availability
View 3 Β· Class
myfirstview
View (external) level β€” what each user sees
Logical (conceptual) level β€” what is stored
8 tables in schema inter: departments, semesters, students, faculty, courses, prerequisites, course_offerings, enrollments β€” with their keys and constraints
Physical (internal) level β€” how it is stored
Data files under the server's data directory (e.g. base/16386/16434), 8 kB pages, B-tree indexes, the WAL
Figure 1.2 β€” The three levels of data abstraction (ANSI/SPARC three-schema architecture)
  • Physical (internal) level β€” the lowest level: how data is actually stored. Files and blocks on disk, file organisation, and access paths such as B+ tree indexes and hashing. Only the DBMS (and the DBA tuning it) works here.
  • Logical (conceptual) level β€” what data is stored and how it is related: the tables, columns, data types, keys and constraints of the whole database. Database designers and DBAs work here.
  • View (external) level β€” the highest level: the part of the database that a particular user sees. There can be many views of the same database; storage details are hidden completely.
🏫 Example · one table seen at all three levels
Physical level β€” where PostgreSQL keeps inter.students on disksql
SELECT pg_relation_filepath('inter.students');

 pg_relation_filepath
----------------------
 base/16386/16434        -- a file under the server's data directory (numbers differ on your machine)
Logical level β€” the table definition (psql: \d inter.students)text
                                             Table "inter.students"
   Column   |          Type          | Collation | Nullable |                      Default
------------+------------------------+-----------+----------+----------------------------------------------------
 student_id | integer                |           | not null | nextval('inter.students_student_id_seq'::regclass)
 full_name  | character varying(100) |           | not null |
 email      | character varying(120) |           | not null |
 join_year  | integer                |           | not null |
 dept_id    | integer                |           |          |
Indexes:
    "students_pkey" PRIMARY KEY, btree (student_id)
    "students_email_key" UNIQUE CONSTRAINT, btree (email)
Foreign-key constraints:
    "students_dept_id_fkey" FOREIGN KEY (dept_id) REFERENCES inter.departments(dept_id) ON DELETE SET NULL
Referenced by:
    TABLE "inter.enrollments" CONSTRAINT "enrollments_student_id_fkey" FOREIGN KEY (student_id) REFERENCES inter.students(student_id) ON DELETE CASCADE
View level β€” each user sees only what they needsql
-- the view you created in class: courses with their department
SELECT dept_code, dept_name, course_id FROM inter.myfirstview ORDER BY course_id;

 dept_code |    dept_name     | course_id
-----------+------------------+-----------
 CS        | Computer Science |         1
 CS        | Computer Science |         2
 CS        | Computer Science |         3
 MA        | Mathematics      |         4
 DA        | Data Analytics   |         5

-- a faculty member's view: just the class list
SELECT student, faculty FROM inter.v_offering_roster
WHERE course_code = 'CS201' ORDER BY student;

   student    |     faculty
--------------+-----------------
 Aarav Menon  | Dr. Nisha Varma
 Diya Nair    | Dr. Nisha Varma
 Kevin Thomas | Dr. Nisha Varma

Don't confuse three levels with three tiers

The three levels (physical, logical, view) describe how data is organised inside the DBMS. The three tiers of a client-server system (client, application server, database server) describe how the machines of an application are arranged β€” see 1.10.

βœ… Remember
  • β–ΈPhysical = how data is stored; Logical = what data is stored; View = what a user sees.
  • β–ΈMany views, one logical schema, one physical schema.
  • β–ΈAbstraction hides storage details, which makes the database simpler to use and design.

1.4 Data Independence

πŸ“– Definition
The ability to change the schema at one level without having to change the schema at the next higher level β€” so that changes in storage or structure do not break the users and programs above them.
TypeYou can change……without changingDifficulty
Physical data independencethe physical level β€” add an index, move files to another disk, change file organisationthe logical schema or any applicationEasy β€” supported by almost every DBMS
Logical data independencethe logical level β€” add a column or a table, split a tablethe views and the applications that use themHarder β€” some logical changes do reach the users
🏫 Example · both kinds of independence
Physical change: add an index β€” every query stays the same, some get fastersql
CREATE INDEX idx_enrollments_student ON inter.enrollments (student_id);
Logical change: add a column β€” the existing view still works unchangedsql
ALTER TABLE inter.students ADD COLUMN phone VARCHAR(15);

SELECT student, course_code
FROM inter.v_offering_roster
ORDER BY student, course_code;      -- still returns the same 6 rows

-- undo both changes when you are done
ALTER TABLE inter.students DROP COLUMN phone;
DROP INDEX inter.idx_enrollments_student;
βœ… Remember
  • β–ΈPhysical independence protects the logical schema from storage changes.
  • β–ΈLogical independence protects views and applications from changes to tables.
  • β–ΈPhysical independence is easier to achieve than logical independence.

1.5 Phases of Database Design

πŸ“– Definition
Building a database moves from the real-world requirements to a running database in three design phases: conceptual, logical and physical.
Requirements
A student enrolls in many course offerings; each offering has a capacity.
1 Β· Conceptual
ER model: STUDENT β€”enrolls inβ€” COURSE OFFERING. DBMS-independent.
2 Β· Logical
Relations: students(student_id PK, …), enrollments(student_id FK, offering_id FK).
3 Β· Physical
CREATE TABLE inter.enrollments … in PostgreSQL 17, with types and indexes.
Figure 1.3 β€” Phases of database design, using CampusDB
  • Conceptual design β€” capture the requirements in a high-level model, usually an ER diagram (entities, attributes, relationships). It does not depend on any DBMS.
  • Logical design β€” convert the ER diagram into the relational model: tables, columns, primary and foreign keys, normalised (typically up to 3NF).
  • Physical design β€” implement the relations in a specific DBMS: exact data types, constraints, indexes and storage β€” the actual CREATE TABLE scripts.
🏫 Example · the enrollments table, phase by phase
PhaseWhat it looks like for enrollments
Requirementβ€œA student can enroll in many course offerings; an offering has many students; a student cannot enroll in the same offering twice.”
ConceptualSTUDENT β€”(enrolls in, M:N)β€” COURSE OFFERING
Logicalenrollments(enrollment_id PK, student_id FK β†’ students, offering_id FK β†’ course_offerings, enrolled_on), with (student_id, offering_id) unique
PhysicalThe PostgreSQL script below
Physical design in PostgreSQLsql
CREATE TABLE inter.enrollments (
  enrollment_id SERIAL  PRIMARY KEY,
  student_id    INTEGER NOT NULL REFERENCES inter.students(student_id)          ON DELETE CASCADE,
  offering_id   INTEGER NOT NULL REFERENCES inter.course_offerings(offering_id) ON DELETE CASCADE,
  enrolled_on   DATE    NOT NULL DEFAULT CURRENT_DATE,
  UNIQUE (student_id, offering_id)
);

Our lab sessions follow exactly these phases: requirements β†’ ER model (conceptual) β†’ schema design (logical) β†’ DDL scripts (physical).

βœ… Remember
  • β–ΈConceptual = ER model (what); Logical = relational tables and keys (structure); Physical = DBMS-specific DDL (how).
  • β–ΈOnly the physical design depends on the DBMS product.

1.6 Features & Advantages of a DBMS

πŸ“– Definition
A DBMS organises data centrally and controls all access to it, which gives it these advantages over a file system.
FeatureWhat it meansIn PostgreSQL / university_lab
Minimal redundancy, consistent dataEach fact is stored once (normalisation), so copies cannot disagree.Departments are stored once in inter.departments; students, faculty and courses point to them.
Simplified data accessAsk for data by name, not by file location.SELECT … FROM inter.students β€” no file paths.
Multiple views of the dataDifferent users see different, tailored parts of the same data.v_offering_roster for faculty, v_seat_availability for the admissions office.
Data securityOnly authorised users can read or change data.Roles plus GRANT / REVOKE β€” example below.
Data integrityRules keep invalid data out.CHECK (capacity > 0), primary keys, foreign keys, NOT NULL.
Concurrent accessMany users work at the same time without corrupting data.MVCC: readers never block writers.
Backup and recoveryData survives mistakes and failures.pg_dump / pg_restore, plus crash recovery from the WAL.
🏫 Example Β· security β€” a role that can see class lists but not student records
Grant access to one view onlysql
CREATE ROLE faculty_reader LOGIN PASSWORD 'change-me';
GRANT USAGE  ON SCHEMA inter          TO faculty_reader;
GRANT SELECT ON inter.v_offering_roster TO faculty_reader;

SET ROLE faculty_reader;              -- act as that user

SELECT course_code, student FROM inter.v_offering_roster
ORDER BY course_code, student LIMIT 3;   -- allowed
 course_code |   student
-------------+-------------
 CS101       | Aarav Menon
 CS201       | Aarav Menon
 CS201       | Diya Nair

SELECT * FROM inter.students;            -- not allowed
ERROR:  permission denied for table students

RESET ROLE;                           -- back to your own user
Backup and recovery β€” the file shared in class is exactly this kind of backupbash
# back up university_lab to a single archive file
pg_dump -U postgres -Fc -d university_lab -f university_lab.dump

# restore it (creates the database again)
pg_restore -U postgres -C -d postgres university_lab.dump
βœ… Remember
  • β–ΈAdvantages: less redundancy, consistency, easy access, multiple views, security, integrity, concurrency, backup and recovery.
  • β–ΈEach advantage answers one file-system problem from 1.2.

1.7 DBMS vs RDBMS

πŸ“– Definition Β· RDBMS
A DBMS based on the relational model proposed by E. F. Codd in 1970. It stores data in tables (relations) and represents relationships with keys. Every RDBMS is a DBMS; not every DBMS is relational.
PointDBMS (general, incl. early non-relational systems)RDBMS
Data stored asFiles, hierarchies (trees) or networks of linked recordsTables of rows and columns
RelationshipsFollowed through pointers, or handled by the applicationRepresented by primary and foreign keys, enforced by the DBMS
NormalisationNot applicableSupported (1NF β†’ 3NF β†’ BCNF)
Integrity constraintsLimitedPRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, NOT NULL
Query languageNavigational, record-at-a-time programsDeclarative SQL, set-at-a-time
Users and scaleOften single-user or smallMulti-user, concurrent, large data volumes
History1960s β€” IDS (Charles Bachman), IBM IMS1970 β€” Codd’s relational model; 1970s β€” System R, Ingres
ExamplesIBM IMS (hierarchical), IDMS (network), file-based systemsPostgreSQL, Oracle, MySQL, SQL Server, IBM Db2
🏫 Example · relationships the RDBMS knows about and enforces

PostgreSQL records every foreign key in its catalog β€” the relationships are part of the database, not hidden in programs:

Every foreign key in the inter schemasql
SELECT conrelid::regclass  AS child_table,
       confrelid::regclass AS parent_table,
       conname             AS foreign_key
FROM pg_constraint
WHERE contype = 'f'
  AND connamespace = 'inter'::regnamespace
ORDER BY conrelid::regclass::text, confrelid::regclass::text, conname;

      child_table       |      parent_table      |             foreign_key
------------------------+------------------------+-------------------------------------
 inter.course_offerings | inter.courses          | course_offerings_course_id_fkey
 inter.course_offerings | inter.faculty          | course_offerings_faculty_id_fkey
 inter.course_offerings | inter.semesters        | course_offerings_semester_id_fkey
 inter.courses          | inter.departments      | courses_dept_id_fkey
 inter.enrollments      | inter.course_offerings | enrollments_offering_id_fkey
 inter.enrollments      | inter.students         | enrollments_student_id_fkey
 inter.faculty          | inter.departments      | faculty_dept_id_fkey
 inter.prerequisites    | inter.courses          | prerequisites_course_id_fkey
 inter.prerequisites    | inter.courses          | prerequisites_prereq_course_id_fkey
 inter.students         | inter.departments      | students_dept_id_fkey

Get the history right

Codd did not invent the DBMS. The first DBMSs (IDS, IMS) appeared in the 1960s and were navigational. Codd's 1970 paper introduced the relational model, which RDBMSs are built on. PostgreSQL descends from Berkeley's Ingres and POSTGRES projects.

βœ… Remember
  • β–ΈRDBMS = DBMS + relational model (tables, keys, SQL).
  • β–ΈEvery RDBMS is a DBMS; not every DBMS is relational.
  • β–ΈCodd proposed the relational model in 1970.

1.8 Transactions & ACID Properties

πŸ“– Definition Β· Transaction
A logical unit of work β€” a sequence of database operations that must be performed as one. Either all of them take effect (COMMIT) or none of them does (ROLLBACK).

A DBMS must guarantee four properties for every transaction, so that data stays correct even with many concurrent users and with system failures. Together they are called ACID:

PropertyMeaningIn one phraseHow PostgreSQL ensures it
AtomicityAll operations of the transaction happen, or none do.All or nothingA failed or rolled-back transaction is undone completely.
ConsistencyA transaction takes the database from one valid state to another; no integrity rule is broken.No rule brokenConstraints (PK, FK, CHECK, NOT NULL) plus correct application logic.
IsolationConcurrent transactions do not see each other’s unfinished changes; the result is as if they ran one after another.Unfinished work is invisibleMVCC and isolation levels (default READ COMMITTED).
DurabilityOnce committed, changes survive crashes and power failures.Committed means permanentThe write-ahead log (WAL) is flushed to disk at COMMIT.
🏫 Example · Diya switches from DA301 to CS101

Switching courses is two steps β€” leave DA301, join CS101. If only the first step happened, Diya would lose her seat and have no course. That is why it must be one transaction.

Atomicity β€” a failing step undoes the whole transaction. Here the second step uses an offering that doesn't exist:

Step 2 fails β†’ step 1 is undone toosql
BEGIN;
DELETE FROM inter.enrollments                      -- step 1: leave DA301
WHERE student_id  = (SELECT student_id FROM inter.students WHERE email = 'diya@duk.ac.in')
  AND offering_id = (SELECT o.offering_id
                     FROM inter.course_offerings o
                     JOIN inter.courses c ON c.course_id = o.course_id
                     WHERE c.course_code = 'DA301');
-- DELETE 1

INSERT INTO inter.enrollments (student_id, offering_id)   -- step 2: join offering 999 (no such offering)
VALUES ((SELECT student_id FROM inter.students WHERE email = 'diya@duk.ac.in'), 999);
-- ERROR:  insert or update on table "enrollments" violates foreign key constraint "enrollments_offering_id_fkey"

COMMIT;
-- ROLLBACK        <- PostgreSQL refuses to commit a failed transaction

SELECT course_code FROM inter.v_offering_roster WHERE student = 'Diya Nair' ORDER BY 1;
-- CS201, DA301    <- the DELETE was undone: Diya is still in DA301

Now do it properly β€” both steps succeed, and COMMIT makes them permanent together:

Both steps succeed β†’ COMMITsql
BEGIN;
DELETE FROM inter.enrollments
WHERE student_id  = (SELECT student_id FROM inter.students WHERE email = 'diya@duk.ac.in')
  AND offering_id = (SELECT o.offering_id
                     FROM inter.course_offerings o
                     JOIN inter.courses c ON c.course_id = o.course_id
                     WHERE c.course_code = 'DA301');
INSERT INTO inter.enrollments (student_id, offering_id)
VALUES ((SELECT student_id FROM inter.students WHERE email = 'diya@duk.ac.in'),
        (SELECT o.offering_id
         FROM inter.course_offerings o
         JOIN inter.courses c ON c.course_id = o.course_id
         WHERE c.course_code = 'CS101'));
COMMIT;

SELECT course_code FROM inter.v_offering_roster WHERE student = 'Diya Nair' ORDER BY 1;
-- CS101, CS201

Consistency β€” a rule the database will not let any transaction break:

An offering must have at least one seatsql
UPDATE inter.course_offerings SET capacity = 0
WHERE course_id = (SELECT course_id FROM inter.courses WHERE course_code = 'CS101');

ERROR:  new row for relation "course_offerings" violates check constraint "course_offerings_capacity_check"

Isolation β€” open two psql windows and run these steps in order:

StepWindow AWindow B
1BEGIN;
2UPDATE inter.course_offerings SET capacity = 45 WHERE room = 'LH-3';
3SELECT capacity FROM inter.course_offerings WHERE room = 'LH-3';
β†’ 40 (A has not committed)
4COMMIT;
5Run the same SELECT again β†’ 45

Durability β€” PostgreSQL writes the WAL to disk before it reports COMMIT:

The settings behind isolation and durabilitysql
SHOW transaction_isolation;   -- read committed
SHOW synchronous_commit;      -- on  (COMMIT waits until the WAL is safely on disk)

Put the sample data back

The successful switch and the isolation steps change the sample data. To undo them, run the switch again with the course codes swapped (leave CS101, join DA301), and set the LH-3 capacity back to 40.

βœ… Remember
  • β–ΈACID = Atomicity (all or nothing), Consistency (no rule broken), Isolation (unfinished work invisible), Durability (committed means permanent).
  • β–ΈCommands: BEGIN starts, COMMIT saves, ROLLBACK undoes.
  • β–ΈConsistency is shared work: the DBMS enforces declared constraints; the programmer writes correct transactions.

1.9 File-Server Model

πŸ“– Definition
An architecture in which a central file server only stores and shares files. All application logic and data processing run on each client workstation, which pulls the files it needs across the network.

File servers replaced the mainframe in the 1980s, on office networks. Besides files, the server also shared resources such as printers and large disks. The application's files may live on the server, but the application runs in the client machine's memory, on the client's processor.

File server
Client PC
Runs the application Β· does all processing
β‡  entire
students.xlsx
File server
Only stores and shares files
Client-server
Client (psql)
Sends SQL Β· shows results
SQL β‡’
β‡  1 result row
PostgreSQL server
Parses, runs and secures every query
Figure 1.4 β€” File-server model vs client-server model: what travels over the network
AdvantagesDisadvantages
Low-cost entry point β€” just a shared disk on a networkAll processing happens on the client, so every client needs a powerful machine
Flexible β€” add or remove computers and resources as neededWhole files travel over the network β†’ heavy network traffic
Simple to set upSeveral users writing the same file causes locking problems and corruption; security is weak
🏫 Example · the department before university_lab

Suppose the department kept students.xlsx on a shared drive. To find one student's phone number, Excel on your PC downloads the entire file and searches it locally. If a colleague has it open, you get β€œfile is locked for editing” β€” or worse, two people save and one person's changes are lost. Microsoft Access .accdb files on a shared folder work the same way.

βœ… Remember
  • β–ΈFile server = shared storage only; the client does all the work.
  • β–ΈMain drawbacks: heavy network traffic, powerful clients needed, poor multi-user control.

1.10 Client-Server Model

πŸ“– Definition
An architecture in which a client sends requests (SQL statements) to a database server, which processes them and sends back only the results.

Sending a query and getting back a few result rows, instead of whole files, cuts network traffic dramatically. The server enforces security and integrity in one place, and many users can update the shared database at the same time. Clients and servers communicate using SQL or remote procedure calls (RPCs) over the network β€” PostgreSQL listens on TCP port 5432.

2-tier
Client
psql / pgAdmin β€” UI + application logic
Database server
PostgreSQL Β· university_lab
3-tier
Client
Web browser β€” UI only
Application server
Student portal β€” business logic, connection pooling
Database server
PostgreSQL Β· university_lab
Figure 1.5 β€” 2-tier and 3-tier client-server architectures
2-tier3-tier
LayoutClient talks directly to the database serverClient β†’ application server (middleware) β†’ database server
Where the logic runsUser interface and application logic on the clientUser interface on the client; business logic on the application server
Typical sizeSmall environments β€” tens of usersLarge numbers of users
Examplepsql or pgAdmin connected straight to PostgreSQLBrowser β†’ student portal (web application) β†’ PostgreSQL
StrengthsSimple to buildScales better, more flexible, database never exposed to users
WeaknessEach client needs a direct database connection; hard to scaleMore complex to develop

The middleware in a 3-tier system can be an application server, a transaction-processing monitor or a message server. It handles queuing, application execution, scheduling and prioritisation of work, and connection pooling.

Client-server systems also scale in two directions. Horizontal scaling adds more clients or application servers with little performance impact. Vertical scaling moves to a bigger, faster server, or to several servers.

🏫 Example · PostgreSQL is a client-server DBMS
psql is a client; it connects to the server over the networkbash
psql -h localhost -p 5432 -U postgres -d university_lab
Ask the server who and where you aresql
SELECT current_user, current_database(), inet_server_addr(), inet_server_port();

 current_user | current_database | inet_server_addr | inet_server_port
--------------+------------------+------------------+------------------
 postgres     | university_lab   | ::1              |             5432

-- every connected client is a separate session on the server
SELECT pid, usename, application_name, client_addr, state
FROM pg_stat_activity
WHERE datname = 'university_lab';
-- open pgAdmin as well and run it again: you will see two clients
βœ… Remember
  • β–ΈClient sends SQL; server processes it; only the results come back.
  • β–Έ2-tier: client ↔ DB server. 3-tier: client ↔ application server ↔ DB server.
  • β–ΈHorizontal scaling = more machines; vertical scaling = a bigger machine.

1.11 Components of a DBMS

πŸ“– Definition
A database system is made of five components: hardware, software, data, procedures and the database access language. Many textbooks add a sixth: people.
ComponentWhat it isIn our lab
HardwareThe physical devices: computers, disks, RAM, CPU, network and I/O channels.Your lab PC or the server; PostgreSQL's data directory lives on its disk (SHOW data_directory;).
SoftwareThe DBMS itself, plus the operating system, client tools and utilities.PostgreSQL 17 server, psql, pgAdmin, pg_dump.
DataThe user's data and metadata β€” data about the data (structure, types, constraints, owners).Rows in inter.students; metadata in information_schema and pg_catalog.
ProceduresWritten instructions and rules for using and running the database.Installing PostgreSQL, starting the service, creating users, the nightly backup, the restore drill.
Database access languageThe language used to define, change, query and control data.SQL β€” DDL, DML, DCL, TCL.
PeopleThose who design, run and use the database.DBA, database designer, application developer, end users.
🏫 Example · data vs metadata
Metadata: what the DBMS knows about the students tablesql
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'inter' AND table_name = 'students'
ORDER BY ordinal_position;

 column_name |     data_type     | is_nullable
-------------+-------------------+-------------
 student_id  | integer           | NO
 full_name   | character varying | NO
 email       | character varying | NO
 join_year   | integer           | NO
 dept_id     | integer           | YES

The access language, by category β€” one example each from our database (Module 3 covers SQL in depth):

CategoryPurposeExample
DDL β€” Data DefinitionDefine structureCREATE TABLE inter.semesters (…);
DML β€” Data ManipulationRead and change rowsSELECT * FROM inter.courses WHERE credits = 4;
DCL β€” Data ControlPermissionsGRANT SELECT ON inter.v_offering_roster TO faculty_reader;
TCL β€” Transaction ControlGroup work into transactionsBEGIN; … COMMIT; / ROLLBACK;
βœ… Remember
  • β–ΈFive components: Hardware, Software, Data, Procedures, Database access language (+ People).
  • β–ΈMetadata is data about data, kept by the DBMS in its catalog (the data dictionary).

Module 1 at a glance

TopicOne-line answer
Data vs informationRaw facts vs processed, meaningful data.
Database vs DBMSThe organised data vs the software that manages it.
Why a DBMSIt removes redundancy, inconsistency, hard access, unauthorised access, no concurrency, and no backup.
Three levelsPhysical (how stored) Β· Logical (what is stored) Β· View (what a user sees).
Data independenceChange one level without changing the level above. Physical is easy; logical is harder.
Design phasesConceptual (ER) β†’ Logical (relations) β†’ Physical (DDL).
RDBMSA DBMS built on Codd’s 1970 relational model: tables, keys, SQL.
ACIDAtomicity, Consistency, Isolation, Durability.
File serverShares files only; the client does all processing.
Client-serverThe server processes SQL and returns results. 2-tier or 3-tier.
ComponentsHardware, software, data, procedures, access language (+ people).

Practice on university_lab

1

Information for a decision

Easy
Using the inter.v_seat_availability view, list the offerings that have no seats left.
2

Prove atomicity

Medium
Inside a transaction, delete all of Kevin's enrollments and check that they are gone. Then roll back and show that they are back.
3

Read the metadata

Medium
List every column of inter.course_offerings with its data type and whether it allows NULL.
4

Demonstrate logical data independence

Hard
Add a column email_verified BOOLEAN DEFAULT FALSE to inter.students. Show that inter.v_offering_roster still returns the same rows, then remove the column.

Exam-style questions

Short answer (2 marks)
  1. Define data and information, with an example of each.
  2. What is metadata?
  3. Expand ACID.
  4. Differentiate physical and logical data independence.
  5. What is a database instance? How is it different from a schema?
Long answer (5–10 marks)
  1. Explain the drawbacks of the file system that led to the DBMS.
  2. Explain the three levels of data abstraction with a neat diagram.
  3. Explain the ACID properties with a suitable example.
  4. Compare the file-server model with 2-tier and 3-tier client-server models.
  5. Describe the components of a DBMS.