Vault Notes

Databases

Subject 4 of 10 · Exact transcription of the original notes.

1. ER Model

1.1 Entity Sets and Attributes

ER Model

The ER Model is a conceptual design tool for database schemas that focuses on logical structure without implementation details. It uses Entity-Relationship diagrams to visualize database components.

Core Components

Entity: A distinct object or concept with independent existence, defined by its attributes.

Entity Set: A collection of similar entities, represented by rectangles in ER diagrams.

Relationship: An association between two or more entities.

Relationship Set: A collection of similar relationships between entity sets.

Key Concepts

Super Key: Any combination of attributes that uniquely identifies an entity within its set.

Candidate Key: A minimal super key - removing any attribute would lose uniqueness.

Primary Key: The candidate key chosen by the database designer as the main identifier.

Entity Types

Strong Entity Set: Has sufficient attributes to form a primary key independently.

Weak Entity Set: Lacks attributes for a complete primary key and depends on a strong entity for identification.

Remember: Weak entities cannot exist without their supporting strong entity - if you delete the strong entity, all related weak entities must also be deleted.

1.2 Cardinality Constraints (1:1, 1:N, M:N)

Structural Constraints

Structural Constraints define how entities participate in relationships within an ER model.

Degree

Number of entity sets participating in a relationship.

One-to-One (1:1)

One instance of an entity relates to exactly one instance of another entity. ... can serve as the relationship's key. Typically one or attributes from E1 or E2. Example: Person-Passport relationship where each person has exactly one passport.

One-to-Many (1:N)

One entity instance relates to multiple instances of another entity, but each instance of the second entity relates to only one instance of the first. ER Representation: Entity E1 connects with cardinality 1, entity E2 connects with cardinality M. Candidate Key: Key from the "many" side (E from E2) becomes the relationship's candidate key. Example: Department-Employee relationship where one department has many employees, but each employee belongs to one department.

Many-to-One (M:1)

Multiple instances of the first entity relate to one instance of the second entity. ER Representation: Entity E1 connects with cardinality M, entity E2 connects with cardinality 1. Candidate Key: Key from the "many" side (A from E1) becomes the relationship's candidate key.

lead-in: Participation Constraints specify whether all or only some entity instances participate in a relationship:

Note: Total participation indicates a minimum cardinality of 1, while partial participation allows minimum cardinality of 0.

Many-to-many

A many-to-many relationship connects two entities where each instance of one entity can relate to multiple instances of the other entity, and vice versa. ER Diagram Structure:

aE1MRNbE2
This diagram shows a many-to-many relationship in an ER diagram. On one side is entity E1 with its attribute a, and on the other side is entity E2 with its attribute b. The two entities are connected through a relationship diamond labelled R. The cardinality written on the relationship is M to N, which means one instance of E1 can be related to many instances of E2, and one instance of E2 can also be related to many instances of E1. The takeaway is that a many-to-many relationship like this cannot be stored directly in one table and always needs its own separate relationship table.

Mapping Process:

  1. Create table for E1 with primary key a
  2. Create table for E2 with primary key b
  3. Create relationship table R with columns a and b as foreign keys
  4. Primary key of R is the composite key (a, b)

Example: Students and Courses

Remember: Many-to-many always requires three tables - no exceptions for merging.

1.3 ER to Relational Mapping

Overview

Database Models Overview Database Models provide a framework for organizing and structuring data. The two fundamental models in database design are: Entity-Relationship (ER) Model

Relational Model

Limitations of File System

File systems have several critical limitations when used for data management: Data inconsistency when concurrent writes occur

All-or-Nothing Access Control File system permissions operate at the file level only. Once a user gains access to a file, they can view and modify all data within it, regardless of data sensitivity. There is no easy way to maintain consistency across related files during backup operations .

These limitations make file systems unsuitable for applications requiring structured data management, leading to the development of database management systems.

2. Relational Model

2.1 Relation Schema and Instance

Rdbms

RDBMS (Relational Database Management System) is the foundation for SQL and modern database systems like Oracle, MySQL, PostgreSQL, and SQL Server. Core Structure:

Key Characteristics:

Table Structure:

Example: A university database might have:

Remember: RDBMS enforces data integrity through constraints and relationships, unlike flat file systems.

2.2 Keys (Super, Candidate, Primary, Foreign)

According to Codd

No two rows in a relational table should be identical - this is the uniqueness constraint in Codd's relational model. Every table must have at least one attribute (or combination of attributes) that uniquely identifies each row. This unique identifier is called a primary key. Why this matters:

Example: In a Student table, even if two students have the same name and age, they must differ in at least one attribute (like Student_ID).

Student_IDNameAge
101 John20
102 John20

Here, Student_ID serves as the primary key, making each row unique despite identical Name and Age values. Note: This rule applies to the logical structure - physical storage may have duplicates temporarily during operations, but the final table state must maintain uniqueness.

Difference Between Primary Key and Alternative Key

A primary key uniquely identifies each row and cannot be null. An alternative key (candidate key) can also uniquely identify rows but is not chosen as the primary key. Key Differences:

AspectPrimary KeyAlternative Key
Count per tableExactly oneMultiple
Null valuesNot allowedAllowed
PurposeMain identifierBackup identifier

Definitions

Primary Key: Unique + Not Null

Alternative Key: Any candidate key that wasn't selected as primary key

Super Key: Any set of attributes that can uniquely identify all tuples

Super Key Counting For relation R(A1, A2, ..., An) with n attributes: Case 1: Single candidate key (A1)

Super keys = 2^(n-1)

Case 2: Single candidate key (A1, A2)

Super keys = 2^(n-2)

Case 3: Two candidate keys (A1, A2) and (A3, A4)

Super keys = 2^(n-2) + 2^(n-2) - 2^(n-4) = 2^(n-1) - 2^(n-4)

Formula logic: Include all supersets of each candidate key, subtract overlaps using inclusion-exclusion principle. Remember: Super key count depends on the size and number of candidate keys in the relation.

Foreign Key

A Foreign Key is a set of attributes in one table that references the primary key of another table (or the same table). It establishes relationships between tables and maintains referential integrity. Key Properties:

Example: Student-Enrollment Relationship Consider two tables showing how foreign keys work: Student Table (Primary table):

SidS_nameLogin
101 Alicealice123
102 Bobbob456

Enrolled Table (Referencing table):

SidCourse_idGrade
101 CS101 A
102 CS101 B

Here, Sid in the Enrolled table is a foreign key that references Sid (primary key) in the Student table. Referential Integrity Rules:

Remember: Foreign keys create parent-child relationships where the referenced table is the parent and the referencing table is the child.

2.3 Referential Integrity

Referenced Relation

Referential Integrity Actions control what happens when referenced data is modified. Insertion Operations: No referential integrity violations occur during insertion - foreign keys can only reference existing primary key values. Deletion Operations: When deleting a record from the referenced table (parent): ON DELETE NO ACTION

ON DELETE CASCADE

ON DELETE SET NULL

Update Operations: When updating primary key in the referenced table (parent): ON UPDATE NO ACTION

ON UPDATE CASCADE

ON UPDATE SET NULL

Note: These actions only apply to the referenced table (parent). The referencing table (child) cannot violate integrity constraints during normal operations.

Referencing Relation

In a referencing relation (child table), foreign key constraints affect operations differently: Insertion: May cause violation if the foreign key value doesn't exist in the referenced table. Deletion: No violation - removing a row from the child table doesn't break referential integrity. Update: May cause violation if the new foreign key value doesn't exist in the referenced table. CASCADE Operations When a referenced row is deleted, CASCADE actions automatically handle dependent rows. Example scenario: Table with foreign key constraint:

AB
26
36
45
56
AB
38
45
54

Operation: Delete row (1, 4) with ON DELETE CASCADE Result: Row (1, 2) is automatically deleted because it references the deleted value 1.

AB
3 4
4 2
5 4

Remember: CASCADE ensures referential integrity by automatically removing or updating dependent rows when the referenced data changes.

3. Relational Algebra

3.1 Select Operation (σ)

Selection Operation (Restriction) (σ(sigma))

The selection operation σ filters tuples from a relation based on specified conditions. Basic Properties: Degree preservation: deg(σ(R)) = deg(R)

Cardinality bounds: 0 ≤ |σ_c(R)| ≤ |R|
Commutativity: σ_a(σ_b(R)) = σ_b(σ_a(R)) = σ_{a∧b}(R)

Example: From relation Employee(ID, Name, Salary, Dept)

Remember: Selection is horizontal filtering - picks which rows to keep based on conditions.

3.2 Project Operation (π)

Projection Operation (π(pi))

The projection operation π selects specific columns from a relation and removes duplicates. Notation: π_{A1, A2, ..., Ak}(R) Projects attributes A1, A2, ..., Ak from relation R. Degree Properties:

0 < deg(π(R)) ≤ deg(R)

The degree (number of columns) of the projected relation is between 1 and the original degree. Cardinality Properties:

|π(R)| ≤ |R|

The number of tuples in the result is at most the original count, since duplicates are eliminated. Example: From relation STUDENT(ID, Name, Age, Department)

Key Points:

3.3 Union Operation (∪)

Union Operation

The union operation combines tuples from two relations into a single relation. Union Compatibility Requirement: Relations R and S can be unioned only if:

Degree Property:

deg(R ∪ S) = deg(R) = deg(S)

The result has the same number of attributes as both input relations. Cardinality Bounds:

max(|R|, |S|) ≤ |R ∪ S| ≤ |R| + |S|

Example:

Remember: Union automatically removes duplicates - each tuple appears only once in the result.

3.4 Intersection Operation (∩)

Intersection Operation

The intersection operation (R ∩ S) returns tuples that exist in both relations. Prerequisites: Relations must be union compatible (same number of attributes with compatible data types). Degree property:

deg(R ∩ S) = deg(R) = deg(S)

The result has the same number of attributes as both input relations. Cardinality bounds:

0 ≤ |R ∩ S| ≤ min(|R|, |S|)

Example:

Note: If relations have no tuples in common, intersection returns an empty relation with the same schema.

3.5 Set Difference Operation (-)

Set Difference (-)

Set difference returns tuples present in the first relation but not in the second relation. Prerequisites:

Properties:

deg(R - S) = deg(R) = deg(S)
0 ≤ |R - S| ≤ |R|

The result has the same structure as both input relations, with cardinality between 0 and the size of the first relation. Example: If relation R contains students {A, B, C} and relation S contains students {B, D}, then R - S = {A, C}.

Relational Algebra vs Tuple Calculus:

OperationRelational Algebra
Selectionσ_cond(R)
Projectionπ_{A1, A2}(R)
Cartesian ProductR × S
UnionR ∪ S
Set DifferenceR - S

Read as: Operation name maps to its algebraic notation and equivalent tuple calculus expression. Note: Set difference is not commutative - R - S ≠ S - R in general.

3.6 Cartesian Product (×)

Cartesian Product (×(times))

The Cartesian Product operation combines every tuple from relation R with every tuple from relation S. Degree Formula:

deg(R × S) = deg(R) + deg(S)

The resulting relation has columns equal to the sum of columns in both relations. Cardinality Formula:

|R × S| = |R| × |S|

The resulting relation has rows equal to the product of rows in both relations. Example:

Note: Cartesian product without conditions creates all possible combinations, often resulting in very large relations. Usually combined with selection to filter meaningful combinations.

3.7 Natural Join (⋈)

Natural Join

Natural join combines two relations by matching values in their common attributes.

R₁ ⋈ R₂ = π all attributes (σ common attributes equal (R₁ × R₂))

Process:

  1. Take cross product of both relations
  2. Select rows where common attributes have equal values
  3. Remove duplicate columns from the result

Degree calculation:

deg(R₁ ⋈ R₂) = deg (R₁) + deg (R₂) − common attributes

Example: If R₁ has attributes (A, B, C) and R₂ has (C, D, E)

Key difference from cross product: Natural join eliminates mismatched tuples and duplicate columns, while cross product keeps everything.

Relation counting formulas: Number of x-ary relations over x domains with n elements each:

nˣ

Number of equivalent representations for a relation with degree n and cardinality c:

n! × c!

This accounts for all possible column reorderings (n!) and row reorderings (c!).

3.8 Rename Operation (ρ)

Rename (S ← ρS(R))

The rename operation (ρ) changes the name of a relation without affecting its structure or data. Notation: ρ S (R) renames relation R to S Properties:

The rename operation only changes the relation's identifier - all attributes, tuples, and constraints remain identical. Example: If relation Student has 3 attributes and 100 tuples:

Use case: Rename is essential when the same relation appears multiple times in complex queries, allowing you to distinguish between different instances.

4. SQL

4.1 Data Definition Language (CREATE, ALTER, DROP)

DDL Commands

DDL (Data Definition Language) commands are used to define and modify database structure. These commands automatically commit changes and cannot be rolled back. Core DDL Commands: CREATE - Defines new database objects

CREATE TABLE table_name (column_definitions);

Creates tables, databases, indexes, or views. Establishes the schema structure with column names, data types, and constraints. ALTER - Modifies existing database objects

ALTER TABLE table_name ADD/DROP/MODIFY ...

Changes table structure by adding columns, dropping columns, or modifying data types. Can also add or remove constraints. DROP - Removes database objects completely

DROP TABLE table_name;

Permanently deletes tables, databases, or other objects. All data and structure are lost. Access Control Commands GRANT - Provides privileges to users

GRANT privilege_list ON object TO user;

Assigns specific permissions like SELECT, INSERT, UPDATE, DELETE to database users or roles. REVOKE - Removes privileges from users

REVOKE privilege_list ON object FROM user;

Withdraws previously granted permissions from users or roles. Data Management Commands TRUNCATE - Removes all table data

TRUNCATE TABLE table_name;

Deletes all rows from a table but preserves the table structure. Faster than DELETE as it doesn't log individual row deletions. COMMENT - Adds documentation

COMMENT ON object IS 'description';

Attaches descriptive text to database objects for documentation purposes. Key difference: TRUNCATE vs DROP:

Note: All DDL commands are auto-committed and cannot be undone with ROLLBACK.

Functions of SQL

SQL provides comprehensive database management capabilities through various operations: Data Retrieval:

Data Modification:

Database Structure Management:

Advanced Database Objects:

Security & Access Control:

Example: A typical workflow might involve creating a customers table, inserting customer records, then creating a view that shows only active customers while restricting access to sensitive fields. Remember: SQL operates on sets of data, not individual records - think in terms of operations on entire result sets rather than row-by-row processing.

Type of SQL

SQL commands are categorized into two main types: Data Manipulation Language (DML):

Data Definition Language (DDL):

Key difference: DML works with the data inside tables, while DDL works with the table structure itself. Example:

Remember: Think of DDL as the architect (builds structure) and DML as the resident (uses the structure).

4.2 Data Manipulation Language (INSERT, UPDATE, DELETE)

DML Commands

Data Manipulation Language (DML) commands operate on data within database tables. These commands modify, retrieve, or manipulate existing data without altering the table structure. Core DML Commands: SELECT - Retrieves data from tables

INSERT - Adds new records to tables

UPDATE - Modifies existing records

DELETE - Removes records from tables

Extended DML Commands: CALL - Executes stored procedures or functions

LOCK TABLE - Controls concurrent access to tables

EXPLAIN PLAN - Shows query execution strategy

Key Characteristic: All DML commands work with data content, not database structure. They require existing tables and operate within transaction boundaries for data integrity.

4.3 SELECT Query Basics

Introduction

SQL (Structured Query Language) is the standard language for managing relational databases. It provides a unified interface to access, manipulate, and control database systems. Key characteristics:

Primary operations:

Example: Basic query structure:

SELECT column_name
FROM table_name
WHERE condition;

Note: While SQL is standardized, each database system (MySQL, PostgreSQL, Oracle) may have specific extensions and syntax variations.

Select Statement

The SELECT statement specifies which columns to retrieve from a database table. Basic syntax:

SELECT column1, column2, column3 FROM table_name; 

Key points:

Examples: Select specific columns:

SELECT state_code, state_name FROM states; 

Select all columns:

SELECT * FROM students; 

Remember: SELECT * retrieves every column, which can impact performance on large tables. Specify only needed columns when possible.

From Statement

The FROM clause specifies which tables or views the query will access for data retrieval. Purpose: Defines the data source(s) for SELECT and WHERE operations. Syntax for single table:

FROM table_name

Key points:

Example: Retrieving employee data from multiple related tables:

SELECT e.name, d.department_name, e.salary 
FROM employees e, departments d, salaries s 
WHERE e.dept_id = d.id AND e.emp_id = s.emp_id; 

Remember: When using multiple tables, always include proper JOIN conditions in WHERE clause to avoid Cartesian products.

Select Distinct Statement

The SELECT DISTINCT statement eliminates duplicate rows from query results, returning only unique values. Syntax:

SELECT DISTINCT column_name FROM table_name; 

Multiple columns:

SELECT DISTINCT column1, column2 FROM table_name; 

When used with multiple columns, DISTINCT considers the combination of all specified columns - rows are unique only if ALL column values together are different. Example: Employee table with duplicate departments:

With multiple columns:

Note: DISTINCT applies to the entire row, not individual columns. Use GROUP BY for more complex uniqueness logic with aggregations.

Aliases

SQL aliases provide temporary names for tables and columns during query execution. Purpose:

Column Alias Syntax:

SELECT column_name AS alias_name FROM table_name; 

Table Alias Syntax:

SELECT column_name FROM table_name AS alias_name; 

Example - Column Aliases:

SELECT first_name AS "First Name",
       salary * 12 AS "Annual Salary"
FROM employees;

Output shows readable headers instead of raw column names. Example - Table Aliases:

SELECT e.name, d.department_name
FROM employees AS e, departments AS d
WHERE e.dept_id = d.id;

Note: The AS keyword is optional - SELECT name FROM employees e works identically. Remember: Aliases exist only for the duration of the query and don't modify the actual database structure.

4.4 WHERE Clause and Conditions

Where Clause

The WHERE clause filters records in SQL queries based on specified conditions. It's optional but essential for targeted data retrieval. Basic comparison operators:

Range and list operators:

Pattern matching:

Null handling:

Negation: Use NOT before any condition to reverse its logic:

Example: Find employees with salary between 30,000 and 80,000:

SELECT * FROM employees
WHERE salary BETWEEN 30000 AND 80000;

Remember: Use IS NULL instead of = NULL - null comparisons with = always return false.

And & Or

The AND and OR operators combine multiple conditions in SQL WHERE clauses. AND Operator: All conditions must be true for a record to be selected.

SELECT * FROM students
WHERE age > 18 AND grade = 'A';

Returns only students who are both over 18 AND have grade A. OR Operator: At least one condition must be true for a record to be selected:

SELECT * FROM students
WHERE age > 20 OR grade = 'A';

Returns students who are either over 20 OR have grade A (or both). Combining Multiple Conditions: Use parentheses to group conditions and control evaluation order:

SELECT * FROM products
WHERE (category = 'Electronics' OR category = 'Clothing') 
AND price < 100;
TRUEFALSEFALSE
FALSETRUEFALSE
FALSEFALSEFALSE

Table as printed in the source: a 3 column by 3 row grid of TRUE/FALSE values with no header row visible. First row: TRUE, FALSE, FALSE. Second row: FALSE, TRUE, FALSE. Third row: FALSE, FALSE, FALSE.

Remember: AND narrows results (more restrictive), OR broadens results (less restrictive).

Between Operator

The BETWEEN operator selects values within a specified range, including both boundary values. Syntax:

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2; 

Works with:

Example: Find employees with salary between 30,000 and 50,000:

SELECT name, salary
FROM employees
WHERE salary BETWEEN 30000 AND 50000;

Remember: BETWEEN is inclusive - it includes both boundary values. Use NOT BETWEEN to exclude the range. Equivalent condition:

WHERE column_name >= value1 AND column_name <= value2 

4.5 Aggregate Functions (COUNT, SUM, AVG, MIN, MAX)

Aggregation Operations

Aggregation Operations are SQL functions that perform calculations on multiple rows and return a single result value. Core Functions: SUM: Calculates total of numeric values

SUM(column_name)

COUNT: Returns number of rows

AVG: Calculates arithmetic mean

AVG = SUM(values) / COUNT(non-NULL values)

MIN/MAX: Find smallest/largest values

Key Properties:

Usage with GROUP BY: Aggregation functions are commonly used with GROUP BY to calculate values for each group:

SELECT department, AVG(salary), COUNT(*)
FROM employees
GROUP BY department;

Remember: When using aggregates with GROUP BY, all non-aggregated columns in SELECT must appear in GROUP BY clause.

4.6 ORDER BY Clause

Orderby

The ORDER BY clause sorts query results in a specified sequence. Default behavior: Results are sorted in ascending order (A to Z, 0 to 9).

SELECT column_name FROM table_name ORDER BY column_name;

Explicit ordering:

Multiple columns: Sort by first column, then by second column for ties:

ORDER BY column1, column2 DESC;

Example: Sort employees by salary (highest first), then by name:

SELECT name, salary
FROM employees
ORDER BY salary DESC, name ASC;

Remember: Without ORDER BY, result order is unpredictable and may vary between executions.

Order by Statement

ORDER BY Statement Controls the sorting order of query results. Syntax:

SELECT column1, column2 FROM table_name
ORDER BY column1 ASC|DESC, column2 ASC|DESC; 

Default behavior: Ascending order (ASC) Descending order: Use DESC keyword Example: Sort employees by salary (highest first), then by name:

SELECT name, salary FROM employees
ORDER BY salary DESC, name ASC;

Group Functions

Perform calculations on sets of rows grouped together. Key rules:

Example: Average salary by department:

SELECT department, AVG(salary) FROM employees 
GROUP BY department;

INSERT Statement

Adds new records to a table. Full syntax:

INSERT INTO table_name (column1, column2, ...) 
VALUES (value1, value2, ...);

Shorthand (all columns in order):

INSERT INTO table_name VALUES (value1, value2, ...); 

Example: Add new student record:

INSERT INTO students (id, name, grade) 
VALUES (101, 'Alice', 'A');

UPDATE Statement

Modifies existing records in a table. Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;

Critical: Always include WHERE clause to target specific records. Without it, ALL records get updated. Example: Increase salary for specific employee:

UPDATE employees
SET salary = 75000
WHERE employee_id = 123;

Warning: Omitting WHERE deletes ALL records in the table. Example: Remove inactive users:

DELETE FROM users WHERE status = 'inactive'; 

LIKE Operator

Pattern matching in WHERE clauses using wildcards. Wildcards:

Example: Find names starting with 'A':

SELECT * FROM customers
WHERE name LIKE 'A%';

IN Operator

Tests if a value matches any value in a list. Syntax:

SELECT * FROM table_name
WHERE column_name IN (value1, value2, ...); 

Example: Find orders from specific cities:

SELECT * FROM orders
WHERE city IN ('Delhi', 'Mumbai', 'Pune'); 

Equivalent to: Multiple OR conditions but more concise.

4.7 JOINS in SQL

Joining Tables

Join Operations: Joins combine data from multiple tables based on related columns, typically primary and foreign key relationships. Join Guidelines:

LEFT OUTER JOIN

Returns all records from the left table plus matching records from the right table. Syntax:

SELECT columns FROM table1 LEFT JOIN table2 ON table1.id = table2.id; 

Behavior:

Example: Get all employees and their department names (including employees without departments):

SELECT e.name, d.dept_name
FROM employees e LEFT JOIN departments d ON e.dept_id = d.dept_id; 

RIGHT OUTER JOIN

Returns all records from the right table plus matching records from the left table. Syntax:

SELECT columns FROM table1 RIGHT JOIN table2 ON table1.id = table2.id; 

Behavior:

FULL OUTER JOIN

Combines results of both LEFT and RIGHT joins - returns all records from both tables. Syntax:

SELECT columns FROM table1 FULL OUTER JOIN table2 ON table1.id = table2.id; 

Behavior:

SQL Constraints

Constraints enforce data integrity rules at the table level; violations cause the operation to fail. Constraint Types: NOT NULL - Column must contain a value

CREATE TABLE users (id INT NOT NULL, ...); 

UNIQUE - Each value in column must be distinct

ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE (email); 

PRIMARY KEY - Combines NOT NULL and UNIQUE

CREATE TABLE products (id INT PRIMARY KEY, ...); 

FOREIGN KEY - Maintains referential integrity between tables

ALTER TABLE orders ADD FOREIGN KEY (customer_id) REFERENCES customers(id); 

CHECK - Validates data against specified condition(s)

ALTER TABLE products ADD CHECK (price > 0); 

DEFAULT - Provides default value when none specified

ALTER TABLE orders ADD created_date DATE DEFAULT CURRENT_DATE; 

ALTER TABLE Operations

Modify existing table structure after creation. Add Column:

ALTER TABLE table_name ADD column_name data_type; 

Remove Column:

ALTER TABLE table_name DROP COLUMN column_name; 

Aggregate Functions

Perform calculations on sets of values and return single results. Usage Locations:

Core Functions: AVG() - Calculate average of numeric values

SELECT AVG(salary) FROM employees;

COUNT() - Count rows or non-null values

SELECT COUNT(*), COUNT(email), COUNT(DISTINCT department) FROM employees; 

MAX() / MIN() - Find highest/lowest values

SELECT MAX(salary), MIN(birth_date) FROM employees; 

SUM() - Total of numeric values

SELECT name, LENGTH(name) as name_length FROM employees; 

GROUP BY and HAVING: GROUP BY - Groups rows sharing common values for aggregate calculations

SELECT department, AVG(salary) FROM employees GROUP BY department; 

HAVING - Filters grouped results (WHERE cannot be used with aggregates)

SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

Remember: Use WHERE for row filtering before grouping, HAVING for filtering after grouping.

5. Normalization

5.1 Functional Dependencies

Functional Dependency

A functional dependency X → Y exists when the value of attribute set X uniquely determines the value of attribute set Y. Formal Definition: For any two tuples t₁ and t₂ in relation R:

X → Y if t₁[X] = t₂[X] then t₁[Y] = t₂[Y]

In simple terms: If two rows have the same values for attributes in X, they must have the same values for attributes in Y. Example: In a Student table with attributes (StudentID, Name, Department):

Key Properties:

Note: Functional dependencies help identify redundancy and guide normalization in database design.

Trivial Functional Dependency

A functional dependency X → Y is trivial if Y ⊆ X. In other words, if the right side is a subset of (or contained within) the left side, the dependency is trivial. Why it's called "trivial": The dependency doesn't provide new information since you're determining attributes you already know. Examples:

Key insight: Trivial dependencies are always satisfied in any relation and don't impose real constraints on the database design. Note: In dependency analysis and normalization, trivial dependencies are often ignored since they don't affect the logical structure of the database.

Example

This content appears to be incomplete or corrupted OCR output. The fragment shows what looks like functional dependency notation but lacks sufficient context to create a meaningful handbook entry. Functional Dependencies are relationships where one attribute uniquely determines another:

A → B

This reads as "A functionally determines B" - meaning for any given value of A, there is exactly one corresponding value of B. Example: In a Student table:

Trivial Dependencies:

Note: Trivial dependencies are always true but don't provide useful information for database design.

Non-trivial Functional Dependency

A functional dependency X → Y is non-trivial when the dependent attributes are not already contained in the determining attributes. Definition: X → Y is non-trivial if X ∩ Y = ∅ This means:

Example: In a Student table with attributes (StudentID, Name, Email, Department):

Why it matters: Non-trivial dependencies are the meaningful constraints that drive database normalization. Trivial dependencies exist automatically and don't reveal actual data relationships. Note: Some definitions allow partial overlap, requiring only Y ⊄ X (Y is not a subset of X). The stricter definition above (X ∩ Y = ∅) ensures complete separation.

Example

This appears to be a functional dependency notation in database design:

CId → CName

This means "Customer ID determines Customer Name" - a functional dependency where:

Interpretation: Each unique Customer ID maps to exactly one Customer Name. If you know the Customer ID, you can uniquely determine the Customer Name. Example: In a customer table:

Note: This is a valid functional dependency since customer IDs are typically unique identifiers, ensuring each ID corresponds to only one customer name.

Armstrong's Axioms

Armstrong's Axioms are fundamental rules for deriving functional dependencies in relational databases. They provide a complete and sound inference system. Primary Axioms: Reflexivity: If Y ⊆ X, then X → Y

Augmentation: If X → Y, then XZ → YZ

Transitivity: If X → Y and Y → Z, then X → Z

Derived Rules: Decomposition: If X → YZ, then X → Y and X → Z

Union: If X → Y and X → Z, then X → YZ

Pseudo-transitivity: If X → Y and WY → Z, then WX → Z

Note: The three primary axioms (reflexivity, augmentation, transitivity) are sufficient to derive all other valid functional dependencies. The derived rules are shortcuts for common inference patterns.

Functional Dependency Set Closure (F⁺)

The closure of a functional dependency set F⁺ contains all functional dependencies that can be logically derived from the original set F, including both trivial and non-trivial dependencies. Testing FD Membership: To check if X → Y belongs to F⁺:

  1. Compute the closure X⁺ using the given FD set F
  2. If Y ⊆ X⁺, then X → Y is in F⁺

Lossless Decomposition: A relational schema R can be decomposed into R₁ and R₂ without losing information if all three conditions hold: Condition 1: R₁ ∪ R₂ = R

Condition 2: R₁ ∩ R₂ ≠ ∅
Condition 3: (R₁ ∩ R₂) → R₁ or (R₁ ∩ R₂) → R₂

Example: Given R(A, B, C, D, E) with FDs: {A → BC, CD → E, B → D, E → A} Decomposition: R₁ = {ABC, ACDE}

From A → BC, we got AC → ABC, so the decomposition is lossless. Remember: The shared attributes in a lossless decomposition act as a "join key" that preserves all original information.

5.2 Attribute Closure

Attribute Closure (X⁺)

The attribute closure of a set X is the complete set of all attributes that can be functionally determined by X. Notation: X⁺ Definition: Given a set of functional dependencies F, the closure X⁺ contains:

Algorithm to find X⁺:

  1. Start with result = X
  2. For each functional dependency Y → Z in F:
  1. Repeat step 2 until no new attributes are added
  2. Return result as X⁺

Example: Given F = {A → B, B → C, CD → E}, find (A)⁺

Key uses:

Example

A relation R(ABCD) with Functional dependencies: {A → B, B → C, C → D} Finding closure of attribute A: To find (A)⁺, we determine all attributes that can be derived from A:

  1. Start with A
  2. From A → B, we get B
  3. From B → C, we get C
  4. From C → D, we get D

Therefore, (A)⁺ = {A, B, C, D} Key insight: Since A can determine all other attributes, A is a candidate key for this relation. Transitive dependency chain A → B → C → D creates a complete dependency path, allowing A to functionally determine every attribute in the relation.

5.3 Canonical Cover (Minimal Cover)

Side Effects of Normalization

Database normalization produces several effects on database structure and operations: Storage Impact:

Query Complexity:

Update Operations:

Functional Dependency Simplification: Normalization transforms functional dependencies into simpler, more manageable forms through three key processes: Decomposition: Breaking compound dependencies into atomic ones

Left Reduction: Removing unnecessary attributes from dependency determinants

Redundancy Elimination: Removing dependencies that can be derived from others

Result: The simplified dependency set maintains the same information while being easier to analyze and implement.

5.4 First Normal Form (1NF)

Normalisation

Database normalization eliminates four key anomalies that occur in poorly designed tables: Insertion Anomaly: Cannot add new data without having unrelated information. For example, unable to add a new course to the system unless a student enrolls in it. Deletion Anomaly: Removing a record causes loss of other valuable information. For example, deleting the last student in a course removes all course details from the database. Update Anomaly: Same information stored in multiple places requires updating all copies, leading to inconsistency if some updates are missed. For example, changing a professor's department requires updating every course record they teach. Join Anomaly: Data that should be together gets split across tables unnecessarily, requiring complex joins to retrieve simple information. This creates performance issues and query complexity. Goal: Normalization restructures tables to store each piece of information in exactly one place, eliminating redundancy while preserving all relationships between data.

Goals of Normalisation

The primary goals of database normalization are to achieve data integrity and maintainability. Data Integrity:

Maintainability:

Key Benefits:

Example: In an unnormalized student-course table, updating a professor's name requires changing multiple rows. After normalization, the professor's name exists once in a separate table, requiring only a single update. Remember: Normalization trades some query complexity for data consistency and reduced redundancy.

5.5 Lossless Join Decomposition

Loss-less Join Decomposition

A decomposition is lossless if joining the decomposed relations produces exactly the original relation - no extra tuples are generated.

Formal condition:

R = R₁ ⋈ R₂

where R is the original relation and R₁, R₂ are the decomposed relations.

Key principle: The natural join of decomposed tables must reconstruct the original table perfectly.

Example: Consider relation R(A, B, C) with tuples:

If decomposed into R₁(A, B) and R₂(B, C):

Then R₁ ⋈ R₂ gives back exactly the original tuples.

Lossy decomposition would generate spurious tuples during the join, violating the equality condition.

Note: Lossless decomposition preserves information but may not preserve all functional dependencies.

5.6 Dependency Preserving Decomposition

Database Design Goals

Database design aims to achieve three fundamental goals:

  1. Zero Redundancy

Eliminate duplicate data storage across tables. Each piece of information should be stored exactly once to prevent inconsistencies and reduce storage overhead.

  1. Lossless Join

Ensure that when normalized tables are joined back together, the original data can be completely restored without any information loss. The decomposition must preserve all original relationships.

  1. Dependency Preservation

Maintain all functional dependencies from the original relation within the decomposed tables. This ensures that all business rules and constraints can still be enforced after normalization.

Trade-offs: In practice, achieving all three goals simultaneously may not always be possible. Database designers must balance these objectives based on specific application requirements and performance considerations.

Example: A student enrollment system should store student details once (zero redundancy), allow reconstruction of complete enrollment records (lossless join), and preserve rules like "each student has one advisor" (dependency preservation).

Dependency Preserving Decomposition

A decomposition preserves dependencies when all original functional dependencies can still be enforced after splitting the relation.

Definition: Given relation R with functional dependencies set F, decomposed into relations R₁, R₂, ... Rₙ with corresponding FD sets F₁, F₂, ... Fₙ. The decomposition is dependency preserving if:

F₁ ∪ F₂ ∪ ... ∪ Fₙ ≡ F

This means the union of all FD sets from decomposed relations is logically equivalent to the original FD set.

Key Insight: After decomposition, we might lose some dependencies because:

Why it matters:

Example: Relation R(A, B, C) with F = {A → B, B → C, A → C}

Remember: Dependency preservation ensures data integrity without costly cross-relation checks.

6. Transactions

6.1 ACID Properties

Transaction Properties (ACID)

ACID Properties ensure reliable transaction processing in databases.

Atomicity - All or Nothing Transaction executes completely or not at all. If any operation fails, the entire transaction is rolled back to its initial state. Example: Bank transfer of $100 from Account A to Account B:

Consistency - Valid State Preservation Database remains in a valid state before and after transaction execution. All integrity constraints and business rules are maintained. Example: If total balance across all accounts is 10,000 before transfer, it remains 10,000 after the transfer completes.

Isolation - Concurrent Independence Multiple transactions executing simultaneously appear to run in isolation from each other. Each transaction sees a consistent view of the database. Example: Two users withdrawing from the same account simultaneously won't see each other's intermediate states, preventing incorrect balance calculations.

Durability - Permanent Changes Once a transaction commits successfully, its changes become permanent, even if the system crashes immediately after. Example: After confirming "Payment Successful", the transaction data survives power failures, system reboots, or hardware issues.

Remember: ACID guarantees data reliability - no partial updates, no invalid states, no interference, no data loss.

6.2 Transaction States

TCL Commands

COMMIT - Permanently saves all changes made in the current transaction in the database. Once committed, changes cannot be undone.

COMMIT;

SAVEPOINT - Creates a checkpoint within a transaction that you can roll back to later. Allows partial rollback without losing the entire transaction.

SAVEPOINT savepoint_name;

ROLLBACK - Undoes all changes made in the current transaction, returning the database to its state before the transaction began.

ROLLBACK;
ROLLBACK TO savepoint_name;

SET TRANSACTION - Defines properties for the current transaction, such as isolation level or access mode.

SET TRANSACTION ISOLATION LEVEL READ COMMITTED; 
SET TRANSACTION READ ONLY;

Transaction Flow Example:

  1. BEGIN TRANSACTION
  2. INSERT INTO users VALUES (1, 'John')
  3. SAVEPOINT sp1
  4. UPDATE users SET name = 'Jane' WHERE id = 1
  5. ROLLBACK TO sp1 - undoes the UPDATE, keeps the INSERT
  6. COMMIT - saves the INSERT permanently

Remember: COMMIT makes changes permanent, ROLLBACK undoes them, SAVEPOINT creates checkpoints for partial rollback.

6.3 View Serializability

Classification of Schedule Based on Serializability

A schedule is serializable if it produces the same result as some serial schedule (transactions executed one after another).

Conflict Serializability Two operations conflict when they:

Conflict patterns:

Operation 1Operation 2
read(x)write(x)
write(x)read(x)
write(x)write(x)

Conflict equivalent schedules: Two schedules are conflict equivalent if one can be transformed into the other by swapping non-conflicting operations.

Conflict serializable: A schedule is conflict serializable if it is conflict equivalent to some serial schedule.

Example: Schedule with T₁: read(x), write(x) and T₂: read(x), write(x)

View Serializability Two schedules are view equivalent if they satisfy all three conditions:

  1. Initial reads: If transaction Tᵢ reads the initial value of item Q in schedule S₁, then Tᵢ must also read the initial value of Q in schedule S₂
  2. Read dependencies: If Tᵢ reads a value of Q written by Tⱼ in schedule S₁, then Tᵢ must read the same value written by Tⱼ in schedule S₂
  3. Final writes: The transaction performing the final write on each data item must be the same in both schedules

View serializable: A schedule is view serializable if it is view equivalent to some serial schedule.

Note: Every conflict serializable schedule is also view serializable, but not vice versa. View serializability is a broader concept that allows more schedules to be considered valid.

6.4 Recoverable Schedules

Remember

Key Relationships Between Schedule Types:

Irrecoverable Schedule A schedule where rollback becomes impossible after a transaction commits, because the original data state cannot be restored.

Scenario: Transaction T₁ writes data, T₂ reads that modified data and commits, then T₁ fails. Since T₂ already committed using T₁'s changes, we cannot roll back T₁ without affecting T₂'s committed state.

Timeline example:

  1. T₁: Read(A), Write(A)
  2. T₂: Read(A) - reads T₁'s modified value
  3. T₂: Commit
  4. T₁: Fails - cannot rollback without undoing T₂'s work

Recoverable Schedule A schedule where if transaction T₂ reads data written by T₁, then T₂ commits before T₁ commits. Rule: Reader commits only after writer commits.

Timeline example:

  1. T₁: Read(A), Write(A)
  2. T₁: Commit
  3. T₂: Read(A) - safe to read committed data
  4. T₂: Write(B), Commit

Cascadeless Recoverable Schedule Stricter than recoverable. If T₂ reads data written by T₁, then T₁ commits before T₂ even reads. Rule: Reader waits until writer commits before reading.

Timeline example:

  1. T₁: Read(A), Write(A)
  2. T₁: Commit - must commit first
  3. T₂: Read(A) - only now can read
  4. T₂: Commit

Note: Every cascadeless schedule is recoverable, but not vice versa.

Cascading Rollback When one transaction failure triggers a chain of rollbacks across multiple dependent transactions. Prevention: Use cascadeless schedules to avoid this domino effect.

Strict Recoverable Schedule Most restrictive: If T₁ writes data item A, no other transaction can read or write A until T₁ commits or rolls back.

Tᵢ ActionTⱼ Restriction
Write(A)Cannot Read(A) or Write(A)
Commit/RollbackNow Tⱼ can access A

Schedule Examples:

Recoverable but not cascadeless:

r₁(x) r₂(x) w₂(x) r₁(y) w₁(y) r₂(y) w₂(x) c₂ c₁ a₂

Irrecoverable:

r₁(x) r₂(x) r₁(z) r₂(z) r₃(z) w₁(x) w₂(y) c₂ a₁ w₃(z)

Serializability Testing Process:

  1. Check conflict serializability: Build precedence graph
  1. Check view serializability: Apply view equivalence conditions

Remember: Conflict serializability is easier to test but more restrictive than view serializability.

7. Concurrency Control

7.1 Lock-Based Protocols

Schedules

A schedule defines the chronological order of instruction execution across multiple concurrent transactions in a database system.

Key characteristics:

Schedule notation:

Example schedule: T₁: R₁(x), W₁(x), R₁(y), W₁(y); T₂: R₂(x), W₂(x), R₂(y), W₂(y)

Possible interleaved schedule:

R₁(x) → R₂(x) → W₁(x) → R₂(y) → W₂(x) → R₁(y) → W₁(y)

Types of schedules:

Note: The goal is to allow concurrency while maintaining data consistency through proper schedule management.

Serial Schedule

A serial schedule executes transactions one after another with no overlap - each transaction must complete entirely before the next one begins.

Key Properties:

Total Serial Schedules: For n transactions, there are n! possible serial schedules. Example: With 3 transactions T₁, T₂, T₃:

Advantage: Zero inconsistency - each transaction sees a consistent database state. Disadvantage: Poor performance due to no parallelism - system resources remain underutilized while waiting for transactions to complete sequentially.

Note: Serial schedules serve as the correctness benchmark for evaluating concurrent schedules through serializability testing.

Concurrent Schedule

A concurrent schedule allows multiple transactions to execute simultaneously, interleaving their operations rather than running sequentially.

Benefits:

Risk: Data inconsistency can occur when transactions interfere with each other's operations. Example: Two transactions accessing the same bank account:

ACID Properties ensure transaction reliability in concurrent environments:

Remember: Concurrency improves performance but requires careful control mechanisms to prevent data corruption and maintain ACID properties.

Conflicts in Concurrent Execution

These types of conflicts occur when transactions execute concurrently on the same data item:

Write-Read (WR) Conflict Also called dirty read or uncommitted read:

Transaction T₁Transaction T₂
W(x)↓
↓R(x)

Transaction T₂ reads data that T₁ has modified but not yet committed. If T₁ rolls back, T₂ has read invalid data. Problem: T₂ may make decisions based on uncommitted changes that could be undone.

Read-Write (RW) Conflict Also called unrepeatable read or inconsistent analysis:

Transaction T₁Transaction T₂
R(x)↓
↓W(x)

Transaction T₂ modifies data after T₁ has read it. If T₁ reads the same data again, it gets a different value. Problem: T₁ cannot reproduce its earlier read within the same transaction.

Write-Write (WW) Conflict Also called lost update:

Transaction T₁Transaction T₂
W(x)↓
↓W(x)

Both transactions write to the same data item. The last write overwrites the first, causing the first update to be lost. Problem: One transaction's changes are completely overwritten by another.

Note: All three conflicts violate the isolation property of ACID transactions and require concurrency control mechanisms to resolve.

Concurrency Control With Locks

Locks ensure that only one transaction can access a data item at a time, preventing conflicts in concurrent systems.

Lock Mechanism:

Locking Protocol: A set of rules that all transactions must follow when requesting and releasing locks. Purpose: Locking protocols restrict which schedules are possible, eliminating those that could cause inconsistencies.

Basic Lock Types:

Example: Transaction T₁ wants to update account balance:

  1. T₁ requests exclusive lock on account record
  2. System grants lock (if available)
  3. T₁ reads current balance: $100
  4. T₁ updates balance: $100 + $50 = $150
  5. T₁ commits and releases lock

Note: Without locks, concurrent transactions could read stale data or overwrite each other's changes, leading to inconsistent database states.

Lock Granularity

Lock granularity refers to the level at which locks are applied in a database system. The granularity determines the size of the data unit being locked.

Granularity Levels (from coarse to fine):

Trade-offs:

GranularityConcurrencyOverhead
Coarse (DB/Table)LowLow
Fine (Row/Field)HighHigh

Concurrency vs Overhead: Finer granularity allows more concurrent transactions but requires more system resources to manage locks.

Example: In a banking system:

Note: Most modern databases use row-level locking as the default for optimal balance between concurrency and performance.

Database Level

Database-level locking locks the entire database as a single unit.

Characteristics:

Usage:

Limitations:

Example scenario: A nightly batch job that processes all customer orders and updates inventory. Since no other users need access during this window, database-level locking ensures data consistency without concurrency concerns.

Remember: This is the coarsest granularity of locking - maximum consistency but minimum concurrency.

Table Level

Table-level locking locks the entire table for the duration of a transaction.

Mechanism: When a transaction needs to access a table, the entire table becomes unavailable to other transactions until the lock is released.

Multiple tables: If a transaction requires access to several tables, each table must be locked separately, creating multiple table-level locks simultaneously.

Major limitation: Table-level locks are unsuitable for multi-user database systems because they create excessive blocking.

Why it fails in multi-user environments:

Example: Transaction A updates one row in a 10,000-row customer table. With table-level locking, Transaction B cannot read any customer data until A completes, even though B needs completely different rows.

Note: Table-level locking is primarily used in single-user systems or for operations that genuinely need to access most/all rows in a table.

Page Level

Page-level locking controls access to entire database pages rather than individual records or tables.

Page structure:

How page-level locking works: When a transaction needs to modify any row on a page, it locks the entire page. Other transactions must wait to access any data on that locked page.

Advantages:

Trade-offs:

Example: If rows R₁, R₂, and R₃ are stored on the same page, locking R₁ prevents access to R₂ and R₃, even if they're unrelated records.

Note: Page-level locking strikes a balance between the fine granularity of row locks and the coarse granularity of table locks, making it popular in many commercial DBMS implementations.

Row-level

Row-level locking allows multiple transactions to simultaneously access different rows within the same table, even when those rows exist on the same data page.

Key characteristics:

Trade-offs:

Example scenario: In a banking table, Transaction A can update account 101 while Transaction B simultaneously updates account 103 , even if both accounts are stored on the same database page.

Remember: Row-level locking maximizes concurrency but increases lock management complexity compared to page-level or table-level locking.

Field-level

Field-level locking allows multiple transactions to access the same database row simultaneously, provided they operate on different columns within that row.

Key characteristics:

Advantage: Maximum concurrency - transactions only block each other when accessing the exact same field.

Disadvantage: Extremely high overhead due to:

Example: In a customer record with fields name, email, phone:

Note: Rarely implemented in practice due to prohibitive overhead costs. Most systems use row-level or page-level locking instead.

Binary Locks

Binary locks provide the simplest form of concurrency control in database systems. Each data item has exactly two possible states:

Lock State = { 1 (locked - unavailable); 0 (unlocked - available) }
Lock State =1 (locked - unavailable)0 (unlocked - available)
This diagram shows the two possible states of a binary lock. Lock State can be one of only two values. If the lock state is 1, the data item is locked and unavailable to other transactions. If the lock state is 0, the data item is unlocked and available. The takeaway is that a binary lock is either fully locked or fully unlocked, with no in-between state.

Lock Protocol:

Example: Transaction T₁ wants to read account balance:

  1. Request lock on account record
  2. If unlocked, acquire lock, read balance
  3. Complete operation, release lock
  4. Now other transactions can access the account

Major Limitations:

Note: Binary locks are too restrictive for practical database systems. Most systems use shared/exclusive locks instead to allow multiple readers simultaneously.

Shared (S Mode)

Shared locks allow multiple transactions to read the same data item simultaneously without conflicts.

When granted:

Characteristics:

Lock compatibility:

Example: If transactions T₁, T₂, and T₃ all need to read account balance, they can all acquire shared locks on the same data item without waiting for each other.

Remember: Shared locks enable concurrent reads but prevent any writes until all shared locks are released.

Exclusive (X Mode)

Exclusive (X) Lock Mode grants complete access control to a single transaction:

X - Lock: Exclusive Read + Write Access

Properties:

When to use X-locks:

Lock Compatibility Matrix:

Current LockRequested LockCompatible
NoneExclusive (X)Yes
Shared (S)Exclusive (X)No
Exclusive (X)Exclusive (X)No
Exclusive (X)Shared (S)No

Example: Transaction T₁ wants to update account balance:

  1. T₁ requests X-lock on Account(101)
  2. System grants lock (assuming no conflicts)
  3. T₁ reads current balance: 1000, T₁ updates balance: 1000 - 500 = 500
  4. T₁ commits and releases X-lock

Remember: X-locks ensure write isolation - no other transaction can interfere during the update process, preventing lost updates and inconsistent reads.

Note

Lock Compatibility Matrix

A transaction can acquire a lock on an item only if the requested lock is compatible with existing locks held by other transactions.

Lock TypeShared (S)Exclusive (X)
Shared (S)✓ Compatible✗ Incompatible
Exclusive (X)✗ Incompatible✗ Incompatible

Read as: Row lock can coexist with Column lock on the same data item.

Key Rules:

Common Locking Problems

Non-serializable Schedules:

Deadlocks:

Remember: Shared locks allow concurrent reads, exclusive locks ensure isolated writes.

7.3 Two-Phase Locking (2PL)

Two-phase Locking

Two phase locking (2PL) is a protocol that ensures serializability by controlling when transactions can acquire and release locks.

Protocol Phases:

Growing Phase: Transaction acquires all required locks without releasing any existing locks. The transaction reaches its lock point when all necessary locks are obtained.

Shrinking Phase: Transaction releases locks and cannot acquire any new locks.

Core Rules:

  1. Lock Compatibility: Conflicting transactions cannot hold locks on the same data item simultaneously
  2. No Early Release: A transaction cannot release any lock until it has acquired all locks it needs
  3. No Re-acquisition: Once a transaction enters shrinking phase, it cannot acquire new locks
  4. Deferred Updates: Data modifications are postponed until all required locks are secured

Lock Progression:

Start → Growing Phase → Lock Point → Shrinking [Phase]
StartGrowing PhaseLock PointShrinking Phase
This diagram shows how a transaction's locks progress through two-phase locking, from left to right. First the transaction starts. Then it enters the growing phase, where it only acquires locks. Next it reaches its lock point, the moment it holds every lock it needs. After that it moves into the shrinking phase, where it only releases locks and can acquire no new ones. The takeaway is that all locking happens before the lock point and all unlocking happens after it.

Example Timeline:

Key Insight: The lock point divides the transaction - before it, only locking; after it, only unlocking.

Guarantee: 2PL ensures conflict-serializable schedules, preventing issues like lost updates and inconsistent reads.

Basic 2pl Protocol

The Basic Two-Phase Locking (2PL) protocol ensures serializability by dividing each transaction into two phases:

  1. Growing Phase: Transaction can only acquire locks, cannot release any
  2. Shrinking Phase: Transaction can only release locks, cannot acquire any

The lock point is when a transaction transitions from growing to shrinking phase (acquires its last lock).

Serializability in Basic 2PL:

Transactions following basic 2PL produce schedules equivalent to serial schedules ordered by their lock points.

Example: If transaction T₁ has lock point before T₂, the schedule is equivalent to serial schedule T₁ → T₂.

Problems with Basic 2PL:

  1. Irrecoverability

A committed transaction may have read data from an uncommitted transaction that later aborts.

Scenario:

Result: T₂ used invalid data but already committed - cannot rollback.

  1. Deadlock

Two or more transactions wait indefinitely for each other's locks.

Example:

  1. Starvation

A transaction waits indefinitely because other transactions keep acquiring the needed resources.

Scenario: Transaction T waits for lock on X, but other transactions continuously acquire and release the same lock before T gets a chance.

Note: Basic 2PL guarantees serializability but requires additional mechanisms to handle these three critical problems.

Class Diagram of Schedules With Serializability

Database schedules form a hierarchy based on their properties and guarantees. Understanding this classification helps determine which concurrency control mechanisms to use.

Schedule Classification Hierarchy:

Schedules can be classified into nested categories, each providing stronger guarantees than the outer levels:

Strict ⊂ Cascadeless ⊂ Recoverable ⊂ All Schedules
All SchedulesRecoverableCascadelessStrict
This diagram shows the hierarchy of schedule classes, read from left to right. Strict schedules are a subset of cascadeless schedules. Cascadeless schedules are a subset of recoverable schedules. And recoverable schedules are a subset of all schedules. The takeaway is that the classes are nested: every strict schedule is automatically cascadeless and recoverable, and each step to the right is a weaker, wider class with fewer guarantees.

Recoverable Schedules:

A schedule where if transaction Tⱼ reads data written by Tᵢ, then Tᵢ commits before Tⱼ commits.

Property: Prevents reading uncommitted data that might be rolled back.

Cascadeless Schedules:

A schedule where transactions read only committed data - no transaction reads from uncommitted transactions.

Property: Eliminates cascading rollbacks when a transaction aborts.

Strict Schedules:

A schedule where transactions neither read nor write data written by uncommitted transactions.

Property: Provides the strongest isolation - transactions appear to run in complete isolation.

Serializability Types:

Two main approaches to ensure schedule correctness:

Conflict Serializability:

A schedule is conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations.

Conflicts occur when:

View Serializability:

A schedule is view serializable if it produces the same result as some serial schedule for all possible initial database states.

Relationship: Conflict Serializable ⊂ View Serializable

Two Phase Locking (2PL) Hierarchy:

Locking protocols also form a nested hierarchy with increasing restrictions:

Basic 2PL:

Guarantees: Conflict serializability

Strict 2PL:

Basic 2PL + all exclusive locks held until transaction commits/aborts.

Additional guarantee: Prevents cascading rollbacks

Rigorous 2PL:

Strict 2PL + all locks (shared and exclusive) held until transaction commits/aborts.

Additional guarantee: Strictest isolation, simplest deadlock handling

Example: In a banking system, rigorous 2PL ensures that when transferring money between accounts, no other transaction can see intermediate states or interfere until the transfer completes.

Remember: Each inner protocol provides all guarantees of outer protocols plus additional safety properties.

7.5 Strict and Rigorous 2PL

Strict 2pl Protocol

Strict Two-Phase Locking (Strict 2PL) extends basic 2PL by holding ALL locks until transaction completion.

Protocol Rules:

Lock Hold Time = Entire Transaction Duration

Guarantees:

Serializability: Ensures conflict-serializable schedules by preventing interleaved access to shared data

Strict Recoverability: Eliminates cascading rollbacks since no transaction reads uncommitted data from others.

Example Execution:

Transaction T₁ modifies account balance:

  1. Acquire exclusive lock on Account A
  2. Read balance: 1000
  3. Update balance: 1200
  4. Hold lock through remaining operations
  5. Release lock only at commit

Other transactions wait until T₁ completes, ensuring they see only committed values.

Limitations:

Deadlock Risk: Multiple transactions waiting for each other's locks can create circular dependencies.

Reduced Concurrency: Longer lock hold times mean fewer transactions can execute simultaneously.

