Skip to content

DBMS: Complete MCQ Revision Notes ​

Legend: ⭐ = asked very often · ⚠️ = trap / commonly confused · All numerical examples were checked by running code.

Contents

  1. Fundamentals
  2. ER Model and ER→Table mapping
  3. Relational Model, Keys and Constraints
  4. Relational Algebra and Calculus
  5. SQL (execution order, NULLs, aggregates, joins, subqueries, DDL/DML, views, indexes, triggers, window functions, must-know queries)
  6. Functional Dependencies
  7. Normalization
  8. Transactions and Schedules
  9. Concurrency Control
  10. Recovery
  11. Storage, File Organization, Hashing, RAID
  12. Indexing, B-tree and B+ tree
  13. Query Processing and Optimization
  14. Distributed DB, NoSQL/CAP, Data Warehousing/OLAP, DB Security
  15. Rapid-fire trap list (read this the night before)

1. Fundamentals ​

1.1 File system vs DBMS ​

Problems with file-processing systems that a DBMS solves (Korth's list) ⭐:

  1. Data redundancy and inconsistency
  2. Difficulty in accessing data (new query = new program)
  3. Data isolation (data scattered in different files/formats)
  4. Integrity problems (constraints buried in application code)
  5. Atomicity problems (partial updates after failure)
  6. Concurrent-access anomalies
  7. Security problems

DBMS disadvantages: cost (hardware, software, training), complexity, performance overhead for small/simple apps.

1.2 Core terms ​

  • Database = collection of related data. DBMS = software to define, build, manipulate and share it. Database system = DB + DBMS (+ applications).
  • Metadata = data about data. Stored in the data dictionary / system catalog ⭐.
  • Schema = logical design, changes rarely = intension. Instance = data at a given moment, changes often = extension / database state ⭐.
  • Subschema = schema at the view level.

1.3 Three-schema (ANSI/SPARC) architecture ⭐ ​

LevelAlso calledDescribes
ExternalView levelWhat a particular user/app sees (many external schemas)
ConceptualLogical levelWhat data is stored and the relationships (one per DB)
InternalPhysical levelHow data is stored (files, records, indexes, blocks)

Two mappings: external/conceptual and conceptual/internal.

1.4 Data independence ⭐⭐ ​

  • Physical data independence: change the internal schema (new index, different file organization, new storage device) without changing the conceptual schema. Easier to achieve.
  • Logical data independence: change the conceptual schema (add/remove attributes, split a table) without changing external schemas or application programs. Harder to achieve ⚠️.

1.5 Data models ​

  • Hierarchical: tree, parent–child (IBM IMS).
  • Network: graph of records and sets (CODASYL/DBTG, IDMS).
  • Relational: tables (E. F. Codd, 1970, IBM) ⭐.
  • Entity–Relationship: conceptual design (Peter Chen, 1976) ⭐.
  • Object-oriented, object-relational (PostgreSQL), semi-structured (XML/JSON), NoSQL.
  • Elmasri's classification: high-level/conceptual (ER), representational/implementation (relational, network, hierarchical), low-level/physical.

1.6 Database languages ⭐⭐ ​

CategoryCommands
DDL (Data Definition)CREATE, ALTER, DROP, TRUNCATE, RENAME, COMMENT
DML (Data Manipulation)SELECT, INSERT, UPDATE, DELETE, MERGE
DCL (Data Control)GRANT, REVOKE
TCL (Transaction Control)COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION
DQL (some books only)SELECT
  • ⚠️ TRUNCATE is DDL, not DML.
  • ⚠️ SELECT is DML in Korth and most MCQs. Choose DQL only if the options make that the intended category.
  • DDL output (metadata) goes into the data dictionary.
  • Procedural DML: specify what and how (relational algebra). Declarative / non-procedural DML: specify only what (SQL, relational calculus) ⭐.
  • Elmasri also lists SDL (storage definition language) and VDL (view definition language).

1.7 Users and the DBA ​

  • Users: naive (forms/apps), application programmers, sophisticated (write queries), specialized (CAD, expert systems, multimedia).
  • DBA (central control over data and programs): schema definition, storage structure and access-method definition, schema and physical-organization modification, granting authorization, routine maintenance (backups, disk space, monitoring performance).

1.8 DBMS components ⭐ ​

  • Query processor: DDL interpreter, DML compiler (includes the query optimizer), query evaluation engine.
  • Storage manager: authorization and integrity manager, transaction manager (concurrency control + recovery), file manager, buffer manager.
  • On disk: data files, data dictionary, indices, statistical data.

1.9 Architectures ​

  • 1-tier, 2-tier (client app talks directly to the DB server through ODBC/JDBC; business logic on the client), 3-tier (client β†’ application server β†’ DB; web apps) ⭐.
  • Centralized, client–server, parallel (shared memory, shared disk, shared nothing, hierarchical), distributed.

1.10 Codd's 12 rules (actually 13, numbered 0–12) ​

0 Foundation rule Β· 1 Information rule (all data stored as values in tables) Β· 2 Guaranteed access (table name + PK + column) Β· 3 Systematic treatment of NULLs Β· 4 Active online relational catalog Β· 5 Comprehensive data sublanguage Β· 6 View updating Β· 7 High-level insert/update/delete (set-at-a-time) Β· 8 Physical data independence Β· 9 Logical data independence Β· 10 Integrity independence Β· 11 Distribution independence Β· 12 Non-subversion.


2. ER Model ​

2.1 Chen notation ⭐ ​

SymbolMeaning
RectangleStrong entity set
Double rectangleWeak entity set
EllipseAttribute
Double ellipseMultivalued attribute
Dashed ellipseDerived attribute
Ellipse with child ellipsesComposite attribute
Underlined nameKey attribute
Dashed underlinePartial key (discriminator) of a weak entity
DiamondRelationship set
Double diamondIdentifying relationship (for a weak entity)
Double lineTotal participation
Arrow (Korth)Points to the "one" side

2.2 Attributes ​

  • Simple vs composite (Name β†’ First, Last; Address β†’ Street, City).
  • Single-valued vs multivalued (phone numbers).
  • Stored vs derived (Age derived from DOB).
  • Key attribute; NULL-able attributes; complex attributes (composite and multivalued nested).

2.3 Relationships ​

  • Degree: unary/recursive (one entity set, uses role names, e.g., employee manages employee), binary, ternary, n-ary.
  • Cardinality ratio: 1:1, 1:N, N:1, M:N.
  • Participation: total (every entity takes part; existence dependency; double line) vs partial.
  • (min, max) notation (Elmasri): the pair written beside an entity says how many relationship instances each entity takes part in. min β‰₯ 1 means total participation. ⚠️ Its placement is the reverse of how cardinality ratios / crow's foot are usually read.
  • Descriptive attributes on relationships: for 1:N they can move to the N side; for 1:1 to either side; for M:N they must stay in the relationship table.
  • ⚠️ A ternary relationship is generally not equivalent to three binary relationships.

2.4 Weak entity ⭐⭐ ​

  • Has no key of its own. Identified by its owner (identifying) entity + its partial key (discriminator).
  • Always total participation in the identifying relationship, which is many (weak) to one (owner).
  • PK of the weak entity's table = PK of owner + discriminator.
  • Examples: Dependent (of Employee), Payment (of Loan), Room (of Building).

2.5 Extended ER (EER) ​

  • Specialization (top-down: define subclasses) and generalization (bottom-up: combine into a superclass). Drawn with an ISA triangle. Subclasses inherit attributes and relationships.
  • Constraints: disjoint (d) vs overlapping (o); total vs partial (completeness). Also predicate-defined vs user-defined membership.
  • Aggregation: treat a relationship set (together with its entities) as a higher-level entity so it can take part in another relationship (relationship among relationships) ⭐.
  • Category / union type (Elmasri).

2.6 ER β†’ relational mapping ⭐⭐⭐ ​

ER constructResult
Strong entityOne table. Composite attributes β†’ only their simple components. Derived attributes usually not stored
Multivalued attributeSeparate table (entity PK + attribute), PK = both
Weak entityTable containing owner's PK (as FK) + partial key; PK = both. Identifying relationship needs no table
1:1 relationshipPut FK on either side (prefer the side with total participation)
1:N relationshipFK on the N side; no separate table
M:N relationshipSeparate table; PK = PKs of both sides (+ descriptive attributes)
Ternary / n-arySeparate table with FKs to all participants
Recursive 1:NSelf-referencing FK in the same table (emp.manager_id β†’ emp.emp_id)
Recursive M:NSeparate table with two FKs to the same table
Specialization(a) superclass table + subclass tables (subclass PK = FK to superclass); (b) only subclass tables (works for total specialization); (c) one table + type attribute (disjoint); (d) one table + boolean flags (overlapping)

Minimum number of tables (GATE-style) ⭐⭐

  • 1:N β†’ 2 tables (relationship merged into the N side), whatever the participation.
  • M:N β†’ 3 tables, whatever the participation.
  • 1:1, both sides partial β†’ 2 tables (relationship merged into either side).
  • 1:1 with total participation on at least one side β†’ the two entities can be merged into 1 table (common GATE answer; textbook Korth still keeps 2 entity tables).
  • Each multivalued attribute β†’ +1 table.
  • Owner + weak entity β†’ 2 tables.
  • Example: E1 β€”M:Nβ€” E2, and E1 has one multivalued attribute β†’ E1, E2, R, MV = 4 tables.

3. Relational Model, Keys and Constraints ​

3.1 Terminology ⭐ ​

  • Relation = table; tuple = row; attribute = column; domain = set of allowed atomic values.
  • Degree (arity) = number of attributes (columns); cardinality = number of tuples (rows) ⭐.
  • Properties of a relation in the formal model: no duplicate tuples; tuple order doesn't matter; attribute order doesn't matter (attributes are named); values atomic.
  • ⚠️ SQL tables are multisets (bags): duplicates are allowed unless a key constraint exists.

3.2 Keys ⭐⭐⭐ ​

KeyDefinition
Super keyAny set of attributes that uniquely identifies a tuple
Candidate keyMinimal super key (no proper subset is a super key)
Primary keyThe candidate key chosen by the designer. NOT NULL + UNIQUE. Only one per table
Alternate (secondary) keyCandidate keys not chosen as PK
Composite keyKey with β‰₯ 2 attributes
Foreign keyAttribute(s) referring to the PK or a UNIQUE key of another (or the same) table
Surrogate keySystem-generated (auto-increment, UUID), no business meaning
Natural keyReal-world identifier used as key (email, Aadhaar no.)
Unique keyUnique values but NULL allowed (DBMS-specific, see SQL)
  • Every candidate key is a super key; not every super key is a candidate key.
  • Every relation has at least one candidate key (the whole attribute set is a super key because tuples are distinct).
  • Prime attribute: belongs to at least one candidate key. Non-prime: belongs to none.
  • Foreign key facts ⚠️: may be NULL; may repeat; needs the same domain, not the same name; can reference a UNIQUE key, not only a PK; can be self-referencing; a table can have many FKs.

3.3 Counting formulas ⭐⭐ ​

  • n attributes, single candidate key with k attributes β†’ super keys = 2^(nβˆ’k).
  • Two candidate keys K1, K2 β†’ 2^(nβˆ’|K1|) + 2^(nβˆ’|K2|) βˆ’ 2^(nβˆ’|K1 βˆͺ K2|) (inclusion–exclusion; extend the same way for 3 keys).
  • Maximum super keys on n attributes = 2^n βˆ’ 1 (when every single attribute is a key).
  • Maximum candidate keys on n attributes = C(n, ⌊n/2βŒ‹) (n = 4 β†’ 6, n = 5 β†’ 10, n = 6 β†’ 20).
RelationCandidate keysSuper keys
R(A,B,C,D)A8
R(A,B,C,D)A, B12
R(A,B,C,D)A, BC10
R(A,B,C,D)AB, CD7
R(A,B,C,D)AB, BC6
R(A,B,C,D,E)AB8

3.4 Integrity constraints ⭐ ​

  • Domain constraint (type, range, CHECK).
  • Key constraint (uniqueness).
  • Entity integrity: PK cannot be NULL.
  • Referential integrity: an FK value must match an existing referenced key value, or be NULL.
  • Semantic/general constraints: assertions, triggers.

Which operations can violate referential integrity? ⭐⭐

OperationOn parent (referenced) tableOn child (referencing) table
INSERTNever violatesMay violate (FK value not in parent)
DELETEMay violate (orphans)Never violates
UPDATEMay violate (if key value changes)May violate (if FK changes)

Referential actions (ON DELETE / ON UPDATE): CASCADE, SET NULL, SET DEFAULT, RESTRICT, NO ACTION (default in most DBMSs; NO ACTION is checked at the end of the statement, RESTRICT immediately).


4. Relational Algebra and Calculus ​

4.1 Operators ⭐⭐ ​

TypeOperators
Fundamental (6)Οƒ select, Ο€ project, βˆͺ union, βˆ’ set difference, Γ— Cartesian product, ρ rename
Derived∩ intersection (= R βˆ’ (R βˆ’ S)), joins β‹ˆ (theta, equi, natural), Γ· division, ← assignment
ExtendedGeneralized projection, aggregation 𝒒 (Ξ³), outer joins βŸ• βŸ– βŸ—
  • Unary: Οƒ, Ο€, ρ. Binary: βˆͺ, βˆ’, Γ—, ∩, β‹ˆ, Γ·.
  • Οƒ picks rows (horizontal subset); Ο€ picks columns (vertical subset).
  • ⚠️ Ο€ removes duplicates (set semantics). SQL SELECT does not; you need DISTINCT.
  • Union compatibility (needed for βˆͺ, ∩, βˆ’): same degree and compatible domains, attribute by attribute.
  • R Γ— S: degree = d(R) + d(S), cardinality = |R| Γ— |S| ⭐.

4.2 Properties ​

  • Οƒ is commutative and cascades: Οƒc1(Οƒc2(R)) = Οƒc2(Οƒc1(R)) = Οƒc1∧c2(R).
  • Ο€ cascade: Ο€L1(Ο€L2(R)) = Ο€L1(R) when L1 βŠ† L2 (only the last projection matters).
  • βˆͺ, ∩, β‹ˆ, Γ— are commutative and associative (ignoring column order). βˆ’ is neither ⚠️.
  • Οƒ distributes over βˆͺ, ∩, βˆ’: Οƒ(R βˆ’ S) = Οƒ(R) βˆ’ S = Οƒ(R) βˆ’ Οƒ(S).
  • Ο€ distributes over βˆͺ but not over βˆ’ or ∩ ⚠️.
  • ΞΈ-join = σθ(R Γ— S).

4.3 Joins ⭐⭐ ​

  • Natural join: equality on all common attributes; each common attribute appears once.
    • ⚠️ No common attributes β†’ natural join = Cartesian product.
    • Same schema β†’ R β‹ˆ S = R ∩ S. R β‹ˆ R = R.
  • Equi-join: ΞΈ-join using only "="; keeps both copies of the join columns.
  • Outer joins keep unmatched tuples, padded with NULLs (left βŸ•, right βŸ–, full βŸ—).
  • Semi-join (⋉): tuples of R that have a match in S (only R's attributes). Anti-join (β–·): tuples of R with no match.

Result-size bounds (|R| = m, |S| = n) ⭐⭐

OperationMinMax
R Γ— SmΒ·nmΒ·n
R β‹ˆ S (natural)0mΒ·n
R β‹ˆ S on R.FK = S.PK, FK NOT NULL with referential integritymm (exactly m)
R βŸ• S (left outer)mmΒ·n (if n β‰₯ 1)
R βŸ— S (full outer)max(m, n)max(mΒ·n, m + n)
R βˆͺ Smax(m, n)m + n
R ∩ S0min(m, n)
R βˆ’ S0m
Οƒ(R)0m
Ο€(R)1 (if m β‰₯ 1)m

4.4 Division ⭐⭐ ​

  • R(A, B) Γ· S(B) = the A-values in R that are paired with every B-value in S. Used for "for all / every" queries ("students who took ALL courses").
  • R Γ· S = Ο€A(R) βˆ’ Ο€A((Ο€A(R) Γ— S) βˆ’ R).
  • Degree of the result = d(R) βˆ’ d(S); S's attributes must be a subset of R's.

4.5 Relational calculus ​

  • TRC (tuple relational calculus): {t | P(t)}; variables range over tuples (basis of SQL).
  • DRC (domain relational calculus): {<x1, …, xn> | P(x1, …, xn)}; variables range over domain values (basis of QBE).
  • Both are non-procedural ⭐.
  • Unsafe expressions (e.g., {t | Β¬R(t)}) give infinite results, so only safe expressions are allowed.
  • Expressive power: relational algebra = safe TRC = safe DRC (Codd's theorem). A language that can express every RA query is relationally complete. SQL is relationally complete and more (aggregates, ordering, recursion via CTEs).
  • ⚠️ Basic relational algebra cannot express transitive closure (recursive queries).
  • βˆ€x P ≑ Β¬βˆƒx Β¬P.

5. SQL ​

5.1 Logical execution order ⭐⭐⭐ ​

FROM (+ JOIN … ON) β†’ WHERE β†’ GROUP BY β†’ HAVING β†’ SELECT (expressions, aliases) β†’ DISTINCT β†’ ORDER BY β†’ LIMIT / OFFSET (TOP / FETCH)

Consequences:

  • ⚠️ A column alias cannot be used in WHERE (it doesn't exist yet). It can be used in ORDER BY. (MySQL and PostgreSQL also accept aliases in GROUP BY, and MySQL in HAVING. That is non-standard.)
  • ⚠️ Aggregates are not allowed in WHERE; use HAVING.
  • ORDER BY may use columns that are not in the SELECT list, except when SELECT DISTINCT is used.

5.2 WHERE vs HAVING ⭐⭐ ​

WHEREHAVING
Filters rows before groupingFilters groups after grouping
No aggregate functionsAggregates allowed
Works without GROUP BYUsually with GROUP BY; without it the whole table is one group

GROUP BY rule: every non-aggregated column in SELECT must appear in GROUP BY (standard SQL; MySQL relaxes this when ONLY_FULL_GROUP_BY is off).

5.3 Aggregates and NULLs ⭐⭐⭐ ​

  • COUNT(*) counts all rows, including NULLs and duplicates. COUNT(col) counts non-NULL values. COUNT(DISTINCT col) counts distinct non-NULL values.
  • SUM, AVG, MIN, MAX ignore NULLs. AVG(col) = SUM(col) / COUNT(col), not / COUNT(*) ⚠️.
  • On an empty input: COUNT β†’ 0; SUM / AVG / MIN / MAX β†’ NULL ⚠️.
  • SELECT COUNT(*) FROM empty_table returns 1 row (value 0). The same with GROUP BY x returns 0 rows ⚠️.
  • Example: values {10, 20, NULL} β†’ COUNT(*) = 3, COUNT(col) = 2, SUM = 30, AVG = 15 (not 10).
  • ⚠️ SQL Server: AVG of an INT column does integer division (AVG of 1 and 2 = 1).
  • Nested aggregates like MAX(AVG(sal)) are not allowed in standard SQL (use a subquery/CTE; Oracle allows it with GROUP BY).

5.4 NULL and three-valued logic ⭐⭐⭐ ​

  • NULL = unknown / missing / inapplicable. Any comparison with NULL, even NULL = NULL, gives UNKNOWN. Test with IS NULL / IS NOT NULL.
  • Arithmetic with NULL gives NULL (5 + NULL = NULL).
  • WHERE, HAVING and ON keep only TRUE rows (UNKNOWN is dropped).
  • ⚠️ A CHECK constraint only rejects FALSE, so NULL passes a CHECK (CHECK (salary > 0) accepts NULL).
  • Truth table: TRUE AND UNKNOWN = UNKNOWN Β· FALSE AND UNKNOWN = FALSE Β· TRUE OR UNKNOWN = TRUE Β· FALSE OR UNKNOWN = UNKNOWN Β· NOT UNKNOWN = UNKNOWN.
  • GROUP BY puts all NULLs in one group. DISTINCT and UNION treat NULLs as duplicates of each other.
  • ORDER BY: NULLs come first in ASC in MySQL and SQL Server, last in ASC in Oracle and PostgreSQL (NULLS FIRST / NULLS LAST to control).
  • ⚠️⭐ x NOT IN (1, 2, NULL) is never TRUE, so the query returns no rows. x IN (1, NULL) is TRUE if x = 1, otherwise UNKNOWN.
  • NOT EXISTS is NULL-safe and is preferred over NOT IN.
  • ⚠️ Oracle treats the empty string '' as NULL.
  • Functions: COALESCE(a, b, …) = first non-NULL; NULLIF(a, b) = NULL if a = b, else a; IFNULL (MySQL), NVL (Oracle), ISNULL (SQL Server).
  • CASE without ELSE returns NULL when nothing matches.

5.5 Subqueries and quantifiers ⭐⭐ ​

  • Non-correlated: runs once. Correlated: refers to the outer query, so it is (conceptually) evaluated once per outer row.
  • EXISTS(subquery) is TRUE if the subquery returns β‰₯ 1 row (even a row of NULLs). It stops at the first match.
  • = ANY ≑ IN. <> ALL ≑ NOT IN. ⚠️ <> ANY is not NOT IN (x <> ANY (1, 2) is TRUE for x = 1, because 1 β‰  2).
  • ⚠️ > ALL (empty set) β†’ TRUE; > ANY (empty set) β†’ FALSE.
  • > ALL (subquery) behaves like > MAX; > ANY like > MIN (when there are no NULLs).
  • A scalar subquery that returns more than one row is a runtime error.
  • A derived table (subquery in FROM) needs an alias (MySQL, PostgreSQL).

5.6 Set operations ​

  • UNION (removes duplicates), UNION ALL (keeps them; faster), INTERSECT, EXCEPT (MINUS in Oracle).
  • Same number of columns, compatible types. Result column names come from the first query. One ORDER BY, at the very end.
  • MySQL added INTERSECT/EXCEPT only in 8.0.31. MySQL has no FULL OUTER JOIN (emulate with LEFT JOIN UNION RIGHT JOIN).

5.7 Joins in SQL ​

  • INNER, LEFT / RIGHT / FULL [OUTER], CROSS (Cartesian product), SELF (needs table aliases), NATURAL (joins on all same-named columns), JOIN … USING (col).
  • ⚠️ After a LEFT JOIN, a filter on the right table in WHERE (WHERE d.city = 'X') removes the NULL-extended rows, so it behaves like an INNER JOIN. Put the condition in ON to keep unmatched left rows.

5.8 Operators ​

  • LIKE: % = any sequence (including empty), _ = exactly one character. 'a%' starts with a Β· '%a' ends with a Β· '_a%' second letter a Β· '%a%' contains a Β· ESCAPE for a literal % or _. Case sensitivity depends on collation (MySQL is case-insensitive by default; PostgreSQL is case-sensitive and has ILIKE).
  • BETWEEN a AND b is inclusive at both ends; BETWEEN 10 AND 5 returns nothing.
  • IN (list), IS NULL, EXISTS, ANY/SOME, ALL.

5.9 DELETE vs TRUNCATE vs DROP ⭐⭐⭐ ​

DELETETRUNCATEDROP
TypeDMLDDLDDL
RemovesSelected rowsAll rowsTable structure + data + indexes + constraints + triggers
WHERE clauseYesNoNo
RollbackYesOracle/MySQL: no (implicit commit). SQL Server/PostgreSQL: yes inside a transactionGenerally no (Oracle recycle bin / FLASHBACK aside)
TriggersFires DELETE triggersDoesn't fire row DELETE triggersn/a
SpeedSlow (row by row, fully logged)Fast (deallocates pages)Fast
Identity / auto-incrementNot resetResetGone
Table structureKeptKeptRemoved

5.10 Constraints ​

  • NOT NULL, UNIQUE, PRIMARY KEY (= NOT NULL + UNIQUE; one per table; creates an index automatically), FOREIGN KEY, CHECK, DEFAULT.
  • A composite PK must be declared at table level: PRIMARY KEY (a, b).
  • ⚠️ UNIQUE and NULLs: Oracle, PostgreSQL and MySQL allow many NULLs in a UNIQUE column; SQL Server allows only one.
  • Constraints can be named (CONSTRAINT pk_emp PRIMARY KEY (id)) and added or dropped with ALTER TABLE.
  • CREATE TABLE new AS SELECT … copies columns and data (and NOT NULL), not the PK/FK/indexes.
  • CREATE ASSERTION (standard, rarely implemented) and CREATE DOMAIN exist.

5.11 Data types ​

  • CHAR(n) fixed-length (blank-padded) vs VARCHAR(n) variable-length (VARCHAR2 in Oracle).
  • INT/SMALLINT/BIGINT; DECIMAL(p, s)/NUMERIC exact (DECIMAL(5,2) holds up to 999.99); FLOAT/REAL/DOUBLE approximate; DATE, TIME, TIMESTAMP; BOOLEAN; BLOB (binary large object); CLOB/TEXT (character large object).

5.12 Views ⭐⭐ ​

  • A view is a virtual table: a stored query, no data stored (except a materialized view). Dropping a view never touches base-table data.
  • Uses: security (hide rows/columns), simplicity, logical data independence.
  • Generally updatable only if: single base table; no aggregates; no GROUP BY/HAVING; no DISTINCT; no set operations; no subquery in SELECT; includes every NOT NULL column without a default (for INSERT).
  • WITH CHECK OPTION rejects inserts/updates through the view that would produce rows the view can't see.
  • INSTEAD OF triggers make complex views updatable.
  • Materialized view: result physically stored; must be refreshed (immediate or deferred); used in data warehouses.

5.13 Indexes in SQL ⭐⭐ ​

  • CREATE [UNIQUE] INDEX idx ON t (col, …). Faster search, joins and ORDER BY; slower INSERT/UPDATE/DELETE; extra space.
  • PK and UNIQUE constraints create unique indexes automatically.
  • Clustered index: rows physically ordered by the key β†’ at most one per table (SQL Server's PK default; MySQL InnoDB clusters on the PK). Non-clustered: separate structure with pointers β†’ many allowed ⭐.
  • Composite index (a, b, c) is usable for a, (a, b), (a, b, c): the leftmost-prefix rule. ⚠️ Not for b alone.
  • Usually not used for: leading wildcard (LIKE '%x'), a function on the indexed column (WHERE UPPER(name) = …), implicit type conversion, low-selectivity columns.

5.14 Triggers, procedures, functions, cursors ​

  • Trigger = ECA rule (Event–Condition–Action). Timing: BEFORE / AFTER / INSTEAD OF (for views). Granularity: row-level (FOR EACH ROW, OLD/NEW values) vs statement-level. Events: INSERT, UPDATE, DELETE (Oracle also DDL and logon).
  • Stored procedure vs function: a function must return a value and can be used inside SQL (SELECT f(x)). A procedure is called with CALL/EXEC, may return values through OUT parameters, and cannot be used in SELECT. Procedures can COMMIT; functions generally cannot.
  • PL/SQL block: DECLARE (optional) β†’ BEGIN β†’ EXCEPTION (optional) β†’ END.
  • Cursor: pointer to a result set for row-by-row processing. Implicit (automatic for DML and SELECT INTO; named SQL in Oracle) vs explicit. Steps: DECLARE β†’ OPEN β†’ FETCH (loop) β†’ CLOSE (β†’ DEALLOCATE in SQL Server). Oracle attributes: %FOUND, %NOTFOUND, %ROWCOUNT, %ISOPEN.

5.15 DCL and TCL ​

  • GRANT privilege ON object TO user [WITH GRANT OPTION]; REVOKE privilege ON object FROM user [CASCADE | RESTRICT]. CASCADE also revokes what that user granted to others.
  • Roles group privileges; PUBLIC = all users.
  • COMMIT makes changes permanent; ROLLBACK undoes everything since the last commit; SAVEPOINT sp + ROLLBACK TO sp undoes part of a transaction (the transaction stays active).
  • ⚠️ DDL causes an implicit COMMIT in Oracle and MySQL (PostgreSQL DDL is transactional).
  • Autocommit is ON by default in MySQL, PostgreSQL clients and SQL Server; OFF in Oracle SQL*Plus.

5.16 Window functions ⭐⭐ ​

func() OVER (PARTITION BY … ORDER BY … [frame]) computes per row without collapsing rows (unlike GROUP BY).

Salaries 100, 90, 90, 80 ordered DESC:

SalaryROW_NUMBERRANKDENSE_RANK
100111
90222
90322
8044 (gap)3 (no gap)

Others: NTILE(n), LAG/LEAD (previous/next row), FIRST_VALUE/LAST_VALUE, SUM() OVER (ORDER BY …) for running totals, PERCENT_RANK, CUME_DIST.

5.17 Must-know queries ⭐⭐⭐ ​

sql
-- 2nd highest salary
SELECT MAX(salary) FROM emp
WHERE salary < (SELECT MAX(salary) FROM emp);

-- Nth highest (distinct)
SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET N-1;   -- MySQL/PostgreSQL
SELECT salary FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r FROM emp
) t WHERE r = N;
SELECT DISTINCT salary FROM emp e1                                           -- correlated
WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM emp e2 WHERE e2.salary > e1.salary);

-- Find duplicates
SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;

-- Delete duplicates, keep the lowest id
DELETE FROM users WHERE id NOT IN (SELECT MIN(id) FROM users GROUP BY email);
-- (MySQL needs the subquery wrapped in a derived table)

-- Employees earning more than their manager (self join)
SELECT e.name FROM emp e JOIN emp m ON e.manager_id = m.id WHERE e.salary > m.salary;

-- Departments with no employees (anti-join)
SELECT d.name FROM dept d LEFT JOIN emp e ON e.dept_id = d.id WHERE e.id IS NULL;

-- Highest-paid employee per department
SELECT * FROM (
  SELECT e.*, ROW_NUMBER() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rn FROM emp e
) t WHERE rn = 1;

-- Department(s) with the highest average salary
SELECT dept_id FROM emp GROUP BY dept_id
HAVING AVG(salary) >= ALL (SELECT AVG(salary) FROM emp GROUP BY dept_id);

-- Even-numbered rows by id
SELECT * FROM emp WHERE MOD(id, 2) = 0;
  • ⚠️ ORDER BY salary DESC LIMIT 2 gives the top 2 rows, not the 2nd highest; duplicates break naive LIMIT tricks (use DISTINCT).
  • ⚠️ MySQL LIMIT 5, 10 = skip 5, return 10 (offset comes first). Same as LIMIT 10 OFFSET 5.
  • Row limiting: LIMIT (MySQL/PostgreSQL/SQLite), TOP n (SQL Server), ROWNUM / FETCH FIRST n ROWS ONLY (Oracle 12c+).
  • ⚠️ Oracle ROWNUM is assigned before ORDER BY, so WHERE ROWNUM <= 3 ORDER BY sal is not the top 3. WHERE ROWNUM = 2 (or > 1) returns no rows.

5.18 Misc SQL facts ​

  • SQL is declarative. It began as SEQUEL at IBM (System R). Standards: SQL-86, SQL-92, SQL:1999 (recursive queries, triggers), SQL:2003 (window functions), later JSON and property-graph additions.
  • Keywords are case-insensitive. String literals use single quotes. Identifiers are quoted with double quotes (standard), backticks (MySQL) or [ ] (SQL Server). Comments: -- and /* */.
  • String concatenation: || (standard, Oracle, PostgreSQL), + (SQL Server), CONCAT() (MySQL, where || means OR by default).
  • DUAL = Oracle's one-row dummy table (SELECT SYSDATE FROM DUAL).
  • CTE: WITH t AS (…) SELECT …; WITH RECURSIVE for hierarchies / transitive closure.
  • Upsert: MERGE; INSERT … ON CONFLICT (PostgreSQL); ON DUPLICATE KEY UPDATE (MySQL).
  • Embedded SQL: EXEC SQL …; host variables prefixed with :; status in SQLCA / SQLCODE / SQLSTATE. Dynamic SQL: PREPARE/EXECUTE at run time.
  • JDBC: DriverManager β†’ Connection β†’ Statement / PreparedStatement (precompiled, prevents SQL injection) / CallableStatement (stored procedures) β†’ ResultSet. Driver types: 1 JDBC-ODBC bridge, 2 Native-API, 3 Network-protocol (middleware), 4 Thin / pure Java (most used). ODBC = C-based standard API.
  • SQL injection: user input concatenated into a query (' OR '1'='1). Prevention: parameterized/prepared statements, parameterized stored procedures, input validation, least-privilege DB accounts.

6. Functional Dependencies ​

6.1 Basics ​

  • X β†’ Y: whenever two tuples agree on X, they agree on Y. X is the determinant.
  • Trivial: Y βŠ† X (AB β†’ A). Non-trivial: Y βŠ„ X. Completely non-trivial: X ∩ Y = βˆ….
  • ⚠️ An instance can only disprove an FD (show a violation); it can never prove that an FD holds for the schema.

6.2 Armstrong's axioms (sound and complete) ⭐⭐ ​

  1. Reflexivity: if Y βŠ† X then X β†’ Y
  2. Augmentation: X β†’ Y β‡’ XZ β†’ YZ
  3. Transitivity: X β†’ Y and Y β†’ Z β‡’ X β†’ Z

Derived rules: Union (X β†’ Y, X β†’ Z β‡’ X β†’ YZ), Decomposition (X β†’ YZ β‡’ X β†’ Y and X β†’ Z), Pseudo-transitivity (X β†’ Y, WY β†’ Z β‡’ WX β†’ Z), Composition (X β†’ Y, Z β†’ W β‡’ XZ β†’ YW).

  • ⚠️ XY β†’ Z does not imply X β†’ Z (you can't split the left side).
  • X β†’ Z does imply XY β†’ Z (augment, then decompose).

6.3 Attribute closure X⁺ ⭐⭐⭐ ​

Algorithm: result = X; repeat { for each FD A β†’ B: if A βŠ† result, add B } until nothing changes.

Uses: X is a super key ⇔ X⁺ = all attributes; X β†’ Y holds ⇔ Y βŠ† X⁺; computing F⁺.

6.4 Finding candidate keys fast ⭐⭐⭐ ​

  1. Attributes on no right-hand side must be in every key (essential attributes).
  2. Attributes that appear only on right-hand sides are in no key.
  3. Start with the essential set. If its closure is all of R, it is the only candidate key. Otherwise add other attributes one at a time (smallest sets first) and keep only minimal ones.
  4. If X β†’ A and A is in key K, then (K βˆ’ A) βˆͺ X is also a super key; check it for minimality to find more keys.

Worked example 1 ⭐ R(A,B,C,D,E), F = {A β†’ B, BC β†’ E, ED β†’ A}

  • C and D are on no RHS, so both are in every key. (CD)⁺ = CD, not enough.
  • (ACD)⁺ = ACD β†’ B β†’ E = ABCDE βœ“ Β· (BCD)⁺ = BCD β†’ E β†’ A = ABCDE βœ“ Β· (CDE)⁺ = CDE β†’ A β†’ B = ABCDE βœ“
  • Candidate keys: ACD, BCD, CDE. Every attribute is prime.
  • 3NF? Each RHS attribute (B, E, A) is prime β†’ yes. BCNF? A β†’ B with A not a super key β†’ no. Highest NF = 3NF.

Worked example 2 R(A,B,C,D,E,H), F = {A β†’ B, BC β†’ D, E β†’ C, D β†’ A}

  • E and H are on no RHS. (EH)⁺ = CEH.
  • AEH, BEH, DEH all have closure = all attributes; CEH doesn't. Keys: AEH, BEH, DEH. Also (AE)⁺ = ABCDE.

6.5 Equivalence and minimal (canonical) cover ⭐⭐ ​

  • F covers G if every FD of G is in F⁺. F ≑ G iff each covers the other (F⁺ = G⁺).
  • Minimal cover steps: (1) make every RHS a single attribute; (2) remove extraneous LHS attributes (A is extraneous in XA β†’ B if X β†’ B already follows); (3) remove redundant FDs (X β†’ A is redundant if A is still in X⁺ computed without that FD).
  • The canonical cover is not necessarily unique.
  • Example: F = {A β†’ BC, B β†’ C, A β†’ B, AB β†’ C} β†’ canonical cover {A β†’ B, B β†’ C}.

7. Normalization ⭐⭐⭐ ​

7.1 Why: anomalies from redundancy ​

  • Insertion anomaly: can't record one fact without another (a new course with no student yet).
  • Deletion anomaly: deleting one fact loses another (last student of a course deleted β†’ course info lost).
  • Update (modification) anomaly: the same fact in many rows β†’ partial update leaves inconsistency.

7.2 Normal forms ​

NFCondition
1NFAll values atomic; no repeating groups or multivalued attributes
2NF1NF + no partial dependency: no non-prime attribute depends on a proper subset of any candidate key
3NF2NF + no transitive dependency. Test: for every non-trivial X β†’ A, X is a super key OR A is prime
BCNFFor every non-trivial X β†’ Y, X is a super key
4NFBCNF + for every non-trivial MVD X β†’β†’ Y, X is a super key
5NF (PJNF)Every non-trivial join dependency is implied by the candidate keys
DKNFEvery constraint follows from domain and key constraints

Containment: 5NF βŠ‚ 4NF βŠ‚ BCNF βŠ‚ 3NF βŠ‚ 2NF βŠ‚ 1NF (a higher NF satisfies all lower ones).

7.3 Finding the highest normal form ⭐⭐⭐ ​

  1. Find all candidate keys β†’ prime attributes.
  2. For each non-trivial FD X β†’ A (single attribute on the right):
    • X is a super key β†’ fine at every level.
    • Else, A is prime β†’ violates BCNF only (still 3NF).
    • Else (A non-prime): X is a proper subset of a candidate key β†’ partial dependency β†’ violates 2NF (relation is 1NF). Otherwise β†’ transitive dependency β†’ violates 3NF (relation is 2NF).
  3. The answer is the highest level with no violation.
R and FDsKeysHighest NFReason
R(A,B,C,D): AB β†’ C, B β†’ DAB1NFB β†’ D: D non-prime, B βŠ‚ key (partial)
R(A,B,C,D): AB β†’ C, C β†’ DAB2NFC β†’ D transitive
R(A,B,C): AB β†’ C, C β†’ BAB, AC3NFC β†’ B: C not a super key, but B is prime
R(A,B,C,D,E): A β†’ B, BC β†’ E, ED β†’ AACD, BCD, CDE3NFall attributes prime; A β†’ B breaks BCNF
Any R(A,B)BCNFbinary relation

7.4 Shortcut facts ⭐⭐ ​

  • Any relation with two attributes is in BCNF (and 4NF).
  • If every candidate key is a single attribute, partial dependency is impossible β†’ at least 2NF.
  • If all attributes are prime β†’ at least 3NF (maybe not BCNF).
  • An all-key relation (the only key is all attributes) is in BCNF, but may still violate 4NF (MVDs).
  • 3NF-but-not-BCNF needs two or more overlapping composite candidate keys. Classic: R(A,B,C), AB β†’ C, C β†’ B.
  • 3NF + every candidate key single-attribute β‡’ BCNF (in fact 5NF, the Date–Fagin theorem). BCNF + at least one single-attribute key β‡’ 4NF.

7.5 Decomposition properties ⭐⭐⭐ ​

  • Lossless join: R into R1, R2 is lossless iff (R1 ∩ R2) β†’ R1 or (R1 ∩ R2) β†’ R2, i.e., the common attributes are a super key of at least one part (and R1 βˆͺ R2 = R). For more than two relations use the chase/tableau test or apply the binary test repeatedly.
  • ⚠️ A lossy decomposition produces extra (spurious) tuples on joining, never fewer. "Loss" means loss of information.
  • No common attribute β†’ always lossy (the join is a Cartesian product).
  • Dependency preserving: (F1 βˆͺ F2 βˆͺ … βˆͺ Fn)⁺ = F⁺, where Fi = the FDs of F⁺ that use only Ri's attributes.
TargetAlways lossless?Always dependency preserving?
3NF (synthesis algorithm)YesYes ⭐
BCNFYesNo ⚠️
4NFYesNo

So 3NF is the highest normal form that can always be reached with both properties.

Algorithms:

  • BCNF decomposition: find a violating X β†’ Y; replace R with R1 = X βˆͺ Y and R2 = R βˆ’ (Y βˆ’ X); repeat.
  • 3NF synthesis: compute the canonical cover; make one relation per FD X β†’ Y (schema XY); if no relation contains a candidate key, add one that does; drop relations contained in others.

7.6 Multivalued dependencies and 4NF/5NF ​

  • X β†’β†’ Y: for each X value, the set of Y values is independent of the remaining attributes. Typical cause: two independent multivalued facts in one table, e.g., (Emp, Skill, Language).
  • Every FD is an MVD (X β†’ Y β‡’ X β†’β†’ Y), not vice versa. Complementation: X β†’β†’ Y β‡’ X β†’β†’ (R βˆ’ X βˆ’ Y).
  • Trivial MVD: Y βŠ† X or X βˆͺ Y = R.
  • 4NF fix: R(E, S, L) with E β†’β†’ S | L β†’ R1(E, S), R2(E, L).
  • 5NF / join dependency: the table splits losslessly into 3+ projections but not into 2 (cyclic Supplier–Part–Project rule).
  • Denormalization: deliberately adding redundancy (pre-joined or pre-aggregated data) to speed up reads; common in OLAP.

8. Transactions and Schedules ​

8.1 ACID ⭐⭐⭐ ​

PropertyMeaningEnsured by
AtomicityAll or nothingRecovery system / transaction manager (undo using logs)
ConsistencyMoves the DB from one consistent state to anotherApplication programmer + integrity constraints
IsolationConcurrent transactions don't see each other's intermediate state; result equals some serial orderConcurrency-control manager
DurabilityCommitted changes survive failuresRecovery system (redo logs, stable storage)

8.2 Transaction states ⭐⭐ ​

Active β†’ Partially committed (after the last statement) β†’ Committed Active or Partially committed β†’ Failed β†’ Aborted (rolled back) β†’ restart (hardware/software error, not logical error) or kill. Committed and aborted transactions are terminated. ⚠️ Partially committed β‰  committed: a failure at that point still leads to abort.

8.3 Schedules ​

  • Serial: transactions run one after another. n transactions β†’ n! serial schedules.
  • Concurrent (non-serial): interleaved. Number of interleavings of T1 (n1 ops), T2 (n2 ops), … keeping each transaction's own order = (n1 + n2 + …)! / (n1! Β· n2! Β· …). Example: 3 ops + 2 ops β†’ 10.
  • Why concurrency: higher throughput and resource utilization, lower average response time.

8.4 Serializability ⭐⭐⭐ ​

  • Conflicting operations: different transactions, same data item, at least one write β†’ R–W, W–R, W–W. R–R never conflicts.
  • Conflict equivalent: one schedule can be turned into the other by swapping adjacent non-conflicting operations.
  • Conflict serializable ⇔ precedence graph is acyclic. Draw an edge Ti β†’ Tj when an operation of Ti conflicts with and comes before an operation of Tj. Equivalent serial orders = topological sorts.
  • View equivalent schedules have the same (1) initial reads, (2) reads-from pairs (Ti reads the value written by Tj), (3) final write for each item.
  • Conflict serializable βŠ‚ view serializable. A view-serializable schedule that is not conflict serializable always has blind writes (writes without a prior read by that transaction) ⭐.
  • Testing view serializability is NP-complete; testing conflict serializability is polynomial (cycle detection).

Examples (checked):

  • R1(A) W1(A) R2(A) W2(A) R1(B) W1(B) R2(B) W2(B) β†’ only T1 β†’ T2 edges β†’ conflict serializable (T1, T2).
  • R1(X) R2(X) W1(X) W2(X) β†’ T1 β†’ T2 (R1X before W2X) and T2 β†’ T1 (R2X before W1X) β†’ cycle β†’ not CS, not VS (the lost-update pattern).
  • R1(A) W2(A) W1(A) W3(A) β†’ cycle between T1 and T2 β†’ not CS. But T1 reads the initial A and T3 writes last, so it is view-equivalent to T1 β†’ T2 β†’ T3 β†’ VS but not CS. Blind writes: W2(A), W3(A).

8.5 Recoverability ⭐⭐⭐ ​

ClassRule
RecoverableIf Tj reads a value written by Ti, Ti commits before Tj commits
Cascadeless (ACA)Tj reads only values written by committed transactions
StrictNo read or write of X until the last transaction that wrote X has committed or aborted

Strict βŠ‚ Cascadeless βŠ‚ Recoverable. Every serial schedule is strict.

  • Non-recoverable example: W1(X) R2(X) C2 … then T1 aborts β†’ T2 already committed using dirty data.
  • Cascading rollback: one abort forces dependents to abort (possible in recoverable schedules, impossible in cascadeless).
  • ⚠️ Serializability and recoverability are independent properties.

8.6 Concurrency problems and isolation levels ⭐⭐⭐ ​

  • Lost update (W–W), dirty read (reading uncommitted data; W–R), non-repeatable read (re-reading a row gives a different value; R–W), phantom read (re-running a query returns new or missing rows because of inserts/deletes), incorrect summary.
Isolation levelDirty readNon-repeatable readPhantom
Read UncommittedPossiblePossiblePossible
Read CommittedPreventedPossiblePossible
Repeatable ReadPreventedPreventedPossible
SerializablePreventedPreventedPrevented
  • Defaults ⭐: Oracle, PostgreSQL, SQL Server β†’ Read Committed; MySQL InnoDB β†’ Repeatable Read (and its next-key locks also block most phantoms). Oracle has no Read Uncommitted.
  • Snapshot isolation (MVCC) can still allow the write-skew anomaly.

9. Concurrency Control ​

9.1 Locks ⭐ ​

  • Shared (S) for reading, Exclusive (X) for writing. Only S–S is compatible.
  • Upgrade S β†’ X only in the growing phase; downgrade X β†’ S only in the shrinking phase.
  • Locking and unlocking immediately after use does not by itself guarantee serializability.

9.2 Two-phase locking ⭐⭐⭐ ​

VariantRuleGuaranteesDeadlock?
Basic 2PLGrowing phase (only acquire), then shrinking phase (only release). Lock point = last lock acquiredConflict serializability (serial order = lock-point order)Possible; cascading rollback possible
Strict 2PLBasic + hold all X locks until commit/abortCS + strict schedules (so cascadeless and recoverable)Possible
Rigorous 2PLHold all locks (S and X) until commit/abortCS + strict; serial order = commit orderPossible
Conservative (static) 2PLAcquire all locks before starting (declare read/write sets in advance)CSDeadlock-free ⭐ (not necessarily strict)
  • ⚠️ 2PL is sufficient but not necessary for conflict serializability (some CS schedules can't be produced by 2PL).
  • ⚠️ Basic 2PL doesn't guarantee recoverability.

Graph (tree) protocol: only X locks; the first lock can be on any node; after that a node can be locked only if its parent is currently locked by the same transaction; unlock any time; no relocking. Gives CS + deadlock freedom; does not guarantee recoverability/cascadelessness; can unlock earlier than 2PL.

Multiple-granularity locking: hierarchy DB β†’ area β†’ file β†’ record. Intention modes IS, IX, SIX. Lock top-down, release bottom-up.

ISIXSSIXX
ISβœ”βœ”βœ”βœ”βœ˜
IXβœ”βœ”βœ˜βœ˜βœ˜
Sβœ”βœ˜βœ”βœ˜βœ˜
SIXβœ”βœ˜βœ˜βœ˜βœ˜
X✘✘✘✘✘

9.3 Timestamp ordering (TO) ⭐⭐⭐ ​

  • Each Ti gets TS(Ti) when it starts (older = smaller). Each item Q keeps W-TS(Q) and R-TS(Q) (largest timestamps that wrote/read it).
  • Ti reads Q: if TS(Ti) < W-TS(Q) β†’ reject, roll back Ti. Else read; R-TS(Q) = max(R-TS(Q), TS(Ti)).
  • Ti writes Q: if TS(Ti) < R-TS(Q) β†’ roll back Ti. Else if TS(Ti) < W-TS(Q) β†’ roll back (basic TO) or ignore the write (Thomas' write rule). Else write; W-TS(Q) = TS(Ti).
  • A rolled-back transaction restarts with a new timestamp.
  • Properties: conflict serializable (order = timestamp order); deadlock-free (nobody waits) ⭐; starvation possible; may produce non-recoverable or cascading schedules unless extended (strict TO).
  • Thomas' write rule ignores obsolete writes, which allows some view-serializable (not conflict-serializable) schedules ⭐.

9.4 Optimistic and multiversion schemes ​

  • Validation-based (optimistic): Read phase (work on local copies) β†’ Validation phase (check for conflicts) β†’ Write phase. Best when conflicts are rare; no locks, no deadlocks; work is wasted on abort.
  • Multiversion: keep several versions; reads never wait or fail. Multiversion TO, multiversion 2PL. MVCC: readers don't block writers and writers don't block readers (PostgreSQL, Oracle, InnoDB).

9.5 Deadlock handling in databases ⭐⭐⭐ ​

Timestamp-based prevention. A restarted transaction keeps its original timestamp, so there is no starvation.

SchemeRequester Ti older than holder TjRequester Ti younger than holder Tj
Wait–Die (non-preemptive)Ti waitsTi dies (rolled back)
Wound–Wait (preemptive)Ti wounds Tj (Tj rolled back)Ti waits
  • Memory hook: in both schemes only the younger transaction is ever rolled back. Wait–die: old waits for young. Wound–wait: young waits for old.
  • Wait–die can cause more rollbacks (a young transaction may die repeatedly).
  • Timeout-based: wait up to a limit, then roll back (simple; may roll back transactions that weren't deadlocked).
  • Other prevention: lock everything up front (conservative 2PL), impose an order on data items (tree protocol).
  • Detection: wait-for graph (Ti β†’ Tj if Ti waits for Tj); cycle ⇔ deadlock. Recovery: choose a victim by cost (work done, locks held, locks still needed, number of transactions involved), total or partial rollback, include the number of past rollbacks in the cost to avoid starvation.

10. Recovery ​

10.1 Failures and storage ​

  • Failures: transaction failure (logical error such as bad input; system error such as deadlock), system crash (power/OS/DBMS crash; fail-stop assumption: disk contents survive), disk failure (head crash; restore from backup).
  • Storage: volatile (RAM, cache), non-volatile (disk, flash), stable storage (never loses data; approximated by replicating on several disks/sites).

10.2 Log-based recovery ⭐⭐⭐ ​

  • Log records: <Ti start>, <Ti, X, old value, new value>, <Ti commit>, <Ti abort>. The log is on stable storage.
  • WAL (write-ahead logging): (1) the log record of an update must reach stable storage before the data page is written to disk; (2) all of Ti's log records, including <Ti commit>, must be on stable storage before Ti counts as committed.
  • undo(Ti) restores old values (scan backward); redo(Ti) reapplies new values (scan forward). Both must be idempotent.
TechniqueWhen the DB on disk is updatedNeeded after a crash
Deferred modificationOnly after commitREDO only (NO-UNDO/REDO)
Immediate modificationPossibly before commitUNDO + REDO
Shadow pagingCopy-on-write pages; commit = switch the page-table pointerNeither (NO-UNDO/NO-REDO)

Rule after a crash (immediate modification) ⭐⭐:

  • <Ti start> and <Ti commit> (or <Ti abort>) in the log β†’ REDO Ti.
  • <Ti start> with no commit/abort β†’ UNDO Ti.
  • Deferred modification: redo committed transactions; simply ignore uncommitted ones.
  • Order: the classic scheme undoes (backward scan) then redoes (forward scan). ARIES does Analysis β†’ Redo (repeat history) β†’ Undo.

10.3 Checkpoints ⭐⭐ ​

Periodically: flush log records and modified buffer blocks to disk, then write <checkpoint L> (L = transactions active at that moment). After a crash only transactions active at, or started after, the last checkpoint matter:

  • Committed before the checkpoint β†’ nothing to do.
  • Committed after the checkpoint β†’ REDO.
  • Not committed at the crash β†’ UNDO.

Purpose: shorter recovery (no need to scan/redo the whole log). Fuzzy checkpoints allow updates to continue while checkpointing.

Worked example (immediate modification)

<T1 start> <T1, A, 100, 200> <T1 commit>
<T2 start> <T2, B, 50, 80>
<checkpoint {T2}>
<T3 start> <T3, C, 10, 20> <T3 commit>
<T2, D, 5, 9>
<T4 start> <T4, E, 1, 2>
--- crash ---

T1: nothing (committed before the checkpoint) Β· T3: redo Β· T2, T4: undo (B = 50, D = 5, E = 1).

10.4 Shadow paging ​

Keeps a shadow page table (on disk, unchanged) and a current page table. Commit = atomically make the current table the shadow. No log needed in the single-user case. Drawbacks: commit overhead (flush pages + table), data fragmentation (related pages scattered), garbage collection, hard to combine with concurrency.

10.5 Buffer policies ⭐⭐ ​

  • Steal: uncommitted dirty pages may be written to disk β†’ UNDO needed. No-steal β†’ no undo.
  • Force: all dirty pages written at commit β†’ no REDO. No-force β†’ REDO needed.
  • Steal + No-force (most flexible, fastest) β†’ UNDO + REDO; used by ARIES. No-steal + Force β†’ neither, but impractical.

10.6 ARIES and distributed commit ​

  • ARIES: LSNs (log sequence numbers; PageLSN on every page), dirty page table, transaction table, CLRs (compensation log records, redo-only), fuzzy checkpoints. Three passes: Analysis, Redo, Undo. Supports steal/no-force and fine-grained locking.
  • Remote backup: one-safe (commit once the primary logs it), two-very-safe (both sites must log), two-safe (both if both are up).
  • 2PC (two-phase commit): Phase 1 prepare/vote, Phase 2 commit or abort decision. Blocking if the coordinator fails. 3PC adds a pre-commit phase; non-blocking if there are no network partitions.

11. Storage, File Organization, Hashing, RAID ​

11.1 Storage basics ​

  • Hierarchy (fast β†’ slow): cache β†’ main memory β†’ flash/SSD β†’ magnetic disk β†’ optical β†’ tape. Primary (volatile), secondary (online, non-volatile: disk), tertiary (offline: tape, optical).
  • Block (page) = unit of transfer between disk and memory.
  • Disk access time = seek time + rotational latency + transfer time. Average rotational latency = Β½ rotation (7,200 RPM β†’ 8.33 ms per rotation β†’ 4.17 ms average).
  • Buffer manager: replacement policies LRU, MRU (better for some nested-loop joins), toss-immediate; pinned blocks; forced output.

11.2 Records and blocks ⭐⭐ ​

  • Blocking factor bfr = ⌊B / RβŒ‹ records per block (unspanned). Number of blocks b = ⌈r / bfrβŒ‰.
  • Spanned (a record may cross blocks; no wasted space) vs unspanned (simpler; wastes space when R doesn't divide B).
  • Variable-length records: slotted-page structure (header with slot array, records packed from the end).

11.3 File organizations ⭐⭐ ​

OrganizationInsertSearchNotes
Heap (unordered)Fast (append)Linear: b/2 average, b worstGood for bulk loading
Sequential (sorted)Costly (overflow blocks / reorganization)Binary search: ⌈logβ‚‚ bβŒ‰Good for ordered/range access
HashedFast~1 block for equalityBad for range queries
Multitable clusteringn/aFast joinsRelated records of different tables in the same block

11.4 Hashing ​

  • Static hashing: fixed number of buckets β†’ bucket overflow (skew or too few buckets), handled with overflow chains. ⚠️ Korth calls overflow chaining "closed hashing", the opposite of data-structures books (where chaining = open hashing).
  • Extendible hashing: directory of 2^(global depth) pointers; each bucket has a local depth ≀ global depth. If an overflowing bucket has local depth = global depth, the directory doubles; if local depth < global depth, only the bucket splits.
  • Linear hashing: no directory; buckets split in round-robin order.

11.5 RAID ⭐⭐ ​

LevelTechniqueSurvivesNotes
0Block striping, no redundancy0 failuresFastest, full capacity
1Mirroring1 disk per mirror pair50% capacity, fast reads
2Bit-level striping + Hamming ECC1Obsolete
3Bit/byte-level striping + dedicated parity disk1
4Block-level striping + dedicated parity disk1Parity disk is a write bottleneck
5Block-level striping + distributed parity1Usable (nβˆ’1)/n; most common
6Block striping + double distributed parity (P+Q)2Usable (nβˆ’2)/n
10 (1+0)Mirror, then stripe1 per mirror pairFast and reliable; 50% capacity

RAID 5 small write = 4 I/Os (read data, read parity, write data, write parity).


12. Indexing, B-tree and B+ tree ​

12.1 Index types ⭐⭐⭐ ​

  • Index entry = <search key, pointer>. Ordered indices vs hash indices.
  • Dense: an entry for every search-key value (every record). Sparse: entries for only some values (one per block); needs the data file sorted on the search key.
IndexBuilt onDense / sparsePer file
PrimaryOrdering key field (sorted, unique)Sparse (one entry per block, the block's anchor record)At most one
ClusteringOrdering non-key field (sorted, duplicates)Sparse (one entry per distinct value)At most one (a file has a primary or a clustering index, not both)
SecondaryNon-ordering field (key or non-key)DenseMany
  • ⚠️ In Elmasri "primary index" means the index on the ordering key field. In Korth, primary index = clustering index (the index whose search key defines the file's order). Read the question's wording.
  • Multilevel index: build an index on the index until the top level fits in one block. Levels t = ⌈log_fo(r₁)βŒ‰ (fo = index blocking factor/fan-out, r₁ = first-level entries). Search cost = t + 1 block accesses.
  • Single-level primary index lookup = ⌈logβ‚‚ bα΅’βŒ‰ + 1 (binary search on the index blocks + one data block).
  • Secondary index on a non-key field adds a level of indirection (blocks of record pointers).

Worked example ⭐ r = 30,000 records, R = 100 B, B = 1,024 B

  • bfr = ⌊1024/100βŒ‹ = 10 β†’ b = 3,000 blocks. Linear search β‰ˆ 1,500 on average; binary search = ⌈logβ‚‚ 3000βŒ‰ = 12.
  • Primary index: entry = 9 (key) + 6 (pointer) = 15 B β†’ bfrα΅’ = ⌊1024/15βŒ‹ = 68; one entry per data block = 3,000 entries β†’ bα΅’ = ⌈3000/68βŒ‰ = 45 blocks β†’ ⌈logβ‚‚ 45βŒ‰ + 1 = 6 + 1 = 7 accesses.
  • Multilevel: level 1 = 45 blocks, level 2 = ⌈45/68βŒ‰ = 1 block β†’ t = 2 β†’ 3 accesses.

Elmasri's classic: r = 300,000, R = 100, B = 4,096 β†’ bfr = 40, b = 7,500 β†’ binary search 13; primary index (15 B entries) β†’ bfrα΅’ = 273, bα΅’ = 28 β†’ 5 + 1 = 6.

12.2 B-tree vs B+ tree ⭐⭐⭐ ​

B-treeB+ tree
Data/record pointersIn all nodesOnly in leaves
KeysEach key appears onceInternal keys are repeated in the leaves (internal nodes only route)
LeavesNot linkedLinked (fast sequential and range scans)
Fan-outLowerHigher β†’ shorter tree
SearchMay stop at an internal nodeAlways ends at a leaf (uniform cost)
Typical useLess commonStandard DB index (equality + range)

12.3 Structure rules (order p = max children) ​

  • Internal node: ≀ p children and ≀ p βˆ’ 1 keys. A non-root internal node has β‰₯ ⌈p/2βŒ‰ children (β‰₯ ⌈p/2βŒ‰ βˆ’ 1 keys). The root has β‰₯ 2 children unless it is a leaf.
  • All leaves are on the same level. Height grows only when the root splits ⭐.
  • B+ tree leaves are kept at least half full.
  • ⚠️ CLRS uses minimum degree t instead: every non-root node has t βˆ’ 1 to 2t βˆ’ 1 keys (t to 2t children). Check which definition the question uses.

12.4 Order formulas ⭐⭐⭐ ​

B = block size, K = key size, P = block (tree) pointer, Pr = record (data) pointer.

  • B+ internal: pΒ·P + (p βˆ’ 1)Β·K ≀ B β†’ p = ⌊(B + K) / (P + K)βŒ‹
  • B+ leaf: p_leafΒ·(K + Pr) + P ≀ B β†’ p_leaf = ⌊(B βˆ’ P) / (K + Pr)βŒ‹ (one P for the next-leaf link)
  • B-tree node: pΒ·P + (p βˆ’ 1)Β·(K + Pr) ≀ B β†’ p = ⌊(B + K + Pr) / (P + K + Pr)βŒ‹
  • Elmasri example: B = 512, K = 9, P = 6, Pr = 7 β†’ B+ internal p = 34, B+ leaf = 31, B-tree p = 24.
  • Another: B = 512, K = 10, P = 6 β†’ B+ internal p = ⌊522/16βŒ‹ = 32.

12.5 Capacity ​

  • Max keys in a B-tree of order p with L levels = p^L βˆ’ 1 (max nodes = (p^L βˆ’ 1)/(p βˆ’ 1)).
  • Min keys with L levels = 2·⌈p/2βŒ‰^(Lβˆ’1) βˆ’ 1 (p = 5, L = 3 β†’ 17).
  • B+ tree with L levels, internal fan-out p, leaf capacity p_leaf: max records β‰ˆ p^(Lβˆ’1) Γ— p_leaf.
  • Height β‰ˆ ⌈log_p NβŒ‰: with fan-out of a few hundred, 3–4 levels index millions to billions of keys.
  • Insertion: insert into the leaf; overflow β†’ split. ⚠️ B+ leaf split: the middle key is COPIED up (it stays in the leaf). Internal-node split: the middle key MOVES up.
  • Deletion: underflow β†’ borrow from a sibling (redistribution) or merge (coalesce). Merges can propagate up and reduce the height.

12.6 Other index structures ​

  • Hash index: O(1) equality lookups; useless for range queries and ORDER BY.
  • Bitmap index: one bit-vector per distinct value; great for low-cardinality columns (gender, status) and AND/OR queries; data warehouses; expensive to update.
  • Covering index (all needed columns are in the index β†’ index-only scan), composite index (leftmost prefix), full-text index, spatial index (R-tree), LSM tree (write-optimized: Cassandra, RocksDB).

13. Query Processing and Optimization ​

13.1 Steps ​

Parsing and translation (syntax check β†’ relational-algebra expression / query tree) β†’ Optimization (choose the cheapest evaluation plan) β†’ Evaluation (execution engine).

  • Evaluation plan = RA expression annotated with algorithms and access paths.
  • Cost is measured mostly in disk block transfers and seeks (CPU often ignored). Catalog statistics: n_r (tuples), b_r (blocks), l_r (tuple size), f_r (blocking factor), V(A, r) (distinct values of A). Estimated tuples for A = v: n_r / V(A, r).
  • Materialization (write intermediate results to disk) vs pipelining (pass tuples straight to the next operator; demand-driven/lazy or producer-driven/eager).

13.2 Heuristic rules ⭐⭐ ​

  1. Perform selections as early as possible (push Οƒ down).
  2. Perform projections early (push Ο€ down).
  3. Do the most restrictive selections and joins first.
  4. Replace a Γ— followed by Οƒ with a β‹ˆ.
  5. Prefer left-deep join trees (they allow pipelining).

Cost-based optimization: generate equivalent plans with equivalence rules, estimate cost with statistics, dynamic programming (System R). Number of join orders for n relations = (2(nβˆ’1))! / (nβˆ’1)! (n = 3 β†’ 12, n = 7 β†’ 665,280); left-deep orders = n!.

13.3 Join algorithms (Korth worst-case costs, r = outer relation) ⭐ ​

AlgorithmBlock transfersNotes
Nested-loopn_rΒ·b_s + b_rIf the smaller relation fits in memory: b_r + b_s
Block nested-loopb_rΒ·b_s + b_rUse the smaller relation as the outer
Indexed nested-loopb_r + n_rΒ·cc = cost of one index lookup on the inner
Merge (sort-merge) joinb_r + b_s (+ sorting)Equi/natural joins on sorted inputs
Hash joinβ‰ˆ 3(b_r + b_s)Equi/natural joins; build on the smaller relation

Selection: linear scan (b_r, or b_r/2 on average for equality on a key), binary search on a sorted file, index scans. External sort-merge for relations larger than memory.


14. Distributed DB, NoSQL, Warehousing, Security ​

14.1 Distributed databases ⭐ ​

  • Homogeneous (same DBMS everywhere) vs heterogeneous. Transparency: location, fragmentation, replication.
  • Fragmentation: horizontal (Οƒ, subsets of rows; rebuild with βˆͺ), vertical (Ο€, subsets of columns, each includes the key; rebuild with β‹ˆ), mixed. Correctness rules: completeness, reconstruction, disjointness.
  • Replication (full/partial): better availability and reads; harder updates.
  • Semi-join reduces data shipped for distributed joins.
  • Distributed commit: 2PC (blocking if the coordinator fails), 3PC. Global deadlock detection across sites.

14.2 CAP and NoSQL ⭐⭐ ​

  • CAP theorem (Brewer): during a network partition, a distributed system can guarantee either Consistency or Availability, not both. Common MCQ classification: Cassandra/DynamoDB β†’ AP; HBase/MongoDB (default) β†’ CP; single-node RDBMS β†’ CA.
  • ACID (RDBMS) vs BASE = Basically Available, Soft state, Eventually consistent (many NoSQL stores).
NoSQL typeExamplesTypical use
Key–valueRedis, DynamoDB, RiakCaching, sessions
DocumentMongoDB, CouchDBFlexible JSON-like documents
Column-family (wide column)Cassandra, HBase, BigtableHuge write-heavy workloads, time series
GraphNeo4j, Amazon NeptuneRelationship-heavy data (social graphs, fraud)
  • Sharding = horizontal partitioning across servers (often with consistent hashing); replication (leader–follower).
  • Big data V's: Volume, Velocity, Variety (+ Veracity, Value). Hadoop = HDFS + MapReduce (+ YARN); Spark = in-memory processing.

14.3 Data warehousing and OLAP ⭐⭐ ​

OLTPOLAP
Day-to-day transactionsAnalysis and decision support
Current, detailed dataHistorical, summarized data
Normalized (3NF)Denormalized (star/snowflake)
Many short read/write transactionsFew complex read-heavy queries
MillisecondsSeconds to minutes
  • Warehouse properties (Inmon): subject-oriented, integrated, time-variant, non-volatile.
  • ETL: Extract β†’ Transform β†’ Load (ELT in modern cloud warehouses).
  • Star schema: central fact table (measures + FKs) + denormalized dimension tables. Snowflake: dimensions normalized into sub-dimensions. Fact constellation (galaxy): several fact tables sharing dimensions.
  • OLAP operations: roll-up / drill-up (aggregate up a hierarchy or drop a dimension), drill-down (more detail), slice (fix one dimension), dice (select ranges on two or more dimensions), pivot / rotate (swap axes).
  • MOLAP (multidimensional arrays), ROLAP (relational tables), HOLAP (hybrid). Data mart = department-level subset of a warehouse.
  • Data mining: association rules with support = fraction of transactions containing both A and B, confidence = support(A βˆͺ B) / support(A); Apriori algorithm; classification; clustering.

14.4 Database security ⭐ ​

  • Threats to integrity, availability, confidentiality. Controls: access control, inference control (statistical DBs), flow control, encryption.
  • DAC (discretionary): owners grant privileges (GRANT/REVOKE). MAC (mandatory): security labels (Top Secret > Secret > Confidential > Unclassified); Bell–LaPadula: no read up (simple security property), no write down (*-property). RBAC: privileges via roles.
  • Views as a security mechanism (hide rows/columns); audit trails; SQL injection (section 5.18).
  • Statistical databases allow only aggregate queries, but inference (tracker) attacks are possible β†’ minimum query-set size, added noise.

15. Rapid-fire trap list ⭐⭐⭐ ​

  1. Degree = columns; cardinality = rows.
  2. Logical data independence is harder than physical.
  3. Schema = intension (stable); instance = extension (changes).
  4. TRUNCATE = DDL; DELETE = DML; SELECT = DML (DQL in some books).
  5. PK = UNIQUE + NOT NULL, one per table. FK may be NULL and may repeat.
  6. Weak entity: total participation in the identifying relationship; PK = owner PK + discriminator.
  7. M:N β†’ separate table; 1:N β†’ FK on the N side.
  8. Natural join with no common attribute = Cartesian product.
  9. Ο€ removes duplicates in relational algebra; SQL SELECT keeps them.
  10. "For all" queries β†’ division.
  11. Intersection is not a fundamental RA operator.
  12. COUNT(*) counts NULL rows; every other aggregate ignores NULLs.
  13. AVG divides by the non-NULL count.
  14. NOT IN against a list containing NULL β†’ empty result.
  15. NULL = NULL is UNKNOWN; use IS NULL.
  16. CHECK constraints let NULL through.
  17. A SELECT alias can't be used in WHERE.
  18. WHERE filters rows, HAVING filters groups; aggregates go in HAVING/SELECT/ORDER BY only.
  19. UNION removes duplicates; UNION ALL keeps them.
  20. Only one clustered index per table.
  21. Every binary relation is in BCNF.
  22. 3NF: LHS super key OR RHS prime. BCNF: LHS super key.
  23. BCNF decomposition may lose dependencies; 3NF synthesis never does.
  24. Lossless ⇔ common attributes are a key of one side. Lossy β‡’ extra tuples.
  25. Conflict serializable ⇔ acyclic precedence graph. VS but not CS β‡’ blind writes.
  26. Strict βŠ‚ Cascadeless βŠ‚ Recoverable.
  27. 2PL β‡’ conflict serializability, not deadlock freedom. Conservative 2PL β‡’ deadlock-free.
  28. Strict 2PL holds X locks until commit; rigorous 2PL holds all locks.
  29. Timestamp ordering: no deadlock, possible starvation. Thomas' rule ignores obsolete writes.
  30. Wait–die: old waits, young dies. Wound–wait: old wounds young, young waits.
  31. Deferred update β†’ redo only; immediate β†’ undo + redo; shadow paging β†’ neither.
  32. WAL: log record before data page.
  33. Steal β†’ undo needed; no-force β†’ redo needed.
  34. Checkpoints shorten recovery.
  35. Primary index sparse, secondary dense; at most one primary/clustering index.
  36. B+ tree: data only in leaves, linked leaves, best for range queries.
  37. Hash index: equality only.
  38. Default isolation: MySQL InnoDB = Repeatable Read; Oracle/PostgreSQL/SQL Server = Read Committed.
  39. Repeatable Read (standard) still allows phantoms.
  40. ACID: C is the programmer's job; A and D the recovery system's; I the concurrency control's.