Database Management Systems

ER modelling through to recovery: keys, relational algebra, the SQL that gets asked, normalisation up to BCNF, indexing, ACID, concurrency control and the NoSQL contrast.

If you remember nothing else

  • A primary key is unique and never null; a candidate key is any minimal set that could serve as one; a foreign key references another relation's key.
  • 1NF removes repeating groups, 2NF removes partial dependencies, 3NF removes transitive dependencies, BCNF requires every determinant to be a superkey.
  • ACID: Atomicity (all or nothing), Consistency (valid states only), Isolation (concurrent looks serial), Durability (committed survives a crash).
  • Two-phase locking guarantees serialisability but not freedom from deadlock — strict 2PL additionally prevents cascading rollback.
  • An index makes reads faster and writes slower; it is a trade, never a free win.
  • The isolation anomalies in order of severity: dirty read, non-repeatable read, phantom read — each removed by a higher isolation level.

Why a DBMS, and the three-schema architecture

Problem with plain filesWhat a DBMS provides
Data redundancy and inconsistencyNormalisation and a single source of truth
No enforced structureSchemas, types and integrity constraints
Difficult ad-hoc queriesA declarative query language with an optimiser
No concurrency handlingTransactions, locking, isolation levels
Partial updates on crashAtomicity and recovery from a write-ahead log
No access controlUsers, roles, privileges

The ER model

ElementMeaningNotation
EntityA distinguishable real-world objectRectangle
Weak entityCannot be identified without an owner entityDouble rectangle
AttributeA property of an entityEllipse
Key attributeUniquely identifies an entityUnderlined ellipse
Multivalued attributeMay hold several values (phone numbers)Double ellipse
Derived attributeComputed from others (age from date of birth)Dashed ellipse
Composite attributeDecomposes further (address → street, city)Ellipse with sub-ellipses
RelationshipAn association between entitiesDiamond

The relational model and keys

KeyDefinitionNulls?How many per table
Super keyAny attribute set that uniquely identifies a rowMany
Candidate keyA minimal super key — no attribute can be removedNoOne or more
Primary keyThe chosen candidate keyNever nullExactly one
Alternate keyA candidate key not chosen as primaryNoZero or more
Composite keyA key made of two or more attributesNo
Foreign keyReferences a candidate key of another (or the same) relationMay be nullZero or more
Surrogate keyAn artificial identifier with no business meaningNoUsually one

Relational algebra

OperationSymbolDoesSQL equivalent
SelectionPicks rows matching a predicateWHERE
ProjectionPicks columnsSELECT list
UnionAll rows in either (must be union-compatible)UNION
Set differenceRows in the first but not the secondEXCEPT
Cartesian productEvery pairing of rowsCROSS JOIN
RenameRenames a relation or attributeAS
Natural joinJoin on all common attributesNATURAL JOIN
Division"Find rows related to all of a set"No direct equivalent

The first six are the primitive operators; join and division are derived from them.

SQL that actually gets asked

Sub-languageCommandsPurpose
DDLCREATE, ALTER, DROP, TRUNCATEDefine structure
DMLSELECT, INSERT, UPDATE, DELETEManipulate data
DCLGRANT, REVOKEControl access
TCLCOMMIT, ROLLBACK, SAVEPOINTManage transactions
JoinReturns
INNER JOINOnly rows with a match on both sides
LEFT OUTER JOINAll left rows; nulls where the right has no match
RIGHT OUTER JOINAll right rows; nulls where the left has no match
FULL OUTER JOINAll rows from both sides, nulls where unmatched
CROSS JOINCartesian product — every combination
SELF JOINA table joined to itself, e.g. employee to manager
SQLThe query-clause execution order
SELECT d.name, COUNT(*) AS headcount, AVG(e.salary) AS avg_salary FROM employees e JOIN departments d ON d.id = e.dept_id WHERE e.hired_at >= '2020-01-01' -- filters ROWS, before grouping GROUP BY d.name HAVING COUNT(*) > 5 -- filters GROUPS, after aggregation ORDER BY avg_salary DESC LIMIT 10; -- Logical evaluation order (NOT the written order): -- FROM -> JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT -- -- This is why a SELECT alias cannot be used in WHERE (SELECT has not run yet) -- but CAN be used in ORDER BY (it has).
SQLThe two classic query questions
-- 1. Second-highest salary (correlated subquery version) SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); -- The general N-th highest, using a window function: SELECT DISTINCT salary FROM ( SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk FROM employees ) t WHERE rnk = 2; -- 2. Find and remove duplicates, keeping the lowest id DELETE FROM employees WHERE id NOT IN (SELECT MIN(id) FROM employees GROUP BY email);

Functional dependencies and normalisation

Normalisation exists to remove update, insertion and deletion anomalies — the situations where redundant storage lets the database contradict itself.

FormRequirementRemoves
1NFAll attributes atomic; no repeating groups or multivalued fieldsRepeating groups
2NF1NF, and every non-key attribute fully depends on the whole primary keyPartial dependencies (only relevant with a composite key)
3NF2NF, and no non-key attribute depends on another non-key attributeTransitive dependencies
BCNFFor every dependency , X is a superkeyAnomalies from overlapping candidate keys
4NFBCNF, and no non-trivial multivalued dependenciesIndependent multivalued facts in one table
5NF4NF, and no join dependency not implied by candidate keysRemaining join anomalies
Plain textWorking the normal forms on one example
UNNORMALISED StudentID | Name | Courses | Dept | DeptHead 1 | Rina | DB, OS, Networks | CSE | Dr. Khan 1NF - make values atomic (one course per row): StudentID | Name | Course | Dept | DeptHead 1 | Rina | DB | CSE | Dr. Khan 1 | Rina | OS | CSE | Dr. Khan Primary key is now (StudentID, Course). 2NF - Name, Dept and DeptHead depend only on StudentID, which is PART of the composite key. That is a partial dependency. Split: STUDENT(StudentID, Name, Dept, DeptHead) ENROLMENT(StudentID, Course) 3NF - in STUDENT, StudentID -> Dept -> DeptHead. DeptHead depends on a non-key attribute, so it is transitive. Split again: STUDENT(StudentID, Name, Dept) DEPARTMENT(Dept, DeptHead) ENROLMENT(StudentID, Course) Now: changing the head of CSE is ONE update, not one per student.

Indexing and storage

Clustered indexNon-clustered index
Determines physical row orderYesNo
Number per tableAt most oneMany
Leaf level containsThe actual data rowsKey plus a pointer or the clustering key
Range query speedExcellent — rows are already adjacentSlower — each hit may need a separate lookup
Extra lookup neededNoYes, unless the index covers the query
Index typeGood forPoor for
B+ treeEquality, ranges, ordering, prefix matchesVery low-cardinality columns
HashExact equality onlyAny range query — hashing destroys ordering
BitmapLow-cardinality columns in analytics (gender, status)High-update OLTP tables
Full-textWord and phrase search inside documentsStructured comparisons

Transactions and ACID

  1. Atomicity

    All operations commit or none do. A transfer that debits one account and fails before crediting the other must leave no trace. Implemented by the undo log.
  2. Consistency

    A transaction moves the database from one valid state to another, respecting every declared constraint. This one is partly the application's responsibility, not purely the DBMS's.
  3. Isolation

    Concurrent transactions produce the same result as some serial execution. Implemented by locking or by multi-version concurrency control.
  4. Durability

    Once committed, the effect survives a crash. Implemented by forcing the write-ahead log to stable storage before acknowledging the commit.
Transaction stateMeaning
ActiveExecuting
Partially committedFinal statement executed; changes still in buffers
CommittedSuccessfully completed and durable
FailedNormal execution can no longer proceed
AbortedRolled back; the database is restored to its prior state

Schedules and serialisability

Two operations conflict if they belong to different transactions, act on the same data item, and at least one is a write. Read-read never conflicts.

AnomalyWhat happensPrevented from
Dirty readT2 reads a value T1 wrote but has not committed; T1 then abortsRead Committed
Non-repeatable readT2 reads the same row twice and gets different values, because T1 updated it in betweenRepeatable Read
Phantom readT2 re-runs a range query and finds new rows, because T1 inserted matching rowsSerializable
Lost updateTwo transactions read then write the same item; one overwrites the otherRepeatable Read and above
Isolation levelDirty readNon-repeatable readPhantom read
Read UncommittedPossiblePossiblePossible
Read CommittedPreventedPossiblePossible
Repeatable ReadPreventedPreventedPossible
SerializablePreventedPreventedPrevented

Higher isolation means less concurrency. Most systems default to Read Committed; the correct level is a deliberate trade, not an oversight.

Concurrency control and recovery

ApproachMechanismBest when
Pessimistic (locking)Acquire a lock before access; block conflicting transactionsConflicts are common — the lock cost is worth it
Optimistic (validation)Execute freely, then validate at commit and abort on conflictConflicts are rare — most transactions never pay a cost
Timestamp orderingEach transaction gets a timestamp; conflicting operations must respect that order or abortDeadlock-free by construction, but more aborts
MVCCWriters create a new version; readers see a consistent snapshotRead-heavy workloads — readers never block writers. Used by PostgreSQL and Oracle

Recovery

  1. Analysis

    Scan forward from the last checkpoint to determine which transactions were active at the crash.
  2. Redo

    Replay every logged change from the checkpoint forward, restoring the exact state at the moment of the crash — including changes made by transactions that had not committed.
  3. Undo

    Roll back every transaction that had not committed, walking their log records backwards. What remains is exactly the committed state.

NoSQL and the CAP theorem

FamilyModelGood atExamples
Key-valueOpaque value under a keyCaching, sessions — the simplest and fastestRedis, DynamoDB
DocumentSelf-describing JSON-like documentsVarying schemas, nested dataMongoDB, CouchDB
Column-familyRows with sparse, grouped columnsHuge write volumes, time seriesCassandra, HBase
GraphNodes and edges as first-class objectsTraversals — social graphs, fraud, recommendationsNeo4j, Neptune
SQL (relational)NoSQL
SchemaFixed, enforced up frontFlexible or absent
ScalingPrimarily vertical; sharding is manual workHorizontal by design
Consistency modelStrong (ACID)Often eventual (BASE)
JoinsFirst-classLimited or absent — denormalise instead
Best forComplex relationships, transactional integrityHuge volume, simple access patterns, evolving schemas

Self-check

12 questions on Database Management Systems · nothing is stored

0/12 answered
Question 1

1.A relation is in 2NF but not 3NF. What must be removed to reach 3NF?

Question 2

2.Two-phase locking guarantees:

Question 3

3.Which anomaly is possible at Repeatable Read but not at Serializable?

Question 4

4.A table can have at most one clustered index because:

Question 5

5.In relational algebra, σ (sigma) performs:

Question 6

6.With a composite index on (last_name, first_name), which query CANNOT use it?

Question 7

7.The write-ahead logging rule requires that:

Question 8

8.Under the CAP theorem, a distributed database experiencing a network partition must sacrifice:

Question 9

9.Which is true of TRUNCATE compared to DELETE?

Question 10

10.WHERE salary = NULL returns no rows because:

Question 11

11.A schedule is conflict serialisable if and only if its precedence graph:

Question 12

12.In converting an M:N relationship to tables you must: