DBMS Complete Notes
DBMS Complete Notes
SYSTEMS
Complete Syllabus Notes & Reference Guide
Covers: DBMS Fundamentals • ER & Relational Modeling • Relational Algebra & Calculus •
SQL • Normalization & Functional Dependencies • Transactions & ACID • Concurrency
Control • Recovery • Indexing & File Organization • Query Processing & Optimization •
Distributed & NoSQL Databases
Table of Contents
2.2 Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.3 Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2
Database Management Systems — Notes
5.7 Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.9 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10 Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
7.3 Schedules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
7.4 Recoverability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Concurrency Control 29
9.4 Checkpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3
Database Management Systems — Notes
10.3 Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4
Database Management Systems — Notes
CHAPTER 1
Introduction to Database Management
Systems
A database is an organized collection of related data stored in a structured form so that it can be
efficiently accessed, managed, and updated. A Database Management System (DBMS) is the
software layer that sits between the physical data and the applications or users that need it. It provides
a systematic way to create, retrieve, update, and manage data while enforcing rules that keep that
data accurate and secure.
• Data redundancy and inconsistency: the same data (e.g., a customer's address) was often
duplicated across multiple files maintained by different programs, so updating it in one place but
not another left the data inconsistent.
• Difficulty in accessing data: every new question about the data (e.g., 'list all customers in a given
pin code') required a programmer to write a new program, because file systems offer no
general-purpose query capability.
• Data isolation: data was scattered across files in different, often incompatible, formats, making it
hard to write programs that combined data from multiple files.
• Integrity problems: business rules ('an account balance may not go below zero') had to be
hard-coded into every program that touched the data, and were easy to forget.
• Atomicity problems: if a program crashed midway through an operation involving several file
updates (e.g., a funds transfer), the files could be left in a partially updated, inconsistent state.
• Concurrent-access anomalies: when multiple users update the same file simultaneously without
coordination, updates can be lost or the file can become corrupted.
• Security problems: it is hard to give every user exactly the access they need (and no more) when
access control has to be enforced by each individual application.
A DBMS was designed specifically to eliminate or drastically reduce all of these problems by
centralizing data management under one piece of software that every application talks to.
5
Database Management Systems — Notes
• Providing storage structures and search techniques (indexes, hashing) for efficient query
processing.
• Providing backup and recovery so data is not lost due to system or media failure.
• Providing multiple user interfaces: query languages for casual users, APIs for application
programmers, forms and menus for parametric users.
• Representing complex relationships among data using a data model.
• Enforcing integrity constraints that must hold for the data (data types, uniqueness, referential
relationships, business rules).
• Permitting inferencing and actions using rules and triggers (active database capability).
Database Administrator (DBA) Has central control over the system: schema definition,
storage structure, access authorization, and coordination
among users.
Sophisticated/Casual Users Interact with the system by issuing queries and updates
using a query language (e.g., analysts writing SQL).
6
Database Management Systems — Notes
• External level (view level): describes the part of the database that a particular user group is
interested in, hiding the rest. Many external views can exist for one database.
• Conceptual level (logical level): describes what data is stored and the relationships among the data
for the whole database, independent of any particular application.
• Internal level (physical level): describes how the data is actually stored — file organization,
indexes, data structures, and access paths used by the storage engine.
Physical data independence — the capacity to change the internal/physical schema (e.g., add a
new index, switch storage engine) without needing to change the conceptual schema, so application
programs are unaffected.
Logical data independence — the capacity to change the conceptual schema (e.g., add a new
entity or attribute) without having to change existing external schemas or the application programs
written against them.
Record-based Used to specify the overall logical Relational model, Network model,
(representational/implementation) structure of the database using Hierarchical model
records of a fixed format.
7
Database Management Systems — Notes
Physical (low-level) Describe how data is actually stored File organizations, indexing
on the storage medium. structures
Note: In practice SQL is a single language that bundles DDL, DML, DCL and TCL statements together,
which is why it is often called a comprehensive or universal database language rather than a purely
declarative DML.
8
Database Management Systems — Notes
CHAPTER 2
The Entity-Relationship (ER) Model
The Entity-Relationship model is a high-level conceptual data model that lets a database designer
describe the data of an organization independent of any DBMS software. It views the real world as a
set of basic objects (entities) and the relationships among them, and is typically drawn as an ER
diagram during the database design phase.
Entity — a real-world object that is distinguishable from other objects. An entity has a set of
properties (attributes), and the values of some subset of attributes must uniquely identify it (e.g., a
specific STUDENT with student_id = 2027045).
Entity Set — a collection of entities of the same type sharing the same attributes (e.g., the set of all
STUDENT entities).
Attribute — a property that describes an entity. Attributes are drawn as ellipses in an ER diagram.
Types of attributes
• Simple (atomic) attribute — cannot be divided further, e.g., age.
• Composite attribute — can be divided into sub-parts, e.g., name = {first_name, last_name}.
• Single-valued attribute — has only one value for a given entity, e.g., ssn.
• Multi-valued attribute — can have multiple values, e.g., a person can have several phone numbers;
drawn as a double ellipse.
• Derived attribute — its value can be calculated/derived from other attributes, e.g., age can be
derived from date_of_birth; drawn as a dashed ellipse.
• Key attribute — uniquely identifies each entity in the entity set; underlined in a diagram.
2.2 Relationships
A relationship is an association among two or more entities. A relationship set is a collection of
relationships of the same type, and is drawn as a diamond connected to the participating entity sets.
Degree of a relationship
• Unary (recursive) — relates an entity to itself, e.g., an EMPLOYEE 'supervises' another
EMPLOYEE.
• Binary — relates two entity sets, by far the most common, e.g., STUDENT enrolls-in COURSE.
• Ternary — relates three entity sets, e.g., SUPPLIER supplies PART to PROJECT.
9
Database Management Systems — Notes
One-to-Many (1:N) An entity in A can be associated with One DEPARTMENT has many
many entities in B, but an entity in B EMPLOYEEs; each EMPLOYEE
is associated with at most one entity belongs to one DEPARTMENT.
in A.
Many-to-One (N:1) The reverse of one-to-many, viewed Many EMPLOYEEs work in one
from the other side. DEPARTMENT.
Participation constraints
• Total participation: every entity in the entity set must participate in at least one relationship instance
(drawn as a double line). Example: every EMPLOYEE must work in some DEPARTMENT.
• Partial participation: only some entities need to participate (drawn as a single line). Example: not
every EMPLOYEE manages a DEPARTMENT.
2.3 Keys
Alternate Key a candidate key that was not chosen as the primary key.
10
Database Management Systems — Notes
Constraints on specialization/generalization
• Disjoint vs. overlapping: in a disjoint constraint an entity can belong to at most one subclass; in an
overlapping constraint it may belong to more than one.
• Total vs. partial: a total specialization requires every superclass entity to belong to some subclass;
a partial specialization allows entities that belong to no subclass.
Aggregation
Aggregation is an abstraction in which relationship sets (along with their entity sets) are treated as
higher-level entity sets, allowing a relationship to participate in another relationship. This is used when
a relationship set itself needs to be associated with another entity — for instance, treating the
relationship 'WORKS_ON(EMPLOYEE, PROJECT)' as a single unit so it can also be associated with
a MANAGER who monitors that assignment.
11
Database Management Systems — Notes
ER diagram: STUDENT enrolls in COURSE (M:N relationship with a descriptive attribute 'grade')
In this example, STUDENT and COURSE are entity sets connected through the ENROLLS
relationship set, which is many-to-many (a student can enroll in many courses and a course can have
many students). The attribute grade belongs to the relationship itself, since a grade only makes sense
in the context of a specific student-course pairing, not for the student or course alone.
12
Database Management Systems — Notes
CHAPTER 3
The Relational Model
The relational model, proposed by E. F. Codd in 1970, represents data and relationships among data
as a collection of two-dimensional tables called relations. It remains the dominant data model used by
commercial DBMSs today (MySQL, PostgreSQL, Oracle, SQL Server) because of its simplicity and
strong mathematical foundation.
Relation Table
13
Database Management Systems — Notes
• Referential integrity constraint: a value of a foreign key must either match a value of the primary
key it references in the other relation, or be entirely NULL. This constraint is what actually
implements relationships between tables.
• General/semantic (business rule) constraints: additional rules specified by the database
designer/administrator, e.g., 'an employee's salary may not exceed the salary of their manager'.
Action Effect
SET NULL The foreign key column in the referencing rows is set to
NULL.
SET DEFAULT The foreign key column in the referencing rows is set to
a predefined default value.
1 Strong entity → becomes a relation with all its simple/simple-composite attributes; the entity's key
becomes the relation's primary key.
2 Weak entity → becomes a relation whose attributes include its own partial key plus the primary key
of its owner entity (as a foreign key); the primary key of the new relation is the combination of both.
3 1:1 relationship → the primary key of one relation is placed as a foreign key in the other (commonly
on the side with total participation), or the two relations can be merged.
4 1:N relationship → the primary key of the 'one' side is placed as a foreign key in the relation on the
'many' side.
5 M:N relationship → a new relation is created, with the primary keys of both participating entities as
foreign keys, together forming the composite primary key of the new relation. Any descriptive
attributes of the relationship (like 'grade') are added to this new relation.
6 Multi-valued attribute → becomes its own relation, with a foreign key referencing the owner entity's
primary key.
7 Specialization/Generalization → can be mapped in one of several ways: (a) one relation per
subclass plus one for the superclass ('one table per subtype + supertype'), (b) one relation per
subclass only (attributes of the superclass are copied into every subclass table), or (c) a single
relation for the whole hierarchy with a 'type' discriminator column and nullable columns for
subclass-specific attributes.
14
Database Management Systems — Notes
15
Database Management Systems — Notes
CHAPTER 4
Relational Algebra and Relational
Calculus
Relational algebra and relational calculus are formal, mathematically precise query languages that
operate on relations and form the theoretical foundation of SQL. Relational algebra is procedural — a
query specifies a sequence of operations to be performed on existing relations to derive the desired
result. Relational calculus is non-procedural — a query describes the desired result without specifying
how to obtain it.
16
Database Management Systems — Notes
17
Database Management Systems — Notes
Note: Relational algebra, tuple relational calculus, and domain relational calculus (when restricted to safe
expressions) are all provably equivalent in expressive power — this equivalence result is why SQL, which
resembles calculus in its declarative SELECT syntax, can still be evaluated internally by translating it into an
algebra expression that the query optimizer manipulates.
18
Database Management Systems — Notes
CHAPTER 5
Structured Query Language (SQL)
SQL (Structured Query Language) is the standard declarative language used to define, manipulate,
and control data in a relational DBMS. It is declarative in the sense that the user specifies what data is
wanted, and the DBMS's query optimizer determines the most efficient way to retrieve it.
19
Database Management Systems — Notes
Note: This distinction matters: because WHERE is logically evaluated before SELECT, a WHERE clause
cannot reference a column alias defined in SELECT. Because HAVING is evaluated after GROUP BY,
HAVING can filter on aggregate values, whereas WHERE cannot.
-- Left outer join (keep all Employees, even those with no department)
SELECT [Link], [Link]
FROM Employee e LEFT JOIN Department d ON [Link] = [Link];
-- Self join (find employees who earn more than their manager)
SELECT [Link] AS employee, [Link] AS manager
FROM Employee e1 JOIN Employee e2 ON e1.mgr_id = [Link]
WHERE [Link] > [Link];
Common aggregate functions: COUNT, SUM, AVG, MIN, MAX. COUNT(*) counts all rows including
duplicates and NULLs; COUNT(column) counts only non-NULL values in that column.
5.7 Subqueries
20
Database Management Systems — Notes
-- Employees who earn more than the company average (scalar subquery)
SELECT name FROM Employee
WHERE salary > (SELECT AVG(salary) FROM Employee);
Note: A correlated subquery references a column from the outer query and is conceptually re-evaluated
once for every row of the outer query, whereas a non-correlated (simple) subquery is evaluated exactly
once.
5.9 Views
A view is a virtual table defined by a stored query; it does not itself store data (unless materialized),
and is recomputed from its base tables every time it is referenced. Views are used to simplify complex
queries, present a restricted/customized window of data to a class of users (a security mechanism),
and provide logical data independence.
A view is generally updatable (INSERT/UPDATE/DELETE through it will affect the underlying base
table) only if it is defined on a single table without aggregate functions, DISTINCT, GROUP BY, or set
operations.
5.10 Indexes
CREATE INDEX idx_emp_dno ON Employee(dno);
CREATE UNIQUE INDEX idx_dept_name ON Department(dname);
21
Database Management Systems — Notes
22
Database Management Systems — Notes
CHAPTER 6
Functional Dependencies and
Normalization
Normalization is a step-by-step, formal process of organizing the attributes and relations of a database
in order to minimize data redundancy and eliminate undesirable characteristics called update
anomalies. It is driven by the theory of functional dependencies.
For example, in Employee(eid, name, dno, dname), eid -> name holds (each employee id determines
exactly one name), and dno -> dname holds (each department number determines exactly one
department name).
• Insertion anomaly: to record that a new course exists, but no student has enrolled yet, we would be
forced to insert a row with a NULL student_id, which may violate a key constraint.
• Deletion anomaly: if the only student enrolled in a course drops it and that row is deleted, we lose
all information about the course (its name, its instructor) along with the student's row.
• Update anomaly: if an instructor's name changes, every row for every student enrolled in that
instructor's course must be updated; missing even one row leaves the data inconsistent.
23
Database Management Systems — Notes
FDs:
order_id, product_id -> quantity
cust_id -> cust_name, cust_city
product_id -> product_name, unit_price
order_id -> cust_id
This relation has cust_name and cust_city transitively dependent on order_id (through cust_id), and
product_name/unit_price transitively dependent on order_id (through product_id) — a clear violation
of 3NF. Decomposing it removes the redundancy:
24
Database Management Systems — Notes
Each customer's name/city is now stored exactly once, each product's name/price is stored exactly
once, and the OrderItem relation records only the facts specific to a particular order line — this is now
free of the insertion, deletion, and update anomalies described above.
Note: It is always possible to decompose a relation into BCNF such that the decomposition is lossless, but
it is not always possible to simultaneously guarantee dependency preservation. 3NF, in contrast, can
always be achieved with both properties satisfied simultaneously — this trade-off is one reason 3NF is often
accepted as 'good enough' in practical database design.
25
Database Management Systems — Notes
CHAPTER 7
Transaction Management and the ACID
Properties
A transaction is a single logical unit of work that accesses and possibly modifies the contents of a
database, typically comprising one or more SQL statements. Transactions are the mechanism by
which a DBMS guarantees that the database moves from one consistent state to another, even in the
presence of concurrent access and system failures.
Property Meaning
7.3 Schedules
A schedule is a sequence that indicates the chronological order in which instructions of concurrent
transactions are executed. A serial schedule is one in which the transactions are executed one
completely after another with no interleaving — serial schedules are always correct (they trivially
preserve consistency, assuming each transaction individually does) but they offer no concurrency and
26
Database Management Systems — Notes
Serializability
A schedule is called serializable if its effect on the database is equivalent to that of some serial
schedule of the same transactions. Since serial schedules are known to be correct, a serializable
schedule is guaranteed to leave the database in a consistent state, while still allowing operations from
different transactions to interleave for better performance.
Conflict serializability of a given schedule can be tested efficiently by constructing a precedence graph
(serialization graph): a node for every transaction, and a directed edge Ti -> Tj whenever Ti has an
operation that conflicts with, and precedes, an operation of Tj. The schedule is conflict-serializable if
and only if this graph is acyclic.
7.4 Recoverability
• Recoverable schedule: if a transaction Tj reads a data item previously written by Ti, then the
commit operation of Ti must appear before the commit operation of Tj. This guarantees that the
DBMS is never forced to permanently commit a transaction that read uncommitted ('dirty') data
from a transaction that later aborts.
• Cascadeless (avoids cascading rollback) schedule: a transaction is permitted to read a value
written by another transaction only after that other transaction has committed — this prevents a
single abort from forcing a chain of other transactions to also abort.
• Strict schedule: a transaction can neither read nor overwrite a data item written by another
transaction until that other transaction has committed or aborted — strict schedules simplify
recovery, since undoing a transaction just means restoring the old value.
27
Database Management Systems — Notes
28
Database Management Systems — Notes
CHAPTER 8
Concurrency Control
Concurrency control refers to the protocols a DBMS uses to guarantee that concurrently executing
transactions produce a serializable (and hence correct) outcome, without sacrificing more throughput
than necessary.
Shared lock (S) Other S locks Held to read a data item; multiple
transactions may hold a shared lock
on the same item simultaneously.
Exclusive lock (X) No other locks Held to write a data item; only one
transaction may hold an exclusive
lock on an item, and no other
transaction may hold any lock on it
at the same time.
1 Growing phase: the transaction may acquire locks, but may not release any lock.
2 Shrinking phase: the transaction may release locks, but may not acquire any new lock.
It is a proven theorem that if every transaction in a schedule follows 2PL, the resulting schedule is
guaranteed to be conflict-serializable. Basic 2PL, however, can still suffer from cascading rollbacks
(because locks can be released before commit). Strict 2PL fixes this by holding all exclusive locks until
the transaction commits or aborts, and Rigorous 2PL (the variant most commercial systems actually
use) holds both shared and exclusive locks until commit/abort, which additionally guarantees
strictness and produces a schedule equivalent to the serial order in which transactions committed.
Deadlock
2PL does not prevent deadlock — a cyclic situation where transaction T1 waits for a lock held by T2,
which in turn waits for a lock held by T1. DBMSs handle deadlock either by prevention (e.g., the
wait-die and wound-wait schemes, which use transaction timestamps to decide whether a transaction
should wait or be forced to abort/restart) or by detection and recovery (periodically building a wait-for
graph and aborting a transaction — the 'victim' — whenever a cycle is found).
29
Database Management Systems — Notes
Each transaction is assigned a unique timestamp when it begins, and every data item records the
timestamp of the most recent transaction that read it (read_TS) and the most recent one that wrote it
(write_TS). The protocol ensures conflicting operations execute in timestamp order: if a transaction
attempts an operation that would violate this order (e.g., it tries to write a value that a 'younger'
transaction has already read), it is rejected and restarted with a new, later timestamp. This guarantees
conflict-serializability without using locks at all, avoiding deadlock entirely, though at the cost of
potentially restarting transactions.
• Dirty read: a transaction reads a value written by another transaction that has not yet committed
(and might later be rolled back).
• Non-repeatable read: a transaction re-reads a row it read before, and finds that another committed
transaction has modified or deleted it in the meantime.
• Phantom read: a transaction re-executes a query with a search condition, and finds that another
committed transaction has inserted new rows that now satisfy that condition.
30
Database Management Systems — Notes
31
Database Management Systems — Notes
CHAPTER 9
Database Recovery Techniques
Recovery is the process by which a DBMS restores the database to a consistent, correct state after a
failure — whether a transaction failure, a system crash, or a media/disk failure. Recovery techniques
rely heavily on maintaining a log: a sequential record of all updates made to the database.
Write-Ahead Logging (WAL) rule — before a data item's value is written to the actual database (on
disk), the corresponding log record describing that update must first be written to stable storage.
This guarantees that if the system crashes after a database write but before the log record makes it
to disk, the update could be lost and undetectable — WAL prevents exactly this scenario, and is the
single most important rule underlying crash recovery.
9.4 Checkpoints
Scanning the entire log after a crash to determine which transactions to redo/undo becomes
prohibitively slow as the log grows. A checkpoint periodically (a) forces all log records currently in main
32
Database Management Systems — Notes
memory to stable storage, (b) forces all modified buffer (database) pages to disk, and (c) writes a
record to the log, where L is the list of transactions active at checkpoint time. During recovery, the
DBMS only needs to examine the log starting from the most recent checkpoint, since any transaction
that committed before that point is guaranteed to already be durable on disk.
1 Analysis pass: scans the log forward from the last checkpoint to identify which transactions were
active (need undoing) and which data pages were 'dirty' at the moment of the crash, and
determines the point in the log at which the REDO pass must begin.
2 Redo pass: scans forward from the point determined by the analysis pass, and redoes every
logged update (regardless of whether the transaction that made it eventually committed or aborted)
to restore the database to exactly the state it was in at the instant of the crash — this is the 'repeat
history' principle central to ARIES.
3 Undo pass: scans the log backward, undoing the writes of every transaction that was still active
(had not committed) at the time of the crash, restoring the database to a consistent,
transaction-atomic state.
A key feature of ARIES is that log records themselves carry a Log Sequence Number (LSN), and each
database page stores the LSN of the last log record that updated it — this allows the redo pass to skip
updates that are already reflected in the page on disk, making recovery idempotent (safe to interrupt
and restart, since a crash during recovery itself simply causes the whole process to run again).
33
Database Management Systems — Notes
34
Database Management Systems — Notes
CHAPTER 10
Storage Structures, File Organization, and
Indexing
Heap (unordered) file Records are placed in the file in no Fast inserts; full table scans; small
particular order, typically in insertion tables.
order.
Sequential (sorted) file Records are physically sorted on a Range queries and ordered retrieval
chosen ordering (search) key. on the sort key; but expensive to
maintain the order on insert/delete.
Hash file Records are placed into buckets Very fast exact-match lookups on
based on applying a hash function to the hash key; poor for range queries.
a chosen hash key.
Clustered file Records from two or more related Speeding up joins that are almost
tables that are frequently joined always executed together.
together are stored physically near
each other.
10.3 Indexing
An index is an auxiliary access structure built on one or more columns of a table, designed to speed
up retrieval of records that satisfy a given search condition, at the cost of extra storage space and the
overhead of maintaining the index whenever the underlying table changes.
35
Database Management Systems — Notes
Primary index An ordered file whose records have a fixed length with
two fields; the first holds a value of the primary key of the
data file, and the second is a pointer to the
corresponding data block; built only on a data file
ordered on its key field.
Secondary index An ordered file with an entry for every record (not just
every distinct block, as with a primary/clustering index) of
the data file, built on any non-ordering field. A table can
have any number of secondary indexes.
Dense index Has an index entry for every search-key value (and
hence every record) in the data file.
Sparse index Has an index entry only for some of the search-key
values (typically one per block), requiring a subsequent
scan within the block to locate the exact record.
A B+-tree index — internal nodes only guide the search; all actual data pointers live in the leaf nodes, which are
chained together for fast range scans.
36
Database Management Systems — Notes
• Internal (non-leaf) nodes contain only search-key values and pointers to child nodes, used purely
to guide the search down the tree; they contain no data pointers themselves.
• Leaf nodes contain every search-key value along with either the actual data record or a pointer to
it, and are linked together in a doubly linked list, so once the search reaches the correct leaf, a
range query can be answered by simply following these leaf-level links sequentially rather than
re-traversing the tree.
• The tree is always kept height-balanced — every path from the root to a leaf has the same length
— which guarantees that lookups, insertions, and deletions all run in O(log n) time even in the
worst case, regardless of the pattern of past insertions/deletions.
• A B-tree (without the '+') differs in that data pointers are also stored in internal nodes, which saves
some space but forecloses the leaf-chaining trick, making B-trees less common than B+-trees in
practice for range-heavy relational workloads.
37
Database Management Systems — Notes
CHAPTER 11
Query Processing and Optimization
Query processing is the sequence of steps a DBMS takes to translate a high-level declarative query
(SQL) into a low-level, efficient sequence of operations on the physical data, and then execute it.
Linear (full table) scan Always applicable; examines every block of the file.
38
Database Management Systems — Notes
Nested-loop join For every tuple in the outer relation, O(|R| x |S|) in the worst case — the
scan the entire inner relation looking simplest but generally the slowest
for matches. algorithm.
Block nested-loop join A refinement that processes the Number of blocks of the outer
inner relation one block at a time relation.
against an entire block of the outer
relation held in memory, reducing
the number of times the inner
relation must be re-scanned.
Index nested-loop join For each tuple of the outer relation, Requires a suitable index on the
use an index on the join attribute of inner relation's join attribute.
the inner relation to directly retrieve
matching tuples, instead of
scanning.
Sort-merge join Both relations are sorted (or already Cost of sorting each relation (if not
ordered via an index) on the join already sorted), then a linear merge
attribute, and then merged in a pass.
single coordinated linear pass,
similar to the merge step of
merge-sort.
Hash join A hash function is applied to the join Very efficient when the smaller
attribute of the smaller ('build') relation's hash table fits in memory;
relation to partition it into an the standard default algorithm in
in-memory hash table; the larger most modern optimizers for
('probe') relation is then scanned equijoins.
once, and each tuple's hash value is
used to find matches directly.
• Push SELECT operations down the query tree as early as possible (perform selections/filters
before joins), since this reduces the number of tuples that later, more expensive operations must
process.
• Push PROJECT operations down the tree similarly, keeping only the attributes actually needed at
each step, to reduce the size of intermediate results.
• Combine a CARTESIAN PRODUCT immediately followed by a SELECT into a single, more
efficient JOIN operation.
• Reorder the sequence of JOIN operations so that the join producing the smallest intermediate
result executes first.
• Perform SELECT and PROJECT operations before any JOIN, so that the relations being joined are
as small as possible.
39
Database Management Systems — Notes
Unlike an ordinary view, a materialized view physically stores the result of its defining query, trading
extra storage space and the need for periodic refresh against significantly faster read performance —
a common technique for pre-computing expensive aggregate queries in data-warehouse and reporting
systems.
40
Database Management Systems — Notes
CHAPTER 12
An Introduction to Distributed Databases
and NoSQL Systems
• Fragmentation: dividing a relation into smaller pieces distributed across sites. Horizontal
fragmentation splits a relation by rows (each site gets a subset of the tuples, e.g., by region);
vertical fragmentation splits it by columns (each site gets a subset of the attributes, typically
together with the primary key so the pieces can be rejoined).
• Replication: storing copies of the same data at multiple sites, improving availability and read
performance, at the cost of extra work needed to keep the copies synchronized.
• Distributed transactions and the Two-Phase Commit (2PC) protocol: to keep a transaction that
touches multiple sites atomic, a coordinator first asks every participating site to 'prepare' (and
confirm it can commit) in a voting phase, and only issues the actual 'commit' to every site in a
second phase if all sites voted yes — guaranteeing that either every site commits or every site
aborts.
41
Database Management Systems — Notes
Key-Value stores A simple map from a Redis, DynamoDB, Riak Caching, session storage,
unique key to an opaque simple lookups at very
value/blob. high throughput.
Graph databases Data modeled explicitly as Neo4j, Amazon Neptune Social networks,
nodes and the (typed, recommendation engines,
directed) edges between fraud detection,
them, optimized for knowledge graphs.
traversal.
Consistency model Strong consistency, full ACID Often eventual consistency (BASE),
transactions though many modern systems now
offer tunable/strong consistency too
42