CSC271 Database Systems Complete Notes
CSC271 Database Systems Complete Notes
DATABASE SYSTEMS
Complete Lecture Notes
TABLE OF CONTENTS
Lecture 1–2 — Introduction to Databases & DBMS Environment
Lecture 3–4 — Three-Level Architecture, Data Independence, DB Languages
Lecture 5–6 — Relational Model, Keys & Integrity Constraints
Lecture 7 — Relational Algebra & Operations
Lecture 10 — SQL – Introduction & Data Manipulation Basics
Lecture 11 — SQL – WHERE Clause & Search Conditions
Lecture 12 — SQL – GROUP BY, HAVING & Subqueries
Lecture 13 — SQL – Multi-Table Queries & Joins
Lecture 14 — SQL – Data Definition Language (DDL)
Lecture 15 — SQL – Integrity Constraints & CREATE/ALTER/DROP
Lecture 18 — DB Planning, Design & SDLC
Lecture 19 — Requirements Analysis & DB Design Phases
Lecture 20 — Prototyping, Implementation & CASE Tools
Lecture 22 — Entity–Relationship (ER) Modeling
Introduction to Databases
Chapter 1 & 2
Advantages of DBMS
Key Benefits of Using a DBMS
Disadvantages of DBMS
• Complexity – requires skilled staff (DBA)
• Cost – expensive DBMS software and hardware
• Performance – overhead compared to simple file access
• Single point of failure – a DBMS crash affects all users
External Level View Level / User View What individual users see. Each user gets a customized
view. Different users may see the same data in different
formats.
Conceptual Level Community View / Logical The complete logical structure of the whole database —
Level entities, attributes, relationships, and constraints.
Independent of storage.
Internal Level Physical Level / Storage How data is physically stored on disk — file
Level organizations, indexes, storage structures, access
methods.
Schemas
• External Schema (Subschema): Describes one user's view. Multiple per database.
• Conceptual Schema: Describes all entities, attributes, relationships, and integrity constraints. Only
ONE per database.
• Internal Schema: Describes physical storage — stored records, data fields, indexes. Only ONE per
database.
Mappings
• Conceptual/Internal Mapping: Translates conceptual records to physical storage.
• External/Conceptual Mapping: Maps each user's view to the conceptual schema.
Data Independence
Two Types of Data Independence
Logical Data Independence: Ability to change the conceptual schema without changing external
schemas or application programs. Example: adding a new attribute to a table should not break existing
user views.
Database Languages
Language Purpose Example Statements
DDL (Data Definition Define/describe database CREATE TABLE, ALTER TABLE, DROP
Language) structure TABLE
DML (Data Manipulation Insert, update, delete, retrieve SELECT, INSERT, UPDATE, DELETE
Language) data
Procedural DML You specify WHAT data to get AND HOW to Network/Hierarchical DBMSs
get it. Works on one record at a time.
Non-Procedural DML You specify WHAT data you need. DBMS Relational DBMSs (SQL, QBE)
figures out HOW. Works on sets of records.
Functions of a DBMS
• Data storage, retrieval, and update
• User-accessible catalog (data dictionary / metadata)
• Transaction support (ACID properties)
• Concurrency control – safe multi-user access
• Recovery services – after system failure
• Authorization services – access control
• Integrity enforcement
• Support for data communication
DBMS Architectures
Architecture Description Key Point
File-Server DBMS on each workstation, files shared Heavy network traffic, concurrency
problems
Two-Tier Client-Server Client handles UI; Server holds DB Better than file-server; fat client
issue
Three-Tier Client-Server Client (UI) + Middle tier (Logic) + Server Best scalability; web-friendly; thin
(DB) client
Key Terminology
Formal Term Common Term Meaning
Properties of a Relation
• Each relation has a unique name
• Each cell contains exactly one atomic value (no repeating groups)
• Each attribute has a distinct name
• All values in a column are from the same domain
• No duplicate tuples – every row is unique
• Order of attributes has no significance
• Order of tuples has no significance (theoretically)
Types of Keys
Key Type Definition Example (Branch table)
Integrity Constraints
NULL: Represents missing, unknown, or not-applicable data. It is NOT zero or blank.
1. Entity Integrity: No attribute that is part of the PRIMARY KEY can be NULL. Every row must be
uniquely and completely identifiable.
2. Referential Integrity: If a FOREIGN KEY exists in a relation, its value must either match a candidate
key value in the referenced (parent) table, OR it must be completely NULL. You cannot reference a
non-existent record.
General Constraints: Business rules set by users or DBA. Example: "No staff member may manage
more than 100 properties."
Views
A View is a virtual table derived from one or more base relations. It does not physically store data — it is
computed on demand.
Introduction
Relational Algebra is a formal procedural query language (you specify HOW to get data). Relational
Calculus is declarative (you specify WHAT you want). Both are equivalent in expressive power.
A language is relationally complete if it can express any query that can be expressed in relational
calculus.
Selection (Restriction) σ (sigma) Returns rows that satisfy a condition. Works on one
relation.
Derived Operations
Operation Symbol Definition
Examples of Operations
Selection — σ
Projection — Π
Π (Staff)
staffNo, fName, lName, salary
Union
Π (Branch) ∪ Π (PropertyForRent)
city city
Set Difference
Π (Branch) − Π (PropertyForRent)
city city
Intersection
Π (Branch) ∩ Π (PropertyForRent)
city city
What is SQL?
SQL (Structured Query Language) is the standard language for relational databases. It is
non-procedural — you tell the DBMS what you want, not how to get it.
Component Purpose
DDL (Data Definition Language) CREATE, ALTER, DROP tables and schemas
DML Statements
Statement Purpose Example
Comparison =, <>, <, <=, >, >= WHERE salary > 10000
Pattern Match LIKE (% = any chars, _ = one WHERE address LIKE '%Glasgow%'
char)
Example: WHERE name LIKE 'A%' → finds all names starting with A
ORDER BY Clause
SELECT staffNo, lName, salary
FROM Staff
ORDER BY salary DESC; -- highest first
Aggregate Functions
Function Returns Example
GROUP BY Clause
Groups rows with the same value in the specified columns, and produces one summary row per group.
Used with aggregate functions.
Important rule: Every column in SELECT must either appear in GROUP BY OR be inside an aggregate
function.
HAVING Clause
HAVING filters groups (like WHERE filters rows). Use HAVING only with GROUP BY, and only with
conditions involving aggregate functions.
WHERE vs HAVING
Scalar subquery Single value (one column, one row) =, <, >, etc.
Table subquery Multiple rows and columns IN, EXISTS, ANY, ALL
Multi-Table Queries
Joins combine rows from two or more tables based on a related column. A join is a filtered Cartesian
product.
Types of Joins
Join Type SQL Syntax What it returns
Inner Join (default) FROM A, B WHERE [Link] = [Link] OR: A Only rows with matching values in
INNER JOIN B ON [Link] = [Link] BOTH tables
Left Outer Join A LEFT JOIN B ON [Link] = [Link] All rows from A + matched rows from
B. Unmatched B rows → NULL
Right Outer Join A RIGHT JOIN B ON [Link] = [Link] All rows from B + matched rows from
A. Unmatched A rows → NULL
Full Outer Join A FULL JOIN B ON [Link] = [Link] All rows from BOTH tables.
Unmatched rows → NULL
Cross Join (Cartesian) A CROSS JOIN B Every row of A combined with every
row of B
Difference EXCEPT (or MINUS) Rows in first query but NOT in second
Referential Integrity FOREIGN KEY … REFERENCES Value must exist in parent table or
be NULL
SET DEFAULT Set child foreign key columns to their DEFAULT value
-- Drop a column:
ALTER TABLE Staff DROP COLUMN sex;
-- Change a default:
ALTER TABLE Staff ALTER position DROP DEFAULT;
ALTER TABLE Staff ALTER sex SET DEFAULT 'F';
-- Drop a constraint:
ALTER TABLE PropertyForRent DROP CONSTRAINT StaffNotHandlingTooMuch;
CREATE DOMAIN
Domains define reusable data types with constraints:
CREATE DOMAIN SexType AS CHAR(1) CHECK (VALUE IN ('M', 'F'));
CREATE DOMAIN PropertyRooms AS SMALLINT CHECK (VALUE BETWEEN 1 AND 15);
CREATE DOMAIN PropertyRent AS DECIMAL(6,2) CHECK (VALUE BETWEEN 0 AND 9999.99);
# Stage Description
1 Database Planning Define mission statement & mission objectives. Plan standards, format,
documentation.
2 System Definition Define scope, boundaries, and major user views of the database.
3 Requirements Collection Gather and analyze user needs. Produce requirements specification.
& Analysis
6 Application Design Design user interface and application programs (transaction & UI design).
8 Implementation Create the physical database using DDL; write application programs.
1 Testing Test with real data; verify correctness, performance, and usability.
0
Centralized All user requirements merged into one set. Simple systems with few user
One data model created. groups
View Integration Each user view kept separate → local data Complex systems with many
models created → merged later into global different user groups
model
Build a high-level model of the data, completely independent of any DBMS or physical
considerations. Uses Entity-Relationship (ER) diagrams. Captures entities, relationships, and attributes
from users' requirements specification.
Convert the conceptual model into a logical model based on a specific data model (e.g., relational).
Still independent of a particular DBMS. Produces normalized table structures.
Translate the logical model into actual database structures for a specific DBMS. Defines storage
structures, file organizations, indexes for optimal performance. Creates the real database.
Fact-Finding Techniques
Technique Description Best For
Examining Documentation Review existing forms, reports, manuals, org Understanding current
charts system
Questionnaires Written surveys sent to many users Gathering data from large
groups
CASE Tools
Computer-Aided Software Engineering (CASE) tools assist throughout the SDLC:
• Data dictionary to store metadata about the database
• Design tools for data analysis and modeling
• Diagram tools for conceptual and logical data models
• Prototyping support for applications
• Benefits: Standards, Integration, Consistency, Automation
DBA (Database Administrator) Later stages – technical Physical design, security, performance tuning,
backup, recovery, implementation
Why ER Modeling?
Database designers, programmers, and end-users often think about data differently. The
Entity-Relationship (ER) model provides a common, non-technical, unambiguous communication tool
that everyone can understand.
We use UML notation (as it is expected to become the de facto standard) for drawing ER diagrams, while
using traditional database terminology to describe concepts.
Entity Type: A group of objects with the same properties that the enterprise recognizes as having an
independent existence. Shown as a rectangle labeled with a singular noun.
Entity Occurrence: A uniquely identifiable object of an entity type (one specific instance).
2. Relationship Types
Relationship Type: A meaningful association among entity types. Shown as a line connecting entities,
labeled with a verb or verb phrase.
3. Attributes
Attribute: A property of an entity or relationship type. Holds values that describe each entity occurrence.
Attribute Domain: The set of allowable values for one or more attributes.
Types of Attributes
Attribute Type Description Example
Multi-valued Can hold MULTIPLE values per telNo (staff can have several
occurrence phones)
Derived Calculated from other attributes age (derived from DOB), duration
(from rentStart & rentFinish)
• Relationship names start with uppercase, use verbs: Manages, Leases, Supervises
WHERE conditions
WHERE salary > 10000
WHERE salary BETWEEN 20000 AND 30000
WHERE position IN ('Manager', 'Supervisor')
WHERE address LIKE '%Glasgow%'
WHERE comment IS NULL
ORDER BY
ORDER BY salary DESC;
ORDER BY lName ASC, fName ASC;
Aggregate Functions
SELECT COUNT(*), SUM(salary), AVG(salary), MAX(salary), MIN(salary) FROM Staff;
GROUP BY + HAVING
SELECT branchNo, COUNT(staffNo) AS cnt, SUM(salary) AS total
FROM Staff
GROUP BY branchNo
HAVING COUNT(staffNo) > 1;
JOIN
SELECT [Link], [Link], [Link]
FROM Staff s, Branch b
WHERE [Link] = [Link];
Subquery
SELECT staffNo, fName FROM Staff
WHERE branchNo = (SELECT branchNo FROM Branch WHERE street = '163 Main St');
ALTER TABLE
ALTER TABLE Client ADD prefNoRooms INTEGER;
ALTER TABLE Staff ALTER sex SET DEFAULT 'F';
ALTER TABLE Staff DROP COLUMN telNo;
DROP TABLE
DROP TABLE PropertyForRent RESTRICT;
DROP TABLE PropertyForRent CASCADE;
Data Independence Ability to change one level of the DB architecture without affecting others
DDL Data Definition Language — for defining database structure (CREATE, ALTER,
DROP)
Entity Type A group of objects with same properties, recognized as independent by the
enterprise
Foreign Key Attribute(s) in one table referencing a candidate key in another table
Instance (DB) The actual data in the database at a specific point in time
Logical Data Changing the conceptual schema without affecting external schemas
Independence
Physical Data Changing the internal schema without affecting the conceptual schema
Independence
Primary Key The chosen candidate key used to uniquely identify each row
Relation A 2D table with rows and columns (the foundation of the relational model)
Superkey Any set of attributes that uniquely identifies a tuple (may have extra attributes)
View A virtual table defined by a query on base relations; not physically stored