Theme
DBMS: Complete MCQ Revision Notes β
Legend: β = asked very often Β· β οΈ = trap / commonly confused Β· All numerical examples were checked by running code.
Contents
- Fundamentals
- ER Model and ERβTable mapping
- Relational Model, Keys and Constraints
- Relational Algebra and Calculus
- SQL (execution order, NULLs, aggregates, joins, subqueries, DDL/DML, views, indexes, triggers, window functions, must-know queries)
- Functional Dependencies
- Normalization
- Transactions and Schedules
- Concurrency Control
- Recovery
- Storage, File Organization, Hashing, RAID
- Indexing, B-tree and B+ tree
- Query Processing and Optimization
- Distributed DB, NoSQL/CAP, Data Warehousing/OLAP, DB Security
- 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) β:
- Data redundancy and inconsistency
- Difficulty in accessing data (new query = new program)
- Data isolation (data scattered in different files/formats)
- Integrity problems (constraints buried in application code)
- Atomicity problems (partial updates after failure)
- Concurrent-access anomalies
- 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 β β
| Level | Also called | Describes |
|---|---|---|
| External | View level | What a particular user/app sees (many external schemas) |
| Conceptual | Logical level | What data is stored and the relationships (one per DB) |
| Internal | Physical level | How 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 ββ β
| Category | Commands |
|---|---|
| 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 β β
| Symbol | Meaning |
|---|---|
| Rectangle | Strong entity set |
| Double rectangle | Weak entity set |
| Ellipse | Attribute |
| Double ellipse | Multivalued attribute |
| Dashed ellipse | Derived attribute |
| Ellipse with child ellipses | Composite attribute |
| Underlined name | Key attribute |
| Dashed underline | Partial key (discriminator) of a weak entity |
| Diamond | Relationship set |
| Double diamond | Identifying relationship (for a weak entity) |
| Double line | Total 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 construct | Result |
|---|---|
| Strong entity | One table. Composite attributes β only their simple components. Derived attributes usually not stored |
| Multivalued attribute | Separate table (entity PK + attribute), PK = both |
| Weak entity | Table containing owner's PK (as FK) + partial key; PK = both. Identifying relationship needs no table |
| 1:1 relationship | Put FK on either side (prefer the side with total participation) |
| 1:N relationship | FK on the N side; no separate table |
| M:N relationship | Separate table; PK = PKs of both sides (+ descriptive attributes) |
| Ternary / n-ary | Separate table with FKs to all participants |
| Recursive 1:N | Self-referencing FK in the same table (emp.manager_id β emp.emp_id) |
| Recursive M:N | Separate 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 βββ β
| Key | Definition |
|---|---|
| Super key | Any set of attributes that uniquely identifies a tuple |
| Candidate key | Minimal super key (no proper subset is a super key) |
| Primary key | The candidate key chosen by the designer. NOT NULL + UNIQUE. Only one per table |
| Alternate (secondary) key | Candidate keys not chosen as PK |
| Composite key | Key with β₯ 2 attributes |
| Foreign key | Attribute(s) referring to the PK or a UNIQUE key of another (or the same) table |
| Surrogate key | System-generated (auto-increment, UUID), no business meaning |
| Natural key | Real-world identifier used as key (email, Aadhaar no.) |
| Unique key | Unique 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).
| Relation | Candidate keys | Super keys |
|---|---|---|
| R(A,B,C,D) | A | 8 |
| R(A,B,C,D) | A, B | 12 |
| R(A,B,C,D) | A, BC | 10 |
| R(A,B,C,D) | AB, CD | 7 |
| R(A,B,C,D) | AB, BC | 6 |
| R(A,B,C,D,E) | AB | 8 |
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? ββ
| Operation | On parent (referenced) table | On child (referencing) table |
|---|---|---|
| INSERT | Never violates | May violate (FK value not in parent) |
| DELETE | May violate (orphans) | Never violates |
| UPDATE | May 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 ββ β
| Type | Operators |
|---|---|
| Fundamental (6) | Ο select, Ο project, βͺ union, β set difference, Γ Cartesian product, Ο rename |
| Derived | β© intersection (= R β (R β S)), joins β (theta, equi, natural), Γ· division, β assignment |
| Extended | Generalized 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) ββ
| Operation | Min | Max |
|---|---|---|
| R Γ S | mΒ·n | mΒ·n |
| R β S (natural) | 0 | mΒ·n |
| R β S on R.FK = S.PK, FK NOT NULL with referential integrity | m | m (exactly m) |
| R β S (left outer) | m | mΒ·n (if n β₯ 1) |
| R β S (full outer) | max(m, n) | max(mΒ·n, m + n) |
| R βͺ S | max(m, n) | m + n |
| R β© S | 0 | min(m, n) |
| R β S | 0 | m |
| Ο(R) | 0 | m |
| Ο(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 ββ β
| WHERE | HAVING |
|---|---|
| Filters rows before grouping | Filters groups after grouping |
| No aggregate functions | Aggregates allowed |
| Works without GROUP BY | Usually 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_tablereturns 1 row (value 0). The same withGROUP BY xreturns 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 withIS 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. β οΈ<> ANYis 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;> ANYlike> 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 5returns nothing. - IN (list), IS NULL, EXISTS, ANY/SOME, ALL.
5.9 DELETE vs TRUNCATE vs DROP βββ β
| DELETE | TRUNCATE | DROP | |
|---|---|---|---|
| Type | DML | DDL | DDL |
| Removes | Selected rows | All rows | Table structure + data + indexes + constraints + triggers |
| WHERE clause | Yes | No | No |
| Rollback | Yes | Oracle/MySQL: no (implicit commit). SQL Server/PostgreSQL: yes inside a transaction | Generally no (Oracle recycle bin / FLASHBACK aside) |
| Triggers | Fires DELETE triggers | Doesn't fire row DELETE triggers | n/a |
| Speed | Slow (row by row, fully logged) | Fast (deallocates pages) | Fast |
| Identity / auto-increment | Not reset | Reset | Gone |
| Table structure | Kept | Kept | Removed |
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 spundoes 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:
| Salary | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 100 | 1 | 1 | 1 |
| 90 | 2 | 2 | 2 |
| 90 | 3 | 2 | 2 |
| 80 | 4 | 4 (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 2gives 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 asLIMIT 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 salis 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 RECURSIVEfor 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) ββ β
- Reflexivity: if Y β X then X β Y
- Augmentation: X β Y β XZ β YZ
- 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 βββ β
- Attributes on no right-hand side must be in every key (essential attributes).
- Attributes that appear only on right-hand sides are in no key.
- 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.
- 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 β
| NF | Condition |
|---|---|
| 1NF | All values atomic; no repeating groups or multivalued attributes |
| 2NF | 1NF + no partial dependency: no non-prime attribute depends on a proper subset of any candidate key |
| 3NF | 2NF + no transitive dependency. Test: for every non-trivial X β A, X is a super key OR A is prime |
| BCNF | For every non-trivial X β Y, X is a super key |
| 4NF | BCNF + 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 |
| DKNF | Every 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 βββ β
- Find all candidate keys β prime attributes.
- 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).
- The answer is the highest level with no violation.
| R and FDs | Keys | Highest NF | Reason |
|---|---|---|---|
| R(A,B,C,D): AB β C, B β D | AB | 1NF | B β D: D non-prime, B β key (partial) |
| R(A,B,C,D): AB β C, C β D | AB | 2NF | C β D transitive |
| R(A,B,C): AB β C, C β B | AB, AC | 3NF | C β B: C not a super key, but B is prime |
| R(A,B,C,D,E): A β B, BC β E, ED β A | ACD, BCD, CDE | 3NF | all attributes prime; A β B breaks BCNF |
| Any R(A,B) | BCNF | binary 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.
| Target | Always lossless? | Always dependency preserving? |
|---|---|---|
| 3NF (synthesis algorithm) | Yes | Yes β |
| BCNF | Yes | No β οΈ |
| 4NF | Yes | No |
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 βββ β
| Property | Meaning | Ensured by |
|---|---|---|
| Atomicity | All or nothing | Recovery system / transaction manager (undo using logs) |
| Consistency | Moves the DB from one consistent state to another | Application programmer + integrity constraints |
| Isolation | Concurrent transactions don't see each other's intermediate state; result equals some serial order | Concurrency-control manager |
| Durability | Committed changes survive failures | Recovery 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 βββ β
| Class | Rule |
|---|---|
| Recoverable | If Tj reads a value written by Ti, Ti commits before Tj commits |
| Cascadeless (ACA) | Tj reads only values written by committed transactions |
| Strict | No 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 level | Dirty read | Non-repeatable read | Phantom |
|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible |
| Read Committed | Prevented | Possible | Possible |
| Repeatable Read | Prevented | Prevented | Possible |
| Serializable | Prevented | Prevented | Prevented |
- 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 βββ β
| Variant | Rule | Guarantees | Deadlock? |
|---|---|---|---|
| Basic 2PL | Growing phase (only acquire), then shrinking phase (only release). Lock point = last lock acquired | Conflict serializability (serial order = lock-point order) | Possible; cascading rollback possible |
| Strict 2PL | Basic + hold all X locks until commit/abort | CS + strict schedules (so cascadeless and recoverable) | Possible |
| Rigorous 2PL | Hold all locks (S and X) until commit/abort | CS + strict; serial order = commit order | Possible |
| Conservative (static) 2PL | Acquire all locks before starting (declare read/write sets in advance) | CS | Deadlock-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.
| IS | IX | S | SIX | X | |
|---|---|---|---|---|---|
| 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.
| Scheme | Requester Ti older than holder Tj | Requester Ti younger than holder Tj |
|---|---|---|
| WaitβDie (non-preemptive) | Ti waits | Ti 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.
| Technique | When the DB on disk is updated | Needed after a crash |
|---|---|---|
| Deferred modification | Only after commit | REDO only (NO-UNDO/REDO) |
| Immediate modification | Possibly before commit | UNDO + REDO |
| Shadow paging | Copy-on-write pages; commit = switch the page-table pointer | Neither (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 ββ β
| Organization | Insert | Search | Notes |
|---|---|---|---|
| Heap (unordered) | Fast (append) | Linear: b/2 average, b worst | Good for bulk loading |
| Sequential (sorted) | Costly (overflow blocks / reorganization) | Binary search: βlogβ bβ | Good for ordered/range access |
| Hashed | Fast | ~1 block for equality | Bad for range queries |
| Multitable clustering | n/a | Fast joins | Related 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 ββ β
| Level | Technique | Survives | Notes |
|---|---|---|---|
| 0 | Block striping, no redundancy | 0 failures | Fastest, full capacity |
| 1 | Mirroring | 1 disk per mirror pair | 50% capacity, fast reads |
| 2 | Bit-level striping + Hamming ECC | 1 | Obsolete |
| 3 | Bit/byte-level striping + dedicated parity disk | 1 | |
| 4 | Block-level striping + dedicated parity disk | 1 | Parity disk is a write bottleneck |
| 5 | Block-level striping + distributed parity | 1 | Usable (nβ1)/n; most common |
| 6 | Block striping + double distributed parity (P+Q) | 2 | Usable (nβ2)/n |
| 10 (1+0) | Mirror, then stripe | 1 per mirror pair | Fast 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.
| Index | Built on | Dense / sparse | Per file |
|---|---|---|---|
| Primary | Ordering key field (sorted, unique) | Sparse (one entry per block, the block's anchor record) | At most one |
| Clustering | Ordering 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) |
| Secondary | Non-ordering field (key or non-key) | Dense | Many |
- β οΈ 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-tree | B+ tree | |
|---|---|---|
| Data/record pointers | In all nodes | Only in leaves |
| Keys | Each key appears once | Internal keys are repeated in the leaves (internal nodes only route) |
| Leaves | Not linked | Linked (fast sequential and range scans) |
| Fan-out | Lower | Higher β shorter tree |
| Search | May stop at an internal node | Always ends at a leaf (uniform cost) |
| Typical use | Less common | Standard 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 ββ β
- Perform selections as early as possible (push Ο down).
- Perform projections early (push Ο down).
- Do the most restrictive selections and joins first.
- Replace a Γ followed by Ο with a β.
- 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) β β
| Algorithm | Block transfers | Notes |
|---|---|---|
| Nested-loop | n_rΒ·b_s + b_r | If the smaller relation fits in memory: b_r + b_s |
| Block nested-loop | b_rΒ·b_s + b_r | Use the smaller relation as the outer |
| Indexed nested-loop | b_r + n_rΒ·c | c = cost of one index lookup on the inner |
| Merge (sort-merge) join | b_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 type | Examples | Typical use |
|---|---|---|
| Keyβvalue | Redis, DynamoDB, Riak | Caching, sessions |
| Document | MongoDB, CouchDB | Flexible JSON-like documents |
| Column-family (wide column) | Cassandra, HBase, Bigtable | Huge write-heavy workloads, time series |
| Graph | Neo4j, Amazon Neptune | Relationship-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 ββ β
| OLTP | OLAP |
|---|---|
| Day-to-day transactions | Analysis and decision support |
| Current, detailed data | Historical, summarized data |
| Normalized (3NF) | Denormalized (star/snowflake) |
| Many short read/write transactions | Few complex read-heavy queries |
| Milliseconds | Seconds 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 βββ β
- Degree = columns; cardinality = rows.
- Logical data independence is harder than physical.
- Schema = intension (stable); instance = extension (changes).
- TRUNCATE = DDL; DELETE = DML; SELECT = DML (DQL in some books).
- PK = UNIQUE + NOT NULL, one per table. FK may be NULL and may repeat.
- Weak entity: total participation in the identifying relationship; PK = owner PK + discriminator.
- M:N β separate table; 1:N β FK on the N side.
- Natural join with no common attribute = Cartesian product.
- Ο removes duplicates in relational algebra; SQL SELECT keeps them.
- "For all" queries β division.
- Intersection is not a fundamental RA operator.
- COUNT(*) counts NULL rows; every other aggregate ignores NULLs.
- AVG divides by the non-NULL count.
- NOT IN against a list containing NULL β empty result.
- NULL = NULL is UNKNOWN; use IS NULL.
- CHECK constraints let NULL through.
- A SELECT alias can't be used in WHERE.
- WHERE filters rows, HAVING filters groups; aggregates go in HAVING/SELECT/ORDER BY only.
- UNION removes duplicates; UNION ALL keeps them.
- Only one clustered index per table.
- Every binary relation is in BCNF.
- 3NF: LHS super key OR RHS prime. BCNF: LHS super key.
- BCNF decomposition may lose dependencies; 3NF synthesis never does.
- Lossless β common attributes are a key of one side. Lossy β extra tuples.
- Conflict serializable β acyclic precedence graph. VS but not CS β blind writes.
- Strict β Cascadeless β Recoverable.
- 2PL β conflict serializability, not deadlock freedom. Conservative 2PL β deadlock-free.
- Strict 2PL holds X locks until commit; rigorous 2PL holds all locks.
- Timestamp ordering: no deadlock, possible starvation. Thomas' rule ignores obsolete writes.
- Waitβdie: old waits, young dies. Woundβwait: old wounds young, young waits.
- Deferred update β redo only; immediate β undo + redo; shadow paging β neither.
- WAL: log record before data page.
- Steal β undo needed; no-force β redo needed.
- Checkpoints shorten recovery.
- Primary index sparse, secondary dense; at most one primary/clustering index.
- B+ tree: data only in leaves, linked leaves, best for range queries.
- Hash index: equality only.
- Default isolation: MySQL InnoDB = Repeatable Read; Oracle/PostgreSQL/SQL Server = Read Committed.
- Repeatable Read (standard) still allows phantoms.
- ACID: C is the programmer's job; A and D the recovery system's; I the concurrency control's.