Performance Impact: Higher waiting times compared to basic 2PL, especially in high-contention scenarios.

Note: Despite limitations, Strict 2PL is widely used because it guarantees both serializability and recoverability without complex recovery mechanisms.

Rigorous 2pl Protocol

The Rigorous 2-Phase Locking (2PL) protocol is a stricter version of basic 2PL that ensures serializability by controlling when locks can be released.

Protocol Rules:

In Rigorous 2PL, transactions must:

This differs from basic 2PL where locks could be released after use, as long as no new locks were acquired afterward.

Serializability Guarantee:

The equivalent serial schedule follows the commit order of transactions:

Tᵢ → Tⱼ if commit(Tᵢ) < commit(Tⱼ)

Example: If T₁ commits at time 12 and T₂ commits at time 15, then the serial order is T₁ → T₂

Key Benefits:

Remember: "Rigorous" means rigorous about holding locks - keep everything locked until you're completely done.

7.6 Timestamp Ordering Protocol

Time Stamp Ordering Protocols

Timestamp Ordering Protocol assigns a unique global timestamp to each transaction, creating a submission order that determines execution sequence.

Core Mechanism:

Key Advantages:

  1. Deadlock-free: No transaction ever waits for another - conflicts are resolved immediately by aborting the younger transaction
  2. Guarantees serializability: The timestamp order defines a valid serial execution order that all concurrent executions must respect

Basic Rules:

Trade-off: While eliminating deadlocks, timestamp ordering may cause more transaction rollbacks compared to lock-based protocols, especially under high contention.

Note: Timestamps can be system clock values.

Basic Time Stamp Ordering Protocol

Basic Timestamp Ordering Protocol:

Each transaction gets a unique timestamp TS(Tᵢ) when it starts. Data items maintain:

Read Operation Rule:

Write Operation Rule:

Thomas Write Rule:

Relaxes basic protocol for better performance:

Read Operation: Same as basic protocol

Write Operation W(x):

Key difference: Obsolete writes are ignored instead of causing rollback.

Strict Timestamp Ordering:

Prevents cascading rollbacks by enforcing commit dependencies:

Transaction Tⱼ with operation on item x where TS(Tⱼ) > W-TS(x) must wait until the transaction that wrote x commits or aborts.

Wait-Die Protocol:

Older transactions wait, younger transactions die:

Wound-Wait Protocol:

Older transactions wound younger ones:

Remember:

File Organization and Indexing

9.1 Primary Index

Sequential File

Blocking Factor determines how many records fit in one disk block:

Blocking Factor = ⌊ Block Size / Record Size ⌋

Total Blocks Required to store all records:

Number of Record Blocks = ⌈ Total Records / Blocking Factor ⌉

Search Performance:

Linear Search - examines blocks sequentially until record is found:

Average Blocks Accessed = ⌈ Number of Record Blocks / 2 ⌉

Binary Search - requires sorted file, divides search space in half:

Average Blocks Accessed = ⌈ log₂(Number of Record Blocks) ⌉

Example: File with 1,000 records, 4KB blocks, 100-byte records

Note: Binary search requires the file to be sorted on the search key.

8.2 Secondary Index

Clustered Index

A clustered index physically orders database records based on the search key values.

Key Properties:

Index Structure:

The clustered index creates a sparse index where each entry points to the first record of each distinct search key value.

Storage Calculation:

Number of index blocks needed:

Index blocks = ⌈ Distinct values / Index blocking factor ⌉

Access Cost:

Total block accesses for a search:

Block accesses = ⌈log₂(Index blocks)⌉ + 1

The +1 accounts for accessing the actual data block after navigating the index.

Example: For a table with employee records clustered by department:

Remember: Clustered index is most efficient for range queries on the clustering attribute since related records are stored together physically.

Secondary Index

A secondary index uses a search key that differs from the file's ordering key, allowing searches on non-primary attributes.

Key characteristics:

Block access formula:

Block accesses = ⌈log₂(Index blocks)⌉ + 1

The +1 accounts for accessing the actual data block after navigating the index.

Index blocking factor:

All index levels use the same blocking factor, determined by:

Blocking factor = Block size / Index entry size

Example: For a file with 10,000 records and index blocking factor of 100:

Note: Secondary indexes are essential for efficient queries on non-primary attributes, but require additional storage overhead compared to primary indexes.

8.3 Dense vs Sparse Index

Dense Index

A dense index contains an entry for every single record in the database file.

Key characteristic: One-to-one mapping between data records and index entries.

Number of index entries = Number of data records

Structure: Each index entry contains:

Example: Database with 1000 student records requires exactly 1000 index entries, one pointing to each student record.

Advantage: Direct access to any record through its index entry.

Disadvantage: Large index size - grows proportionately with database size.

Note: Dense indexes are typically used for primary keys where every record must be directly accessible.

Sparse Index

A sparse index contains fewer entries than the total number of database records. Each index entry points to a database block rather than individual records.

Key characteristics:

Structure:

Index entries = Database blocks < Total records

How it works:

Example: Database with 1000 records stored in 50 blocks:

Advantage: Smaller index size means faster index searches and less storage overhead.

Requirement: Records must be sorted by the indexed attribute for sparse indexing to work correctly.

8.4 Multilevel Index

Index File

An index file provides fast access to data records by maintaining pointers for record retrieval .

Index Blocking Factor:

The number of index entries that fit in one index block.

Index blocking factor = ⌈ number of record blocks / 2 ⌉ + 1

This formula accounts for the overhead needed to maintain the index structure efficiently.

First Level Index Blocks:

Number of index blocks needed at the first level:

First level blocks = ⌈ number of record blocks / Index blocking factor ⌉

This represents how many index blocks are required to cover all data records.

Block Access Calculation:

Total block accesses needed to locate a record:

Block accesses = ⌈log₂(First level index blocks)⌉ + 1

The logarithmic term represents traversing the index levels, while the +1 accounts for accessing the actual data block.

Example: For 1000 record blocks:

Note: These formulas assume a binary search structure through the index levels.

Indexing Types

Database indexing organizes data for faster retrieval. Two main categories exist based on structure depth:

Single Level Index

Primary Index (Sparse):

Clustered Index (Sparse):

Secondary Index (Dense):

Multilevel Index:

When single-level indexes become too large to fit in memory, multilevel structures provide efficient access:

Indexed Sequential Access Method (ISAM):

B-tree Index:

B+-tree Index:

Key difference: B-trees store data at all levels, while B+-trees concentrate data in leaves and use internal nodes purely for indexing.

Multilevel Index (Static level index):

A multilevel index creates a hierarchy of index levels to reduce search time in large databases.

Structure Rules:

Computing Index Levels:

For any level n ≥ 2:

Blocks at level n = ⌈ Blocks at level (n − 1) / Index blocking factor ⌉

The top level is reached when:

Blocks at level n = 1

Key Metrics:

Total index blocks across all levels:

Total blocks = Σ (blocks at level i), summed from i = 1 to n

Block accesses for search:

Access cost = n + 1

where n is the number of index levels, plus 1 for the final data block access.

Example: Database with 1000 data blocks, index blocking factor = 100

Result: 3 levels, 1011 total index blocks, 4 accesses per search.

Remember: Each level reduces the search space by the blocking factor until reaching a single root block.

MUST DO

8.5 B+ Tree

Tree

A B+ tree is a variation of the B-tree with key differences in structure and access patterns.

Key Characteristics:

Sequential Access Advantage:

Each leaf node contains a pointer to the next leaf node, creating a linked list at the bottom level. This allows efficient range queries and sequential data retrieval without traversing back up the tree.

Node Order Calculations:

For non-leaf nodes (internal nodes):

p × (block pointer size) + (p − 1) × (key size) ≤ Block size

For leaf nodes:

(p_leaf − 1) × (keysize + recordpointersize) + (block pointersize) ≤ Block size

where:

Note: Leaf nodes need space for one block pointer to link to the next leaf, while internal nodes need p child pointers but only (p − 1) keys.

Access Pattern Comparison: