IIT Madras Zanzibar · Teaching

← Z2004 Overview

Lab Explorer & SQLite3 Code Previews

Browser-readable SQL, relational algebra, normalization, indexing, and transaction code previews paired with runnable Colab notebooks and the automated unittest suite.

Schema DDLSQLite3 / PostgreSQL compatible DDL

School Database Relational Schema (SQL)

Standalone SQL schema defining Departments, Students, Courses, and Enrollments with CHECK and foreign-key constraints.

SQL Preview
-- Z2004 Relational Schema & Sample Data (SQLite / Standard SQL)
PRAGMA foreign_keys = ON;

DROP TABLE IF EXISTS Enrolment;
DROP TABLE IF EXISTS Course;
DROP TABLE IF EXISTS Student;

CREATE TABLE Student (
    SID        INTEGER PRIMARY KEY AUTOINCREMENT,
    Name       TEXT    NOT NULL,
    Dept       TEXT    NOT NULL,
    GPA        REAL    CHECK (GPA IS NULL OR (GPA BETWEEN 0.00 AND 4.00)),
Lab 1Schema DDL · PRAGMA foreign_keys = ON

ER-to-Relational DDL & Foreign Keys

Builds normalized Department/Course/Enrollment tables with CASCADE/RESTRICT referential actions.

SQL Preview
import sqlite3
from pathlib import Path


def build_school_db(conn: sqlite3.Connection) -> None:
    """Create Student, Course, and Enrolment tables with PK, FK, UNIQUE, and CHECK constraints."""
    conn.execute("PRAGMA foreign_keys = ON;")
    conn.executescript(
        """
        DROP TABLE IF EXISTS Enrolment;
        DROP TABLE IF EXISTS Course;
Lab 2Set algebra · Select, Project, Natural Join, Division

Relational Algebra Engine

Evaluates selection, projection, natural join, and relational division directly over Python tuple sets.

Python Preview
from typing import Callable, Iterable


Row = dict[str, object]
Relation = list[Row]


def select(rel: Relation, pred: Callable[[Row], bool]) -> Relation:
    return [dict(r) for r in rel if pred(r)]

Lab 3SQLite3 · DENSE_RANK(), moving frames, recursive CTEs

SQL Joins, Views, CTEs & Window Functions

Executes multi-table joins, non-materialized views, ranking windows, and recursive hierarchy walks.

Python Preview
import sqlite3


def run_tests() -> None:
    conn = sqlite3.connect(":memory:")
    conn.executescript(
        """
        CREATE TABLE Students (StudentID TEXT PRIMARY KEY, Name TEXT, Year INT, Hostel TEXT);
        CREATE TABLE FoodItems (ItemID TEXT PRIMARY KEY, Name TEXT UNIQUE, Category TEXT, Price REAL);
        CREATE TABLE Orders (OrderID INT PRIMARY KEY, StudentID TEXT, ItemName TEXT, Qty INT);
Lab 4Closure O(|F|*|R|) · Candidate keys & lossless tests

Normalization: FD Closure & BCNF Checker

Computes attribute closures X+, enumerates candidate keys, and checks BCNF and binary lossless joins.

Python Preview
from itertools import combinations


FD = tuple[frozenset[str], frozenset[str]]


def attribute_closure(attrs: frozenset[str], fds: list[FD]) -> frozenset[str]:
    """Compute X+ under Armstrong's axioms."""
    closure = set(attrs)
    changed = True
    while changed:
Lab 5O(log_F N) range scan · EXPLAIN QUERY PLAN

B+ Tree Range Scans & Query Plans

Compares full table scans against composite B+ tree index lookups using SQLite query plans.

Python Preview
import bisect
import random
import sqlite3
import time


class BPlusLeaf:
    def __init__(self) -> None:
        self.keys: list[int] = []
        self.vals: list[str] = []
        self.next: BPlusLeaf | None = None
Lab 6Precedence graph O(n^2) · Rollback atomicity

ACID Transactions & Conflict Serializability

Tests transaction rollback atomicity in SQLite and detects precedence-graph cycles.

Python Preview
import sqlite3
import tempfile
from pathlib import Path


def is_conflict_serializable(schedule: list[tuple[str, str, str]]) -> tuple[bool, list[str]]:
    """Test conflict serializability via precedence (serialization) graph cycle check.

    Each operation is (txn_id, 'R'|'W', item).
    """
    txns = sorted({t for t, _, _ in schedule})
Lab 7BNL, Sort-Merge, Grace Hash I/O · Indexed SEARCH

Query Optimization & Join Cost Models

Models disk page I/O across Block Nested-Loop, Sort-Merge, and Grace Hash Joins with SQLite plans.

Python Preview
import math
import sqlite3
import tempfile
from pathlib import Path


def cost_block_nested_loop(b_outer: int, b_inner: int, mem_pages: int) -> int:
    """Estimate page I/Os for Block Nested-Loop Join with M buffer pages."""
    if mem_pages < 3:
        raise ValueError("Need at least 3 buffer pages (M-2 outer, 1 inner, 1 output)")
    chunks = math.ceil(b_outer / (mem_pages - 2))
Lab 8JSON1 aggregation & BFS hops vs. recursive CTE parity

NoSQL Document & Graph Patterns vs. SQLite

Demonstrates JSON document queries and BFS property-graph traversal matching SQLite parity.

Python Preview
import json
import sqlite3
from collections import deque


def build_document_store(orders: list[dict]) -> dict[str, dict]:
    """Index embedded order documents by order_id for single-lookup document access."""
    return {doc["order_id"]: doc for doc in orders}


def document_revenue_by_region(doc_store: dict[str, dict]) -> dict[str, float]: