Database Management Systems (DBMS) – Complete Notes

DBMS concepts, SQL queries, normalization और transactions – Detailed notes in English and हिंदी

1. Introduction to DBMS – Evolution & Core Concept

English

  1. Problem: Before DBMS, data was stored in file systems — separate files on disk managed by application programs. This caused serious problems: data redundancy (same data stored in many files), data inconsistency (different copies disagree), difficulty in accessing data (each query needed custom code), data isolation, integrity problems, atomicity problems (partial updates on crash), concurrent access anomalies, and security issues. There was no central control over data.
  2. Definition: A Database Management System (DBMS) is a software system that stores, retrieves, and manages data in a database. It provides an interface between users/applications and the physical database. A database is an organised collection of related data. A DBMS adds a layer of abstraction (metadata, integrity, security, concurrency) on top of raw files. Examples: MySQL, PostgreSQL, Oracle, SQL Server, SQLite, MongoDB.
  3. Example: A university stores students, courses, and enrollments. Without a DBMS, three separate files might duplicate a student's name. With a DBMS, the student is stored once, and courses/enrollments refer to that record by its ID. One central query can join tables:
    SELECT s.name, c.title
    FROM Students s
    JOIN Enrollments e ON s.id = e.student_id
    JOIN Courses c     ON c.id = e.course_id
    WHERE s.id = 42;
  4. Types:
    Type Description Example
    Hierarchical DBMS Tree-like (parent-child). One parent per child. IBM IMS
    Network DBMS Graph-like; a child can have multiple parents. IDMS
    Relational DBMS (RDBMS) Data stored in tables (relations); SQL-based. MySQL, Oracle, PostgreSQL
    Object-Oriented DBMS Stores objects directly. db4o, ObjectDB
    NoSQL DBMS Document, key-value, column, graph stores. MongoDB, Redis, Cassandra, Neo4j
    NewSQL SQL + scalability of NoSQL. CockroachDB, Google Spanner
  5. Advantages:
    • Reduced redundancy: Store data once, reference by key.
    • Consistency: Single source of truth; integrity constraints.
    • Sharing: Multiple users and apps access the same data safely.
    • Security: Authentication, authorisation (GRANT/REVOKE), views.
    • Backup & recovery: Systematic logging and restoration.
    • Concurrency: Transactions allow many users to work safely.
    • Data independence: Physical/logical changes do not break apps.
    • Query language: SQL makes data access simple and standard.
  6. Disadvantages:
    • Cost: DBMS software/licensing and hardware can be expensive.
    • Complexity: Setup, tuning, and administration need skilled staff.
    • Overhead: Higher storage and processing than raw files.
    • Single point of failure: If the DBMS goes down, all apps suffer.
    • Security is critical: Centralised data is a bigger target.
    • Scalability challenges: Vertical scaling has limits; distributed setups are complex.
  7. Characteristics:
    • Self-describing: The DBMS stores metadata (schema) in a system catalogue.
    • Insulation between programs and data: Program-data independence.
    • Support for multiple views: Different users see different views.
    • Multi-user: Concurrent access with integrity.
    • Data abstraction: Physical, logical, and view levels.
    • Transaction management: ACID properties.
  8. Diagram: Three-schema architecture (ANSI/SPARC)
        Users / Applications
        ─────────────────────────────
        External Level  →  Views (View 1, View 2, ...)
        ─────────────────────────────
        Conceptual Level  →  Logical Schema (Tables, Constraints)
        ─────────────────────────────
        Internal Level  →  Physical Schema (Files, Indexes)
        ─────────────────────────────
                 Storage / Disk
        ─────────────────────────────
    
        Mappings:
         External → Conceptual (View mapping)
         Conceptual → Internal (Storage mapping)
  9. Conclusion: A DBMS solves the fundamental problems of file-based data storage — redundancy, inconsistency, and lack of control — by introducing abstraction, integrity constraints, concurrency, and recovery. It provides a single, secure, and shared home for an organisation's data. RDBMSs dominate the market, but NoSQL and NewSQL databases address modern scalability and flexibility needs. Learning DBMS is foundational for backend development, data engineering, and analytics.
  10. Exercise:
    1. List five problems of file-based data management and explain how a DBMS solves each.
    2. Differentiate between a database and a DBMS with an example.
    3. Explain the three-schema architecture with a diagram.
    4. Compare any three DBMS types in a short table.
    5. Name three DBMSs and one real-world use case for each.

हिंदी (सरल)

  1. समस्या: DBMS से पहले data file systems में रखी जाती थी — disk पर अलग-अलग files जिन्हें application programs manage करते थे। इससे बड़ी समस्याएँ हुईं: data redundancy (एक ही data कई files में), data inconsistency (copies अलग-अलग), data access में कठिनाई (हर query के लिए नया code), data isolation, integrity issues, atomicity problems (crash पर आधे-अधूरे updates), concurrent access anomalies और security issues। Data पर कोई central control नहीं था।
  2. परिभाषा: DBMS (Database Management System) एक software system है जो database में data को store, retrieve और manage करता है। यह users/applications और physical database के बीच interface देता है। एक database related data का organised collection है। DBMS raw files के ऊपर abstraction (metadata, integrity, security, concurrency) की layer जोड़ता है। उदाहरण: MySQL, PostgreSQL, Oracle, SQL Server, SQLite, MongoDB।
  3. उदाहरण: एक university students, courses और enrollments रखती है। DBMS के बिना तीन अलग files में student का नाम duplicate हो सकता है। DBMS के साथ student एक बार store होता है, और courses/enrollments उस record को ID से refer करते हैं। एक query से tables join कर सकते हैं:
    SELECT s.name, c.title
    FROM Students s
    JOIN Enrollments e ON s.id = e.student_id
    JOIN Courses c     ON c.id = e.course_id
    WHERE s.id = 42;
  4. प्रकार:
    प्रकार विवरण उदाहरण
    Hierarchical DBMS Tree जैसा (parent-child)। हर child का एक parent। IBM IMS
    Network DBMS Graph जैसा; child के कई parents हो सकते हैं। IDMS
    Relational DBMS (RDBMS) Tables (relations) में data; SQL-based। MySQL, Oracle, PostgreSQL
    Object-Oriented DBMS Objects सीधे store होते हैं। db4o, ObjectDB
    NoSQL DBMS Document, key-value, column, graph stores। MongoDB, Redis, Cassandra, Neo4j
    NewSQL SQL + NoSQL की scalability। CockroachDB, Google Spanner
  5. लाभ:
    • Redundancy कम: Data एक बार store करें, key से refer करें।
    • Consistency: Single source of truth; integrity constraints।
    • Sharing: कई users और apps एक ही data safely access करते हैं।
    • Security: Authentication, authorisation (GRANT/REVOKE), views।
    • Backup & recovery: Systematic logging और restoration।
    • Concurrency: Transactions से कई users safely काम कर सकते हैं।
    • Data independence: Physical/logical बदलाव apps को नहीं तोड़ते।
    • Query language: SQL से data access simple और standard।
  6. नुकसान:
    • Cost: DBMS software/licensing और hardware महँगे।
    • Complexity: Setup, tuning और administration के लिए skilled staff।
    • Overhead: Raw files से ज़्यादा storage और processing।
    • Single point of failure: DBMS down हो तो सभी apps down।
    • Security critical: Centralised data बड़ा target।
    • Scalability challenges: Vertical scaling की सीमाएँ; distributed setups जटिल।
  7. विशेषताएँ:
    • Self-describing: DBMS metadata (schema) system catalogue में रखता है।
    • Program-data independence: Programs और data में insulation।
    • Multiple views: अलग users को अलग views दिखते हैं।
    • Multi-user: Concurrent access integrity के साथ।
    • Data abstraction: Physical, logical और view levels।
    • Transaction management: ACID properties।
  8. आरेख: Three-schema architecture (ANSI/SPARC)
        Users / Applications
        ─────────────────────────────
        External Level  →  Views (View 1, View 2, ...)
        ─────────────────────────────
        Conceptual Level  →  Logical Schema (Tables, Constraints)
        ─────────────────────────────
        Internal Level  →  Physical Schema (Files, Indexes)
        ─────────────────────────────
                 Storage / Disk
        ─────────────────────────────
    
        Mappings:
         External → Conceptual (View mapping)
         Conceptual → Internal (Storage mapping)
  9. निष्कर्ष: DBMS file-based data storage की मूल समस्याएँ — redundancy, inconsistency और control की कमी — abstraction, integrity constraints, concurrency और recovery से हल करता है। यह organisation के data का एक single, secure और shared घर देता है। RDBMS बाज़ार में dominante हैं, लेकिन NoSQL और NewSQL modern scalability और flexibility की ज़रूरतें पूरी करते हैं। DBMS सीखना backend development, data engineering और analytics की नींव है।
  10. अभ्यास:
    1. File-based data management की पाँच समस्याएँ लिखिए और बताइए DBMS हर एक को कैसे हल करता है।
    2. Database और DBMS में फर्क उदाहरण के साथ समझाइए।
    3. Three-schema architecture को diagram के साथ समझाइए।
    4. किन्हीं तीन DBMS types की छोटी table में तुलना कीजिए।
    5. तीन DBMS के नाम और हर एक का एक real-world use case दीजिए।

2. DBMS Architecture & Data Models

English

  1. Problem: A database has to serve many users, applications, and devices, all at the same time, on top of a single physical store. Without a clear architecture, we would not know where to enforce security, where to translate queries into physical reads, or how to change storage technology without breaking applications. Similarly, without a data model we could not describe what the data looks like in a way that both users and machines understand.
  2. Definition: DBMS architecture defines how the DBMS is structured internally and how it interacts with users/applications. The ANSI/SPARC three-schema architecture (external, conceptual, internal) is the classic reference. Data models are formal ways to describe data, relationships, and constraints. Common models: hierarchical, network, relational, object-oriented, and document/graph (NoSQL).
  3. Example: A 3-tier (three-tier) client-server DBMS setup:
       Client (Web Browser / Mobile App)
                 │  HTTP
                 ▼
       Application Server (Business Logic)
                 │  SQL / Driver
                 ▼
       DBMS Server (MySQL / PostgreSQL)
                 │  Reads/Writes
                 ▼
       Physical Storage (Disks, Files)
    Users never talk to the DBMS directly; the application layer enforces business rules and the DBMS enforces data integrity.
  4. Types:

    A. DBMS Architectures:

    Architecture Description Use Case
    1-Tier Client, application, and DBMS on same machine. Learning, single-user desktop apps.
    2-Tier Client talks directly to DBMS over network. LAN apps with trusted clients.
    3-Tier Client → App Server → DBMS. Web apps, enterprise systems.
    N-Tier More layers: cache, queue, microservices. Large-scale distributed apps.

    B. Data Models:

    Model Description
    Hierarchical Tree structure, one parent per record.
    Network Graph, a record can have many parents.
    Relational Tables with rows and columns; SQL-based.
    Object-Oriented Objects, classes, inheritance.
    Document (NoSQL) JSON/BSON documents; nested.
    Graph (NoSQL) Nodes and edges with properties.
  5. Advantages:
    • Clear responsibility: Each layer enforces specific rules.
    • Scalability: App servers and DBMS can scale independently.
    • Security: DBMS not directly exposed to the internet.
    • Data independence: Change storage without changing apps.
    • Reuse: Multiple apps can share the same DBMS.
  6. Disadvantages:
    • Latency: More layers = more hops = slower responses.
    • Complexity: More components to configure and monitor.
    • Cost: Application servers add infrastructure cost.
    • Debugging difficulty: Problems can be in any layer.
  7. Characteristics:
    • Three-schema architecture: External, conceptual, internal.
    • Client-server: DBMS acts as a server; clients request services.
    • Modularity: Query processor, storage manager, transaction manager.
    • Data independence: Logical and physical.
    • Layered communication: Well-defined protocols between layers.
  8. Diagram: DBMS internal modules
            ┌────────────────────────────────────┐
            │       Query Processor              │
            │  Parser → Optimizer → Executor     │
            └─────────────┬──────────────────────┘
                          │
            ┌─────────────▼──────────────────────┐
            │        Transaction Manager         │
            │  Concurrency Control + Recovery    │
            └─────────────┬──────────────────────┘
                          │
            ┌─────────────▼──────────────────────┐
            │        Storage Manager             │
            │  Buffer Manager + File Manager     │
            └─────────────┬──────────────────────┘
                          │
            ┌─────────────▼──────────────────────┐
            │        Physical Storage            │
            │        (Disks, Files, Indexes)     │
            └────────────────────────────────────┘
  9. Conclusion: Understanding DBMS architecture explains where each job happens: parsing and optimising queries, managing transactions, and reading/writing physical storage. Data models give us a shared language to describe data at every level, from the user's view down to the disk. The three-schema architecture and 3-tier deployment remain the reference patterns for building secure, scalable, and maintainable database systems.
  10. Exercise:
    1. Explain the difference between 1-tier, 2-tier, and 3-tier DBMS architectures.
    2. Draw the ANSI/SPARC three-schema diagram and explain each level.
    3. Compare relational and document (NoSQL) data models with examples.
    4. List the modules inside a DBMS and describe their roles.
    5. Give two real-world examples where 3-tier architecture is essential.

हिंदी (सरल)

  1. समस्या: एक database को कई users, applications और devices को एक साथ serve करना होता है, उसी physical store के ऊपर। बिना स्पष्ट architecture के पता नहीं चलेगा कि security कहाँ लगाएँ, query को physical read में कहाँ translate करें, या storage technology कैसे बदलें बिना applications तोड़े। इसी तरह, data model के बिना यह describe नहीं कर सकते कि data कैसा दिखता है — users और machines दोनों की समझ में आने वाले तरीके से।
  2. परिभाषा: DBMS architecture यह तय करती है कि DBMS अंदर से कैसा structured है और users/applications के साथ कैसे interact करता है। ANSI/SPARC three-schema architecture (external, conceptual, internal) classic reference है। Data models data, relationships और constraints describe करने के formal तरीके हैं। प्रमुख models: hierarchical, network, relational, object-oriented, और document/graph (NoSQL)।
  3. उदाहरण: 3-tier (three-tier) client-server DBMS setup:
       Client (Web Browser / Mobile App)
                 │  HTTP
                 ▼
       Application Server (Business Logic)
                 │  SQL / Driver
                 ▼
       DBMS Server (MySQL / PostgreSQL)
                 │  Reads/Writes
                 ▼
       Physical Storage (Disks, Files)
    Users DBMS से सीधे बात नहीं करते; application layer business rules enforce करता है और DBMS data integrity।
  4. प्रकार:

    A. DBMS Architectures:

    Architecture विवरण Use Case
    1-Tier Client, application और DBMS एक ही machine पर। Learning, single-user desktop apps।
    2-Tier Client सीधे DBMS से network पर बात करता है। LAN apps with trusted clients।
    3-Tier Client → App Server → DBMS। Web apps, enterprise systems।
    N-Tier और layers: cache, queue, microservices। Large-scale distributed apps।

    B. Data Models:

    Model विवरण
    Hierarchical Tree structure, हर record का एक parent।
    Network Graph, एक record के कई parents हो सकते हैं।
    Relational Tables with rows और columns; SQL-based।
    Object-Oriented Objects, classes, inheritance।
    Document (NoSQL) JSON/BSON documents; nested।
    Graph (NoSQL) Nodes और edges with properties।
  5. लाभ:
    • साफ responsibility: हर layer specific rules enforce करती है।
    • Scalability: App servers और DBMS अलग-अलग scale हो सकते हैं।
    • Security: DBMS सीधे internet पर expose नहीं।
    • Data independence: Storage बदलें बिना apps बदले।
    • Reuse: कई apps एक ही DBMS share कर सकते हैं।
  6. नुकसान:
    • Latency: ज़्यादा layers = ज़्यादा hops = slow responses।
    • Complexity: ज़्यादा components configure और monitor करने पड़ते हैं।
    • Cost: Application servers infrastructure cost बढ़ाते हैं।
    • Debugging difficulty: समस्या किसी भी layer में हो सकती है।
  7. विशेषताएँ:
    • Three-schema architecture: External, conceptual, internal।
    • Client-server: DBMS server की तरह; clients services माँगते हैं।
    • Modularity: Query processor, storage manager, transaction manager।
    • Data independence: Logical और physical।
    • Layered communication: Layers के बीच well-defined protocols।
  8. आरेख: DBMS internal modules
            ┌────────────────────────────────────┐
            │       Query Processor              │
            │  Parser → Optimizer → Executor     │
            └─────────────┬──────────────────────┘
                          │
            ┌─────────────▼──────────────────────┐
            │        Transaction Manager         │
            │  Concurrency Control + Recovery    │
            └─────────────┬──────────────────────┘
                          │
            ┌─────────────▼──────────────────────┐
            │        Storage Manager             │
            │  Buffer Manager + File Manager     │
            └─────────────┬──────────────────────┘
                          │
            ┌─────────────▼──────────────────────┐
            │        Physical Storage            │
            │        (Disks, Files, Indexes)     │
            └────────────────────────────────────┘
  9. निष्कर्ष: DBMS architecture समझने से यह साफ होता है कि हर काम कहाँ होता है: queries parse और optimize करना, transactions manage करना, और physical storage पर read/write। Data models हमें हर level पर data describe करने की shared भाषा देते हैं, user के view से disk तक। Three-schema architecture और 3-tier deployment secure, scalable और maintainable database systems बनाने के reference patterns बने हुए हैं।
  10. अभ्यास:
    1. 1-tier, 2-tier और 3-tier DBMS architectures का फर्क समझाइए।
    2. ANSI/SPARC three-schema diagram बनाकर हर level समझाइए।
    3. Relational और document (NoSQL) data models की तुलना उदाहरण के साथ कीजिए।
    4. DBMS के अंदर के modules list कीजिए और उनकी भूमिकाएँ बताइए।
    5. दो real-world उदाहरण दीजिए जहाँ 3-tier architecture ज़रूरी है।

3. ER Model & Entity-Relationship Diagrams

English

  1. Problem: Before writing tables, we need to design what data will be stored and how things are related. Jumping straight into SQL leads to missing fields, duplicated information, and awkward queries. A design tool was needed that lets users and designers reason about entities and relationships visually, independent of any particular DBMS.
  2. Definition: The Entity-Relationship (ER) model is a high-level conceptual data model. It represents data as entities (things), attributes (properties), and relationships (associations) between them. An ER diagram is the visual notation. It is later translated into relational tables using a systematic mapping process.
  3. Example: A university database. Entities: Student, Course, Instructor. Attributes: Student(id, name, dob), Course(code, title, credits). Relationships: Student enrolls in Course (M:N), Instructor teaches Course (1:N).
        ┌────────────┐    enrolls     ┌────────────┐
        │  Student   │◄──────────────►│   Course   │
        └────────────┘     (M:N)      └────────────┘
            │  id                          │  code
            │  name                        │  title
            │  dob                         │  credits
                                          ▲
                                          │ teaches (1:N)
                                          │
                                  ┌──────────────┐
                                  │  Instructor  │
                                  └──────────────┘
                                     id, name, dept
  4. Types:

    A. Concepts in ER Model:

    Concept Symbol Meaning
    Entity Rectangle A thing (Student, Course).
    Weak entity Double rectangle Entity with no key of its own (Dependent of Employee).
    Attribute Ellipse Property (name, age).
    Key attribute Underlined ellipse Primary identifier (id).
    Multivalued attribute Double ellipse Phone numbers (list).
    Derived attribute Dashed ellipse Age (derived from dob).
    Composite attribute Ellipse with sub-ellipses Name = first + last.
    Relationship Diamond Enrolls-in, teaches.

    B. Cardinalities:

    Cardinality Meaning Example
    1:1 One-to-one Person ↔ Passport
    1:N One-to-many Instructor → Courses
    M:N Many-to-many Student ↔ Course

    C. Participation constraints: Total vs partial; existence dependency.

  5. Advantages:
    • Visual and intuitive: Non-technical users can validate the design.
    • DBMS-independent: Same diagram maps to any relational DBMS.
    • Reduces mistakes: Catches missing entities/relationships early.
    • Documents business rules: Cardinalities capture real-world rules.
    • Direct mapping to tables: Systematic translation to relations.
  6. Disadvantages:
    • Limited for complex data: Handles simple structures better than graph-like ones.
    • Large diagrams messy: Big systems need many pages.
    • Does not capture timing: Temporal aspects not represented.
    • No operations: ER is a static design tool, not a query model.
    • Ambiguity in modeling choices: Attribute vs entity decisions vary.
  7. Characteristics:
    • Conceptual level: Independent of physical storage.
    • Entities have identity: Each instance is unique via key.
    • Relationships have degree: Unary, binary, ternary.
    • Participation: Total or partial.
    • Weak entities: Depend on an owner entity.
    • Enhanced ER (EER): Adds specialisation, generalisation, aggregation.
  8. Diagram: ER symbols summary
        Entity        ┌───────────┐
                      │  Student  │
                      └───────────┘
    
        Weak Entity   ╔═══════════╗
                      ║ Dependent ║
                      ╚═══════════╝
    
        Attribute           ( name )
    
        Key Attribute       ( id )   ← underlined
    
        Multivalued        (( phones ))
    
        Derived            ( age )   ← dashed
    
        Relationship        ◇ enrolls ◇
    
        Cardinality (1:N)  ─── 1 ───◇─── N ───
  9. Conclusion: The ER model is the bridge between a customer's requirements and a concrete database schema. Its visual notation communicates design clearly to both technical and non-technical stakeholders. Once the ER design is validated, mapping it to relations follows a well-defined procedure: strong entities become tables, weak entities become tables with a foreign key to the owner, M:N relationships become junction tables, and attributes map to columns. Mastering ER modelling prevents most downstream data problems.
  10. Exercise:
    1. Draw an ER diagram for a library (Book, Member, Loan).
    2. Draw an ER diagram for an online store (Customer, Order, Product).
    3. Identify entities, attributes, and relationships for a hospital system.
    4. Convert an M:N relationship into a junction table with sample data.
    5. Distinguish between weak entity and strong entity with an example.

हिंदी (सरल)

  1. समस्या: Tables लिखने से पहले यह design करना चाहिए कि कौन सा data store होगा और चीज़ें कैसे related हैं। सीधे SQL में कूदने से fields छूट जाते हैं, information duplicate होती है और queries अटपटी बन जाती हैं। एक design tool चाहिए जो users और designers को entities और relationships के बारे में visually सोचने दे, किसी particular DBMS से independent।
  2. परिभाषा: Entity-Relationship (ER) model एक high-level conceptual data model है। यह data को entities (चीज़ें), attributes (गुण) और उनके बीच relationships के रूप में represent करता है। ER diagram इसका visual notation है। बाद में इसे systematic mapping process से relational tables में translate किया जाता है।
  3. उदाहरण: एक university database। Entities: Student, Course, Instructor। Attributes: Student(id, name, dob), Course(code, title, credits)। Relationships: Student enrolls in Course (M:N), Instructor teaches Course (1:N)।
        ┌────────────┐    enrolls     ┌────────────┐
        │  Student   │◄──────────────►│   Course   │
        └────────────┘     (M:N)      └────────────┘
            │  id                          │  code
            │  name                        │  title
            │  dob                         │  credits
                                          ▲
                                          │ teaches (1:N)
                                          │
                                  ┌──────────────┐
                                  │  Instructor  │
                                  └──────────────┘
                                     id, name, dept
  4. प्रकार:

    A. ER Model के concepts:

    Concept Symbol मतलब
    Entity Rectangle एक चीज़ (Student, Course)।
    Weak entity Double rectangle अपनी key नहीं (Employee का Dependent)।
    Attribute Ellipse गुण (name, age)।
    Key attribute Underlined ellipse Primary identifier (id)।
    Multivalued attribute Double ellipse Phone numbers (list)।
    Derived attribute Dashed ellipse Age (dob से derived)।
    Composite attribute Ellipse with sub-ellipses Name = first + last।
    Relationship Diamond Enrolls-in, teaches।

    B. Cardinalities:

    Cardinality मतलब उदाहरण
    1:1 One-to-one Person ↔ Passport
    1:N One-to-many Instructor → Courses
    M:N Many-to-many Student ↔ Course

    C. Participation constraints: Total बनाम partial; existence dependency।

  5. लाभ:
    • Visual और intuitive: Non-technical users भी design validate कर सकते हैं।
    • DBMS-independent: वही diagram किसी भी relational DBMS में map होता है।
    • गलतियाँ जल्दी पकड़े: Missing entities/relationships शुरू में पकड़ लेता है।
    • Business rules document: Cardinalities real-world rules capture करती हैं।
    • Tables पर direct mapping: Systematic translation।
  6. नुकसान:
    • Complex data के लिए सीमित: Graph जैसी structures के लिए कमज़ोर।
    • बड़े diagrams messy: बड़े systems में कई pages।
    • Timing capture नहीं: Temporal aspects represent नहीं होते।
    • Operations नहीं: ER static design tool, query model नहीं।
    • Modeling choices में ambiguity: Attribute vs entity के फैसले अलग होते हैं।
  7. विशेषताएँ:
    • Conceptual level: Physical storage से independent।
    • Entities की identity: हर instance key से unique।
    • Relationships का degree: Unary, binary, ternary।
    • Participation: Total या partial।
    • Weak entities: Owner entity पर depend।
    • Enhanced ER (EER): Specialisation, generalisation, aggregation जोड़ता है।
  8. आरेख: ER symbols summary
        Entity        ┌───────────┐
                      │  Student  │
                      └───────────┘
    
        Weak Entity   ╔═══════════╗
                      ║ Dependent ║
                      ╚═══════════╝
    
        Attribute           ( name )
    
        Key Attribute       ( id )   ← underlined
    
        Multivalued        (( phones ))
    
        Derived            ( age )   ← dashed
    
        Relationship        ◇ enrolls ◇
    
        Cardinality (1:N)  ─── 1 ───◇─── N ───
  9. निष्कर्ष: ER model customer की requirements और concrete database schema के बीच का bridge है। इसका visual notation technical और non-technical दोनों stakeholders को design साफ communicate करता है। ER design validate होने के बाद, relations में mapping का well-defined procedure है: strong entities tables बनती हैं, weak entities owner के साथ foreign key वाली tables, M:N relationships junction tables, और attributes columns। ER modelling में महारत हासिल करना आगे की ज़्यादातर data समस्याओं को रोक देता है।
  10. अभ्यास:
    1. Library (Book, Member, Loan) का ER diagram बनाइए।
    2. Online store (Customer, Order, Product) का ER diagram बनाइए।
    3. Hospital system के लिए entities, attributes और relationships पहचानिए।
    4. M:N relationship को sample data के साथ junction table में बदलिए।
    5. Weak entity और strong entity का फर्क उदाहरण के साथ बताइए।

4. Relational Model & Keys

English

  1. Problem: A conceptual design (ER) needs a concrete, mathematical foundation so that DBMSs can enforce integrity, optimise queries, and allow data manipulation using a consistent set of rules. Designers also need clear ways to identify rows uniquely and to link related tables without duplicating data.
  2. Definition: The relational model represents data as a set of relations (tables). Each relation has a schema (columns with domains) and contains tuples (rows). The model is grounded in set theory. Relational databases are queried with SQL. Keys (super, candidate, primary, foreign, composite) provide identity and relationships between tables.
  3. Example: Schema with keys:
        Student ( student_id PK, name, email, dept_id FK )
        Department ( dept_id PK, dept_name )
        Enrollment ( student_id FK, course_id FK, grade,
                     PRIMARY KEY (student_id, course_id) )
    
        Sample row:
        Student(101, 'Amit', 'a@x.com', 3)
          └─ student_id is the primary key
          └─ dept_id refers to Department(dept_id)
  4. Types:

    A. Types of Keys:

    Key Description Example
    Super key Any set of attributes that uniquely identifies a tuple. {student_id, email}
    Candidate key Minimal super key. {student_id} or {email}
    Primary key (PK) Chosen candidate key; unique + not null. student_id
    Alternate key Candidate keys not chosen as PK. email
    Foreign key (FK) Attribute(s) referring to a PK in another table. dept_id in Student
    Composite key Key made of two or more attributes. (student_id, course_id)
    Surrogate key System-generated identifier. Auto-increment id

    B. Relational Integrity Constraints:

    Constraint Rule
    Domain constraint Column values must belong to the declared domain.
    Entity integrity Primary key cannot be null.
    Referential integrity Foreign key must match an existing PK or be null.
    Key constraint Primary key must be unique.
  5. Advantages:
    • Simple and mathematical: Based on set theory and first-order logic.
    • Standard query language: SQL.
    • Data independence: Logical view separated from storage.
    • Integrity enforcement: Keys and constraints.
    • Optimisable: Query optimisers use relational algebra.
    • Mature tooling: Broad ecosystem of tools, ORMs, backups.
  6. Disadvantages:
    • Impedance mismatch: Objects in code vs rows in tables.
    • Scaling: Vertical scaling is limited.
    • Schema rigidity: Adding columns to huge tables is slow.
    • Complex joins: Many-to-many joins can be expensive.
    • Not ideal for all data: Graphs, documents, timeseries fit other models better.
  7. Characteristics:
    • Relations are unordered sets of tuples.
    • Attribute order is irrelevant.
    • Atomic values: First normal form — no repeating groups.
    • Declarative constraints: Keys, CHECK, NOT NULL, UNIQUE.
    • Relational algebra: Selection, projection, join, union, etc.
  8. Diagram: Key relationships between two tables
        Department                       Student
        ┌──────────┬──────────────┐      ┌─────────┬────────┬───────────┬──────────┐
        │ dept_id  │ dept_name    │◄─────│ dept_id │  FK    │           │          │
        │ (PK)     │              │      │ student_id (PK)    │  name     │  email   │
        └──────────┴──────────────┘      └─────────┴────────┴───────────┴──────────┘
                                              │
                                              │  FK student_id
                                              ▼
                                         Enrollment
                                         ┌───────────┬───────────┬────────┐
                                         │ student_id│ course_id │ grade  │
                                         │ (PK part) │ (PK part) │        │
                                         └───────────┴───────────┴────────┘
    
        Legend:
          PK = Primary key
          FK = Foreign key  (enforces referential integrity)
  9. Conclusion: The relational model's simplicity is its power. Keys give rows identity and connect tables, allowing complex data to be represented without duplication. Integrity constraints keep the data trustworthy. SQL is the standard language to work with relations. Understanding keys and constraints is essential before designing or querying real databases — nearly every bug in database-driven apps traces back to a mistake in keys or constraints.
  10. Exercise:
    1. Define each key type with an example from a Student table.
    2. Write DDL for a Department and Employee tables with PK/FK.
    3. Explain referential integrity with an example of a violation.
    4. Convert an ER design of Library (Book, Member, Loan) into tables with keys.
    5. Show how a composite key is used in an Enrollment table.

हिंदी (सरल)

  1. समस्या: Conceptual design (ER) को concrete, mathematical foundation चाहिए ताकि DBMS integrity enforce कर सके, queries optimise कर सके और consistent rules के साथ data manipulation दे सके। Designers को rows को uniquely identify करने और related tables को duplicate data के बिना जोड़ने के साफ तरीके चाहिए।
  2. परिभाषा: Relational model data को relations (tables) के set के रूप में represent करता है। हर relation का एक schema (columns with domains) होता है और उसमें tuples (rows) होते हैं। यह model set theory पर आधारित है। Relational databases को SQL से query करते हैं। Keys (super, candidate, primary, foreign, composite) identity और tables के बीच relationships देते हैं।
  3. उदाहरण: Keys के साथ schema:
        Student ( student_id PK, name, email, dept_id FK )
        Department ( dept_id PK, dept_name )
        Enrollment ( student_id FK, course_id FK, grade,
                     PRIMARY KEY (student_id, course_id) )
    
        Sample row:
        Student(101, 'अमित', 'a@x.com', 3)
          └─ student_id primary key है
          └─ dept_id Department(dept_id) को refer करता है
  4. प्रकार:

    A. Keys के प्रकार:

    Key विवरण उदाहरण
    Super key ऐसा attributes का set जो tuple को uniquely identify करे। {student_id, email}
    Candidate key Minimal super key। {student_id} या {email}
    Primary key (PK) चुनी हुई candidate key; unique + not null। student_id
    Alternate key वे candidate keys जो PK नहीं चुनी गईं। email
    Foreign key (FK) दूसरी table की PK को refer करने वाले attributes। Student में dept_id
    Composite key दो या ज़्यादा attributes से बनी key। (student_id, course_id)
    Surrogate key System-generated identifier। Auto-increment id

    B. Relational Integrity Constraints:

    Constraint Rule
    Domain constraint Column values घोषित domain की हों।
    Entity integrity Primary key null नहीं हो सकती।
    Referential integrity Foreign key किसी existing PK से match करे या null हो।
    Key constraint Primary key unique होनी चाहिए।
  5. लाभ:
    • Simple और mathematical: Set theory और first-order logic पर आधारित।
    • Standard query language: SQL।
    • Data independence: Logical view storage से अलग।
    • Integrity enforcement: Keys और constraints।
    • Optimisable: Query optimisers relational algebra use करते हैं।
    • Mature tooling: Tools, ORMs, backups का बड़ा ecosystem।
  6. नुकसान:
    • Impedance mismatch: Code में objects बनाम tables में rows।
    • Scaling: Vertical scaling limited।
    • Schema rigidity: बड़ी tables में column जोड़ना slow।
    • Complex joins: कई-to-कई joins महँगे।
    • हर data के लिए ideal नहीं: Graphs, documents, timeseries दूसरे models में बेहतर fit।
  7. विशेषताएँ:
    • Relations unordered sets of tuples हैं।
    • Attribute order irrelevant।
    • Atomic values: First normal form — repeating groups नहीं।
    • Declarative constraints: Keys, CHECK, NOT NULL, UNIQUE।
    • Relational algebra: Selection, projection, join, union, आदि।
  8. आरेख: दो tables के बीच key relationships
        Department                       Student
        ┌──────────┬──────────────┐      ┌─────────┬────────┬───────────┬──────────┐
        │ dept_id  │ dept_name    │◄─────│ dept_id │  FK    │           │          │
        │ (PK)     │              │      │ student_id (PK)    │  name     │  email   │
        └──────────┴──────────────┘      └─────────┴────────┴───────────┴──────────┘
                                              │
                                              │  FK student_id
                                              ▼
                                         Enrollment
                                         ┌───────────┬───────────┬────────┐
                                         │ student_id│ course_id │ grade  │
                                         │ (PK part) │ (PK part) │        │
                                         └───────────┴───────────┴────────┘
    
        Legend:
          PK = Primary key
          FK = Foreign key  (referential integrity enforce करता है)
  9. निष्कर्ष: Relational model की simplicity ही इसकी ताकत है। Keys rows को identity देती हैं और tables जोड़ती हैं, जिससे complex data बिना duplication के represent होता है। Integrity constraints data को trustworthy रखते हैं। SQL relations के साथ काम करने की standard language है। असली databases design या query करने से पहले keys और constraints समझना ज़रूरी है — database-driven apps में लगभग हर bug keys या constraints की गलती से आता है।
  10. अभ्यास:
    1. Student table से हर key type को उदाहरण के साथ define कीजिए।
    2. Department और Employee tables के लिए PK/FK सहित DDL लिखिए।
    3. Referential integrity violation के उदाहरण के साथ समझाइए।
    4. Library (Book, Member, Loan) के ER design को keys वाली tables में बदलिए।
    5. Enrollment table में composite key का उपयोग दिखाइए।

5. Normalization (1NF to BCNF)

English

  1. Problem: Poorly designed tables create insertion anomalies (cannot add data without unrelated data), update anomalies (same fact in many rows must be updated everywhere), and deletion anomalies (deleting one fact accidentally removes another). These problems come from mixing different kinds of facts in the same table and from functional dependencies that are not respected.
  2. Definition: Normalization is a systematic process of organizing columns and tables to minimise redundancy and dependency by splitting large tables into smaller ones using functional dependencies and keys. The classic normal forms are 1NF, 2NF, 3NF, BCNF (and beyond: 4NF, 5NF).
  3. Example: Un-normalised →
        StudentCourse(student_id, name, course_id, course_name, instructor)
    
        Problem: instructor depends on course, not student.
        Update instructor for a course → many rows must change.
    
        After 3NF:
        Student(student_id PK, name)
        Course(course_id PK, course_name, instructor)
        Enrollment(student_id FK, course_id FK, PK(student_id, course_id))
  4. Types:
    Normal Form Rule Removes
    1NF All attributes atomic; no repeating groups. Multivalued attributes.
    2NF 1NF + no partial dependency on composite key. Partial dependency.
    3NF 2NF + no transitive dependency of non-key on non-key. Transitive dependency.
    BCNF Every determinant is a candidate key. Remaining redundancy from overlapping candidate keys.
    4NF BCNF + no multivalued dependency. Independent multivalued facts.
    5NF No join dependency (project-join normal form). Certain join dependencies.
  5. Advantages:
    • Reduces redundancy: Same fact stored once.
    • Prevents anomalies: Insert, update, delete are consistent.
    • Improves data integrity: Constraints enforceable.
    • Better storage: Smaller tables, better caching.
    • Simpler queries: Smaller tables are easier to reason about.
  6. Disadvantages:
    • More tables: Requires more joins.
    • Query complexity: Simple business questions need many joins.
    • Performance: Many joins can slow reads.
    • Over-normalization: Too fine-grained hurts usability.
    • Denormalization tradeoff: Sometimes intentionally undone for speed.
  7. Characteristics:
    • Based on functional dependencies: X → Y.
    • Decomposition: Lossless join, dependency preserving.
    • Each normal form is stricter: 3NF implies 2NF implies 1NF.
    • BCNF sometimes trades dependency preservation for less redundancy.
    • Denormalization is a deliberate, measured step for reporting or performance.
  8. Diagram: Normalization progression
        Un-normalised Table
          │
          ▼  (remove repeating groups)
        1NF
          │
          ▼  (remove partial dependency on composite key)
        2NF
          │
          ▼  (remove transitive dependency: non-key → non-key)
        3NF
          │
          ▼  (every determinant is a candidate key)
        BCNF
          │
          ▼  (remove multivalued dependency)
        4NF
          │
          ▼  (remove join dependency)
        5NF
  9. Conclusion: Normalization is the discipline that keeps a schema healthy as it grows. The goal is not "highest normal form" but "correct tradeoff" between integrity and performance. In practice, most OLTP systems aim for 3NF or BCNF. Reporting and analytics often use deliberate denormalization (star, snowflake schemas) to speed up complex queries. Learn the normal forms — then apply judgment about when to go further and when to stop.
  10. Exercise:
    1. Given an un-normalised Sales table, convert it to 1NF, then 2NF, then 3NF.
    2. Explain the difference between partial and transitive dependency with an example.
    3. Show a relation that is in 3NF but not BCNF.
    4. List the anomalies a bad schema can cause with a real example.
    5. Describe when you would intentionally denormalize a table.

हिंदी (सरल)

  1. समस्या: खराब design वाली tables से insertion anomalies (असंबंधित data के बिना data जोड़ नहीं सकते), update anomalies (एक ही fact कई rows में, हर जगह update करना पड़े) और deletion anomalies (एक fact delete करते ही दूसरा भी चला जाए) बनती हैं। ये समस्याएँ एक ही table में अलग-अलग तरह के facts मिलाने और functional dependencies का पालन न करने से आती हैं।
  2. परिभाषा: Normalization columns और tables को व्यवस्थित करने की systematic प्रक्रिया है जिससे redundancy और dependency कम हो, बड़ी tables को functional dependencies और keys के आधार पर छोटी tables में तोड़कर। Classic normal forms: 1NF, 2NF, 3NF, BCNF (और आगे: 4NF, 5NF)।
  3. उदाहरण: Un-normalised →
        StudentCourse(student_id, name, course_id, course_name, instructor)
    
        समस्या: instructor course पर depend करता है, student पर नहीं।
        किसी course का instructor update करने पर कई rows बदलनी पड़ेंगी।
    
        3NF के बाद:
        Student(student_id PK, name)
        Course(course_id PK, course_name, instructor)
        Enrollment(student_id FK, course_id FK, PK(student_id, course_id))
  4. प्रकार:
    Normal Form Rule क्या हटाता है
    1NF सभी attributes atomic; repeating groups नहीं। Multivalued attributes।
    2NF 1NF + composite key पर partial dependency नहीं। Partial dependency।
    3NF 2NF + non-key का non-key पर transitive dependency नहीं। Transitive dependency।
    BCNF हर determinant एक candidate key हो। Overlapping candidate keys से बची redundancy।
    4NF BCNF + multivalued dependency नहीं। Independent multivalued facts।
    5NF Join dependency नहीं (project-join normal form)। कुछ join dependencies।
  5. लाभ:
    • Redundancy कम: एक fact एक बार।
    • Anomalies रुकती हैं: Insert, update, delete consistent।
    • Data integrity बेहतर: Constraints enforce हो सकते हैं।
    • बेहतर storage: छोटी tables, बेहतर caching।
    • Simpler queries: छोटी tables समझने में आसान।
  6. नुकसान:
    • ज़्यादा tables: ज़्यादा joins।
    • Query complexity: साधारण सवालों के लिए भी कई joins।
    • Performance: बहुत joins reads धीमा कर सकते हैं।
    • Over-normalization: बहुत fine-grained usability खराब करता है।
    • Denormalization tradeoff: कभी-कभी speed के लिए जानबूझकर undo।
  7. विशेषताएँ:
    • Functional dependencies पर आधारित: X → Y।
    • Decomposition: Lossless join, dependency preserving।
    • हर normal form सख्त: 3NF में 2NF, 2NF में 1NF implicit।
    • BCNF कभी-कभी dependency preservation trade करता है कम redundancy के लिए।
    • Denormalization एक deliberate, measured step है reporting या performance के लिए।
  8. आरेख: Normalization progression
        Un-normalised Table
          │
          ▼  (repeating groups हटाएँ)
        1NF
          │
          ▼  (composite key पर partial dependency हटाएँ)
        2NF
          │
          ▼  (transitive dependency हटाएँ: non-key → non-key)
        3NF
          │
          ▼  (हर determinant candidate key हो)
        BCNF
          │
          ▼  (multivalued dependency हटाएँ)
        4NF
          │
          ▼  (join dependency हटाएँ)
        5NF
  9. निष्कर्ष: Normalization वह discipline है जो schema को बढ़ते हुए स्वस्थ रखती है। लक्ष्य "highest normal form" नहीं, बल्कि integrity और performance के बीच "correct tradeoff" है। व्यवहार में ज़्यादातर OLTP systems 3NF या BCNF पर लक्ष्य रखते हैं। Reporting और analytics अक्सर deliberate denormalization (star, snowflake schemas) use करते हैं जटिल queries तेज़ करने के लिए। Normal forms सीखें — फिर judgment लगाएँ कि कब आगे बढ़ें और कब रुकें।
  10. अभ्यास:
    1. Un-normalised Sales table को 1NF, फिर 2NF, फिर 3NF में बदलिए।
    2. Partial और transitive dependency का फर्क उदाहरण के साथ समझाइए।
    3. एक relation दिखाइए जो 3NF में है पर BCNF में नहीं।
    4. खराब schema से होने वाली anomalies list कीजिए असली उदाहरण के साथ।
    5. बताइए कब आप जानबूझकर किसी table को denormalize करेंगे।

6. SQL – DDL Commands (CREATE, ALTER, DROP, TRUNCATE)

English

  1. Problem: Before any data can be stored or queried, the database needs to know the shape of the data: tables, columns, types, constraints, and relationships. There must be a way to define, change, and remove these structures as requirements evolve, and to keep this definition consistent across environments (dev, test, production).
  2. Definition: DDL (Data Definition Language) is the subset of SQL that defines and modifies the structure of database objects. Key DDL statements: CREATE, ALTER, DROP, TRUNCATE, RENAME. DDL changes are typically auto-committed by the DBMS.
  3. Example: Create, alter, and drop a table:
    -- CREATE TABLE
    CREATE TABLE Department (
      dept_id    INT PRIMARY KEY,
      dept_name  VARCHAR(50) NOT NULL UNIQUE
    );
    
    CREATE TABLE Student (
      student_id  INT PRIMARY KEY,
      name        VARCHAR(100) NOT NULL,
      email       VARCHAR(100) UNIQUE,
      age         INT CHECK (age >= 16),
      dept_id     INT,
      FOREIGN KEY (dept_id) REFERENCES Department(dept_id)
    );
    
    -- ALTER TABLE
    ALTER TABLE Student ADD COLUMN phone VARCHAR(15);
    ALTER TABLE Student MODIFY phone VARCHAR(20);
    ALTER TABLE Student DROP COLUMN phone;
    
    -- TRUNCATE vs DROP
    TRUNCATE TABLE Student;  -- removes all rows, keeps structure
    DROP TABLE Student;      -- removes table and structure
  4. Types:
    Command Purpose Rollback?
    CREATE Create table, view, index, schema, database. Implicit commit.
    ALTER Add/modify/drop columns, constraints. Implicit commit.
    DROP Delete object and structure. Implicit commit.
    TRUNCATE Delete all rows, keep structure; faster than DELETE. Implicit commit.
    RENAME Rename table or column. Implicit commit.

    Common column types and constraints:

    • Types: INT, VARCHAR, CHAR, TEXT, DATE, TIMESTAMP, DECIMAL, BOOLEAN.
    • Constraints: PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, DEFAULT.
  5. Advantages:
    • Declarative schema: Easy to describe structure and rules.
    • Portable: DDL syntax is similar across DBMSs.
    • Enforces integrity: Constraints are enforced by the DBMS.
    • Versionable: DDL can be stored in migration scripts.
    • Fast: TRUNCATE removes all rows efficiently.
  6. Disadvantages:
    • Auto-commit: DROP, TRUNCATE cannot be rolled back easily.
    • Locks: ALTER on huge tables can lock long.
    • Vendor differences: Some types and syntax differ.
    • Schema rigidity: Changing schema on live data is risky.
    • Requires planning: Wrong decisions (types, keys) are costly later.
  7. Characteristics:
    • Auto-commit: DDL statements commit immediately in most DBMSs.
    • Metadata update: DDL updates the system catalogue.
    • Locking: Some DDL acquires table-level locks.
    • Idempotency: Use IF EXISTS / IF NOT EXISTS for safe scripts.
    • Order matters: Drop child tables before parent tables (FK).
  8. Diagram: DDL lifecycle
        CREATE → table exists (structure defined)
            │
            ▼
        ALTER  → add / change / drop columns and constraints
            │
            ▼
        TRUNCATE → remove all rows (structure remains)
            │
            ▼
        DROP → remove table and structure entirely
    
        Dependencies:
          Parent (Department)  ← referenced by FK
          Child  (Student)     → must DROP first
  9. Conclusion: DDL is the first step of building any database. A good schema carefully chooses types, constraints, and keys, because they are hard to change later on large tables. Prefer writing idempotent migration scripts (with IF EXISTS, IF NOT EXISTS), and version them in your repository. Understanding which operations auto-commit (DROP, TRUNCATE) protects you from irreversible mistakes.
  10. Exercise:
    1. Write DDL for Department and Student tables with PK/FK.
    2. Add a CHECK constraint that age must be between 16 and 100.
    3. Alter the Student table to add an enrolled_on DATE column.
    4. Demonstrate the difference between TRUNCATE and DROP with the same table.
    5. Write a safe migration script using IF NOT EXISTS.

हिंदी (सरल)

  1. समस्या: कोई data store या query करने से पहले database को data का आकार पता होना चाहिए: tables, columns, types, constraints और relationships। ज़रूरत बदलने पर यह structure define, बदल और हटाने का तरीका चाहिए, और यह definition सभी environments (dev, test, production) में consistent रहे।
  2. परिभाषा: DDL (Data Definition Language) SQL का वह हिस्सा है जो database objects की structure define और modify करता है। प्रमुख DDL statements: CREATE, ALTER, DROP, TRUNCATE, RENAME। DDL changes आमतौर पर DBMS auto-commit करता है।
  3. उदाहरण: Table create, alter और drop:
    -- CREATE TABLE
    CREATE TABLE Department (
      dept_id    INT PRIMARY KEY,
      dept_name  VARCHAR(50) NOT NULL UNIQUE
    );
    
    CREATE TABLE Student (
      student_id  INT PRIMARY KEY,
      name        VARCHAR(100) NOT NULL,
      email       VARCHAR(100) UNIQUE,
      age         INT CHECK (age >= 16),
      dept_id     INT,
      FOREIGN KEY (dept_id) REFERENCES Department(dept_id)
    );
    
    -- ALTER TABLE
    ALTER TABLE Student ADD COLUMN phone VARCHAR(15);
    ALTER TABLE Student MODIFY phone VARCHAR(20);
    ALTER TABLE Student DROP COLUMN phone;
    
    -- TRUNCATE vs DROP
    TRUNCATE TABLE Student;  -- सभी rows हटीं, structure बनी
    DROP TABLE Student;      -- table और structure दोनों गए
  4. प्रकार:
    Command उद्देश्य Rollback?
    CREATE Table, view, index, schema, database बनाएँ। Implicit commit।
    ALTER Columns/constraints जोड़ें, बदलें, हटाएँ। Implicit commit।
    DROP Object और structure delete। Implicit commit।
    TRUNCATE सभी rows delete, structure रहे; DELETE से तेज़। Implicit commit।
    RENAME Table या column का नाम बदलें। Implicit commit।

    सामान्य column types और constraints:

    • Types: INT, VARCHAR, CHAR, TEXT, DATE, TIMESTAMP, DECIMAL, BOOLEAN।
    • Constraints: PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, DEFAULT।
  5. लाभ:
    • Declarative schema: Structure और rules describe करना आसान।
    • Portable: DDL syntax DBMSs में समान।
    • Integrity enforce: Constraints DBMS enforce करता है।
    • Versionable: DDL migration scripts में रख सकते हैं।
    • Fast: TRUNCATE सभी rows तेज़ी से हटाता है।
  6. नुकसान:
    • Auto-commit: DROP, TRUNCATE आसानी से rollback नहीं।
    • Locks: बड़ी tables पर ALTER लंबा lock कर सकता है।
    • Vendor differences: कुछ types और syntax अलग।
    • Schema rigidity: Live data पर schema बदलना जोखिम।
    • Planning ज़रूरी: गलत decisions (types, keys) बाद में महँगे।
  7. विशेषताएँ:
    • Auto-commit: ज़्यादातर DBMSs में DDL तुरंत commit।
    • Metadata update: DDL system catalogue update करता है।
    • Locking: कुछ DDL table-level locks लेता है।
    • Idempotency: Safe scripts के लिए IF EXISTS / IF NOT EXISTS।
    • Order मायने रखता है: Child tables को parent से पहले drop करें (FK)।
  8. आरेख: DDL lifecycle
        CREATE → table बनी (structure defined)
            │
            ▼
        ALTER  → columns और constraints add/change/drop
            │
            ▼
        TRUNCATE → सभी rows हटीं (structure रही)
            │
            ▼
        DROP → table और structure पूरी तरह गए
    
        Dependencies:
          Parent (Department)  ← FK से referenced
          Child  (Student)     → पहले DROP
  9. निष्कर्ष: DDL किसी भी database बनाने का पहला कदम है। अच्छा schema types, constraints और keys सावधानी से चुनता है, क्योंकि बड़ी tables पर उन्हें बदलना बाद में मुश्किल होता है। Idempotent migration scripts लिखें (IF EXISTS, IF NOT EXISTS के साथ) और repository में version करें। यह समझना कि कौन से operations auto-commit करते हैं (DROP, TRUNCATE) आपको irreversible गलतियों से बचाता है।
  10. अभ्यास:
    1. PK/FK सहित Department और Student tables के लिए DDL लिखिए।
    2. CHECK constraint जोड़िए कि age 16 से 100 के बीच हो।
    3. Student table में enrolled_on DATE column जोड़ने के लिए ALTER लिखिए।
    4. एक ही table पर TRUNCATE और DROP का फर्क demonstrate कीजिए।
    5. IF NOT EXISTS के साथ एक safe migration script लिखिए।

7. SQL – DML (INSERT, UPDATE, DELETE)

English

  1. Problem: Once tables exist, we need to put data in them, change it as things evolve, and remove data that is no longer needed — all while respecting constraints and preserving consistency. Directly editing files is impossible; a safe, transactional way to modify data is required.
  2. Definition: DML (Data Manipulation Language) is the subset of SQL used to insert, update, delete, and merge data in tables. The core statements are INSERT, UPDATE, DELETE, and MERGE. DML changes are transactional and can be rolled back before commit.
  3. Example: Insert, update, and delete rows:
    -- INSERT
    INSERT INTO Department (dept_id, dept_name)
    VALUES (1, 'Computer Science'), (2, 'Mathematics');
    
    INSERT INTO Student (student_id, name, email, age, dept_id)
    VALUES (101, 'Amit', 'a@x.com', 20, 1);
    
    -- UPDATE
    UPDATE Student
    SET age = age + 1
    WHERE dept_id = 1;
    
    UPDATE Student
    SET email = 'amit.new@x.com'
    WHERE student_id = 101;
    
    -- DELETE
    DELETE FROM Student WHERE student_id = 101;
    
    -- Transaction (rollback-safe)
    BEGIN;
    UPDATE Student SET age = 99 WHERE student_id = 101;
    ROLLBACK;   -- age will not actually change
  4. Types:
    Statement Purpose Notes
    INSERT Add new rows. Can insert single or multiple rows; can insert from SELECT.
    UPDATE Modify existing rows. Always use a WHERE clause to limit scope.
    DELETE Remove rows. Always use WHERE; TRUNCATE is faster for all rows.
    MERGE / UPSERT Insert or update in one statement. Vendor-specific syntax (MERGE, ON CONFLICT, ON DUPLICATE KEY).
  5. Advantages:
    • Simple syntax: Easy to learn and read.
    • Set-based: One statement can affect many rows.
    • Transactional: Can be rolled back before commit.
    • Constraints enforced: DBMS prevents bad data.
    • Auditing possible: Triggers and change logs.
  6. Disadvantages:
    • Danger of missing WHERE: UPDATE or DELETE without WHERE affects all rows.
    • Large transactions: Lock many rows and consume log space.
    • Silent rowcount: "0 rows affected" is not an error.
    • Referential integrity errors: Delete may fail if FK references exist.
    • Bulk inserts: Row-by-row inserts are slow — use bulk forms.
  7. Characteristics:
    • Transactional: Rollback possible before COMMIT.
    • Rowcount returned: Number of affected rows.
    • Triggers fire: BEFORE / AFTER triggers run.
    • Cascading rules: ON DELETE CASCADE affects child rows.
    • Atomic within a statement: Even a multi-row update succeeds or fails as a whole.
  8. Diagram: DML change and transaction lifecycle
        BEGIN
          │
          ▼
        INSERT / UPDATE / DELETE
          │  (changes visible to this session)
          ▼
        More changes …
          │
          ├── COMMIT   → changes permanent, visible to all
          │
          └── ROLLBACK → changes undone
    
        Referential integrity:
    
          Parent (Department) ── FK ── Child (Student)
          DELETE parent → fails (or CASCADE deletes child rows
                                  depending on FK rule)
  9. Conclusion: DML is what brings data to life. The safest habits are: always write a WHERE clause, run UPDATE/DELETE inside a transaction, verify rowcounts, and test on a copy before touching production. Keep transactions short to avoid locking. Use bulk inserts and MERGE/UPSERT for performance. Remember that constraints and foreign keys protect you — embrace them.
  10. Exercise:
    1. Insert 5 students into a Student table with varied ages and departments.
    2. Update all students in one department to a new department id, inside a transaction.
    3. Delete a department and demonstrate the referential integrity error.
    4. Demonstrate rollback by updating a row, then rolling back.
    5. Write an INSERT ... SELECT to copy rows from one table to another.

हिंदी (सरल)

  1. समस्या: Tables बन जाने के बाद उनमें data डालना, बदलना और हटाना होता है — constraints का सम्मान करते हुए और consistency बनाए रखते हुए। Files को सीधे edit करना असंभव है; data बदलने का safe, transactional तरीका चाहिए।
  2. परिभाषा: DML (Data Manipulation Language) SQL का वह हिस्सा है जो tables में data insert, update, delete और merge करता है। मुख्य statements: INSERT, UPDATE, DELETE, MERGE। DML changes transactional होते हैं और commit से पहले rollback हो सकते हैं।
  3. उदाहरण: Rows insert, update और delete:
    -- INSERT
    INSERT INTO Department (dept_id, dept_name)
    VALUES (1, 'Computer Science'), (2, 'Mathematics');
    
    INSERT INTO Student (student_id, name, email, age, dept_id)
    VALUES (101, 'अमित', 'a@x.com', 20, 1);
    
    -- UPDATE
    UPDATE Student
    SET age = age + 1
    WHERE dept_id = 1;
    
    UPDATE Student
    SET email = 'amit.new@x.com'
    WHERE student_id = 101;
    
    -- DELETE
    DELETE FROM Student WHERE student_id = 101;
    
    -- Transaction (rollback-safe)
    BEGIN;
    UPDATE Student SET age = 99 WHERE student_id = 101;
    ROLLBACK;   -- age असल में नहीं बदलेगी
  4. प्रकार:
    Statement उद्देश्य Notes
    INSERT नई rows जोड़ें। Single/multiple rows; SELECT से भी insert।
    UPDATE मौजूदा rows बदलें। हमेशा WHERE से scope सीमित करें।
    DELETE Rows हटाएँ। हमेशा WHERE; सभी rows के लिए TRUNCATE तेज़।
    MERGE / UPSERT एक statement में insert या update। Vendor-specific syntax (MERGE, ON CONFLICT, ON DUPLICATE KEY)।
  5. लाभ:
    • Simple syntax: सीखना और पढ़ना आसान।
    • Set-based: एक statement कई rows affect करती है।
    • Transactional: COMMIT से पहले rollback।
    • Constraints enforce: DBMS bad data रोकता है।
    • Auditing possible: Triggers और change logs।
  6. नुकसान:
    • WHERE भूलने का खतरा: बिना WHERE UPDATE या DELETE सभी rows पर।
    • बड़े transactions: कई rows lock और log space।
    • Silent rowcount: "0 rows affected" error नहीं है।
    • Referential integrity errors: Delete fail हो सकता है अगर FK references हों।
    • Bulk inserts: Row-by-row slow — bulk forms use करें।
  7. विशेषताएँ:
    • Transactional: COMMIT से पहले rollback possible।
    • Rowcount return: Affected rows की गिनती।
    • Triggers fire: BEFORE / AFTER triggers चलते हैं।
    • Cascading rules: ON DELETE CASCADE child rows affect करता है।
    • Atomic within statement: Multi-row update पूरा success या पूरा fail।
  8. आरेख: DML change और transaction lifecycle
        BEGIN
          │
          ▼
        INSERT / UPDATE / DELETE
          │  (changes सिर्फ इस session को दिखते हैं)
          ▼
        और changes …
          │
          ├── COMMIT   → changes permanent, सबको दिखते हैं
          │
          └── ROLLBACK → changes undone
    
        Referential integrity:
    
          Parent (Department) ── FK ── Child (Student)
          Parent DELETE → fail (या CASCADE से child rows
                               delete, FK rule पर निर्भर)
  9. निष्कर्ष: DML data को जीवन देता है। सबसे सुरक्षित आदतें: हमेशा WHERE लिखें, UPDATE/DELETE transaction में चलाएँ, rowcounts verify करें, और production से पहले copy पर test करें। Locking से बचने के लिए transactions छोटी रखें। Performance के लिए bulk inserts और MERGE/UPSERT use करें। याद रखें constraints और foreign keys आपकी रक्षा करते हैं — उन्हें अपनाएँ।
  10. अभ्यास:
    1. Student table में अलग-अलग ages और departments वाले 5 students insert कीजिए।
    2. एक department के सभी students को नए department id में update कीजिए, transaction में।
    3. एक department delete करके referential integrity error demonstrate कीजिए।
    4. एक row update करके, फिर rollback करके rollback demonstrate कीजिए।
    5. एक table से दूसरी में rows copy करने के लिए INSERT ... SELECT लिखिए।

8. SQL – DQL (SELECT, Joins, Subqueries)

English

  1. Problem: Data is useless unless we can ask precise questions about it: which students passed, which products sold best last month, which employees report to which manager. We need a powerful, declarative way to filter, combine, aggregate, and reshape data across many tables without writing procedural code.
  2. Definition: DQL (Data Query Language) is the subset of SQL for querying data, centred on the SELECT statement. It supports filtering (WHERE), sorting (ORDER BY), grouping (GROUP BY), filtering groups (HAVING), joining tables (JOIN), subqueries, set operations, and window functions.
  3. Example: Joins, aggregates, and a subquery:
    -- INNER JOIN with aggregate
    SELECT d.dept_name, COUNT(*) AS students
    FROM Student s
    JOIN Department d ON s.dept_id = d.dept_id
    GROUP BY d.dept_name
    HAVING COUNT(*) > 5
    ORDER BY students DESC;
    
    -- Subquery: students above average age
    SELECT name, age
    FROM Student
    WHERE age > (SELECT AVG(age) FROM Student);
    
    -- LEFT JOIN: departments with no students
    SELECT d.dept_name
    FROM Department d
    LEFT JOIN Student s ON s.dept_id = d.dept_id
    WHERE s.student_id IS NULL;
  4. Types:

    A. Joins:

    Join Returns
    INNER JOIN Only matching rows in both tables.
    LEFT (OUTER) JOIN All rows from left + matches from right.
    RIGHT (OUTER) JOIN All rows from right + matches from left.
    FULL OUTER JOIN All rows from both sides.
    CROSS JOIN Cartesian product.
    SELF JOIN Table joined with itself.

    B. Other DQL concepts:

    • Aggregations: COUNT, SUM, AVG, MIN, MAX.
    • Subqueries: Scalar, IN, EXISTS, correlated.
    • Set operators: UNION, INTERSECT, EXCEPT.
    • Window functions: ROW_NUMBER, RANK, SUM() OVER.
    • CTEs: WITH clause for readable queries.
  5. Advantages:
    • Declarative: Say what you want, not how.
    • Powerful: Complex analytics in one query.
    • Optimisable: The DBMS chooses efficient plans.
    • Portable: Similar syntax across DBMSs.
    • Analytic support: Aggregations and window functions.
  6. Disadvantages:
    • Complex queries are hard to read: Deeply nested subqueries.
    • Performance pitfalls: Missing indexes cause slow joins.
    • NULL semantics: Tri-valued logic surprises beginners.
    • Dialect differences: Window functions and LIMIT vary.
    • Cartesian products: Missing join conditions blow up results.
  7. Characteristics:
    • Logical order of execution: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
    • NULL handling: = NULL never matches; use IS NULL.
    • Deterministic output: Only with ORDER BY.
    • Set-based thinking: Operations apply to whole sets of rows.
    • Optimiser freedom: Rewrites queries for performance.
  8. Diagram: Logical query processing order
        Logical order of execution:
    
          1. FROM / JOIN         → build the working set
          2. WHERE               → filter rows
          3. GROUP BY            → collapse into groups
          4. HAVING              → filter groups
          5. SELECT              → compute output columns
          6. DISTINCT            → remove duplicates
          7. ORDER BY            → sort
          8. LIMIT / OFFSET      → paginate
    
        Note: SELECT comes AFTER GROUP BY logically, even
        though we type it near the beginning.
  9. Conclusion: SELECT is the workhorse of SQL. Mastering joins, aggregates, subqueries, and window functions unlocks the full power of a relational database. Prefer explicit JOIN syntax over comma joins, always qualify column names when joining, watch out for NULLs, and use CTEs for readability. Understand the logical order of execution — many confusing bugs come from not knowing WHERE runs before SELECT. Add indexes to support the joins and filters you actually use.
  10. Exercise:
    1. List all students with their department names using INNER JOIN.
    2. Find departments with zero students using LEFT JOIN.
    3. Get the average age per department with GROUP BY and HAVING.
    4. Write a subquery that finds students older than the average.
    5. Use a CTE and a window function to rank students by age.

हिंदी (सरल)

  1. समस्या: Data तब तक बेकार है जब तक हम उससे सटीक सवाल न पूछ सकें: कौन से students pass हुए, पिछले महीने कौन से products सबसे ज़्यादा बिके, कौन से employees किस manager को report करते हैं। हमें filter, combine, aggregate और reshape करने का powerful, declarative तरीका चाहिए, बिना procedural code लिखे।
  2. परिभाषा: DQL (Data Query Language) SQL का वह हिस्सा है जो data query करता है, मुख्य रूप से SELECT statement। यह filtering (WHERE), sorting (ORDER BY), grouping (GROUP BY), groups filter (HAVING), tables join (JOIN), subqueries, set operations और window functions support करता है।
  3. उदाहरण: Joins, aggregates और subquery:
    -- INNER JOIN with aggregate
    SELECT d.dept_name, COUNT(*) AS students
    FROM Student s
    JOIN Department d ON s.dept_id = d.dept_id
    GROUP BY d.dept_name
    HAVING COUNT(*) > 5
    ORDER BY students DESC;
    
    -- Subquery: average age से बड़े students
    SELECT name, age
    FROM Student
    WHERE age > (SELECT AVG(age) FROM Student);
    
    -- LEFT JOIN: बिना students वाले departments
    SELECT d.dept_name
    FROM Department d
    LEFT JOIN Student s ON s.dept_id = d.dept_id
    WHERE s.student_id IS NULL;
  4. प्रकार:

    A. Joins:

    Join क्या return करता है
    INNER JOIN सिर्फ दोनों tables की matching rows।
    LEFT (OUTER) JOIN Left की सभी rows + right की matches।
    RIGHT (OUTER) JOIN Right की सभी rows + left की matches।
    FULL OUTER JOIN दोनों ओर की सभी rows।
    CROSS JOIN Cartesian product।
    SELF JOIN Table का खुद से join।

    B. अन्य DQL concepts:

    • Aggregations: COUNT, SUM, AVG, MIN, MAX।
    • Subqueries: Scalar, IN, EXISTS, correlated।
    • Set operators: UNION, INTERSECT, EXCEPT।
    • Window functions: ROW_NUMBER, RANK, SUM() OVER।
    • CTEs: WITH clause से readable queries।
  5. लाभ:
    • Declarative: क्या चाहिए बताएँ, कैसे नहीं।
    • Powerful: एक query में complex analytics।
    • Optimisable: DBMS efficient plans चुनता है।
    • Portable: DBMSs में syntax समान।
    • Analytic support: Aggregations और window functions।
  6. नुकसान:
    • Complex queries पढ़ना कठिन: गहरे nested subqueries।
    • Performance pitfalls: Missing indexes slow joins।
    • NULL semantics: Tri-valued logic शुरुआती को confuse करती है।
    • Dialect differences: Window functions और LIMIT अलग-अलग।
    • Cartesian products: Join condition भूलने पर result explode।
  7. विशेषताएँ:
    • Logical execution order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT।
    • NULL handling: = NULL कभी match नहीं; IS NULL use करें।
    • Deterministic output: सिर्फ ORDER BY से।
    • Set-based thinking: Operations पूरे row sets पर।
    • Optimiser freedom: Queries performance के लिए rewrite।
  8. आरेख: Logical query processing order
        Logical order of execution:
    
          1. FROM / JOIN         → working set बनाएँ
          2. WHERE               → rows filter
          3. GROUP BY            → groups में collapse
          4. HAVING              → groups filter
          5. SELECT              → output columns compute
          6. DISTINCT            → duplicates हटाएँ
          7. ORDER BY            → sort
          8. LIMIT / OFFSET      → paginate
    
        Note: SELECT logically GROUP BY के बाद आता है,
        हालाँकि type हम शुरू में करते हैं।
  9. निष्कर्ष: SELECT SQL का workhorse है। Joins, aggregates, subqueries और window functions में महारत हासिल करना relational database की पूरी ताकत unlock करता है। Comma joins से explicit JOIN syntax prefer करें, join करते समय हमेशा column names qualify करें, NULLs से सावधान रहें, और readability के लिए CTEs use करें। Logical order of execution समझें — कई confusing bugs इसी से आते हैं कि WHERE SELECT से पहले चलता है। जो joins और filters आप वाकई use करते हैं उनके लिए indexes जोड़ें।
  10. अभ्यास:
    1. INNER JOIN से सभी students और उनके department names list कीजिए।
    2. LEFT JOIN से वे departments ढूँढिए जिनमें कोई student नहीं।
    3. GROUP BY और HAVING से हर department की average age निकालिए।
    4. ऐसा subquery लिखिए जो average से बड़ी age वाले students खोजे।
    5. CTE और window function से students को age पर rank कीजिए।

9. SQL – DCL & TCL Commands (GRANT, REVOKE, COMMIT, ROLLBACK, SAVEPOINT)

English

  1. Problem: Not every user should be able to see or modify every table. We need a way to control who can do what (authorisation). At the same time, DML changes must be safe: we need to group changes into transactions, decide when they become permanent, and have a way to undo them if something goes wrong.
  2. Definition:
    • DCL (Data Control Language): statements that manage permissions — GRANT and REVOKE. Roles group privileges for convenience.
    • TCL (Transaction Control Language): statements that manage transactions — COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION.
  3. Example: Permissions and transactions:
    -- DCL: grant read-only access to a report user
    CREATE ROLE analyst;
    GRANT SELECT ON Student TO analyst;
    GRANT SELECT ON Department TO analyst;
    GRANT analyst TO alice;
    
    -- Later, revoke one privilege
    REVOKE SELECT ON Department FROM analyst;
    
    -- TCL: transaction with savepoint
    BEGIN;
    UPDATE Student SET age = age + 1 WHERE dept_id = 1;
    SAVEPOINT after_update;
    
    DELETE FROM Student WHERE student_id = 999;
    ROLLBACK TO SAVEPOINT after_update;  -- undo only the delete
    COMMIT;                              -- keep the update
  4. Types:

    A. DCL statements:

    Statement Purpose
    GRANT Give privileges (SELECT, INSERT, UPDATE, DELETE, EXECUTE).
    REVOKE Take privileges away.
    CREATE ROLE Group privileges and assign them to users.

    B. TCL statements:

    Statement Purpose
    COMMIT Make changes permanent.
    ROLLBACK Undo changes since last COMMIT or SAVEPOINT.
    SAVEPOINT Mark a point inside a transaction to roll back to.
    SET TRANSACTION Set isolation level, read-only mode, etc.
  5. Advantages:
    • Security: Least-privilege access enforced at the DBMS.
    • Roles: Manage many users consistently.
    • Safety: Transactions let you undo mistakes.
    • Consistency: Multi-statement operations succeed or fail as a unit.
    • Fine-grained control: Savepoints allow partial rollback.
  6. Disadvantages:
    • Complexity: Managing roles and grants across many tables.
    • Privilege creep: Over time, users accumulate privileges.
    • Long transactions: Hold locks and consume log space.
    • Deadlocks: Long transactions are more likely to deadlock.
    • Dialect differences: Role syntax varies (CREATE USER vs CREATE ROLE).
  7. Characteristics:
    • Least privilege: Grant only what is needed.
    • Granularity: Object-level and column-level grants.
    • Auto-commit: DDL and DCL auto-commit; DML does not.
    • Atomicity: Transactions are all-or-nothing.
    • Isolation levels: READ COMMITTED, REPEATABLE READ, SERIALIZABLE.
  8. Diagram: Transaction with savepoints and privileges
        BEGIN
          │
          ▼
        INSERT / UPDATE  ← SAVEPOINT A
          │
          ▼
        DELETE           ← SAVEPOINT B
          │
          ▼
        ROLLBACK TO B    → undo DELETE only
          │
          ▼
        COMMIT           → keep INSERT / UPDATE
    
        DCL example:
    
          User alice
             │
             ▼
          GRANT SELECT ON Student → yes
          REVOKE SELECT ON Student → no longer
  9. Conclusion: DCL and TCL are the safety systems of a database. DCL enforces the principle of least privilege, protecting data from unauthorised access and mistakes. TCL makes DML safe by grouping changes into transactions with clear commit and rollback semantics, and by supporting savepoints for partial recovery. Together they turn a database from a simple data store into a secure, reliable system ready for real-world use.
  10. Exercise:
    1. Create a role analyst with SELECT on Student only.
    2. Grant the role to a user and revoke it. Observe the effect.
    3. Demonstrate COMMIT and ROLLBACK with a simple UPDATE.
    4. Use SAVEPOINT to undo only the second of three DML statements.
    5. Explain how isolation levels affect concurrent transactions.

हिंदी (सरल)

  1. समस्या: हर user को हर table देखने या बदलने का अधिकार नहीं होना चाहिए। कौन क्या कर सकता है, यह control करने का तरीका चाहिए (authorisation)। साथ ही, DML changes safe होने चाहिए: changes को transactions में group करें, तय करें कब permanent हों, और कुछ गलत हो तो undo का तरीका हो।
  2. परिभाषा:
    • DCL (Data Control Language): वे statements जो permissions manage करते हैं — GRANT और REVOKE। Roles privileges को group करते हैं।
    • TCL (Transaction Control Language): वे statements जो transactions manage करते हैं — COMMIT, ROLLBACK, SAVEPOINT, SET TRANSACTION।
  3. उदाहरण: Permissions और transactions:
    -- DCL: read-only access एक report user को
    CREATE ROLE analyst;
    GRANT SELECT ON Student TO analyst;
    GRANT SELECT ON Department TO analyst;
    GRANT analyst TO alice;
    
    -- एक privilege बाद में revoke
    REVOKE SELECT ON Department FROM analyst;
    
    -- TCL: savepoint वाला transaction
    BEGIN;
    UPDATE Student SET age = age + 1 WHERE dept_id = 1;
    SAVEPOINT after_update;
    
    DELETE FROM Student WHERE student_id = 999;
    ROLLBACK TO SAVEPOINT after_update;  -- सिर्फ delete undo
    COMMIT;                              -- update रहेगा
  4. प्रकार:

    A. DCL statements:

    Statement उद्देश्य
    GRANT Privileges देना (SELECT, INSERT, UPDATE, DELETE, EXECUTE)।
    REVOKE Privileges वापस लेना।
    CREATE ROLE Privileges group करके users को assign करना।

    B. TCL statements:

    Statement उद्देश्य
    COMMIT Changes permanent करना।
    ROLLBACK पिछले COMMIT या SAVEPOINT के बाद के changes undo करना।
    SAVEPOINT Transaction के अंदर एक point mark करना जिस पर roll back कर सकें।
    SET TRANSACTION Isolation level, read-only mode आदि set करना।
  5. लाभ:
    • Security: Least-privilege access DBMS पर enforce।
    • Roles: कई users को consistently manage।
    • Safety: Transactions से गलतियाँ undo।
    • Consistency: Multi-statement operations all-or-nothing।
    • Fine-grained control: Savepoints से partial rollback।
  6. नुकसान:
    • Complexity: कई tables पर roles और grants manage करना।
    • Privilege creep: समय के साथ users के privileges बढ़ते हैं।
    • Long transactions: Locks और log space।
    • Deadlocks: Long transactions deadlock के chance बढ़ाते हैं।
    • Dialect differences: Role syntax अलग (CREATE USER vs CREATE ROLE)।
  7. विशेषताएँ:
    • Least privilege: सिर्फ ज़रूरी privileges दें।
    • Granularity: Object-level और column-level grants।
    • Auto-commit: DDL और DCL auto-commit; DML नहीं।
    • Atomicity: Transactions all-or-nothing।
    • Isolation levels: READ COMMITTED, REPEATABLE READ, SERIALIZABLE।
  8. आरेख: Savepoints और privileges वाला transaction
        BEGIN
          │
          ▼
        INSERT / UPDATE  ← SAVEPOINT A
          │
          ▼
        DELETE           ← SAVEPOINT B
          │
          ▼
        ROLLBACK TO B    → सिर्फ DELETE undo
          │
          ▼
        COMMIT           → INSERT / UPDATE रहें
    
        DCL उदाहरण:
    
          User alice
             │
             ▼
          GRANT SELECT ON Student → हाँ
          REVOKE SELECT ON Student → अब नहीं
  9. निष्कर्ष: DCL और TCL database के safety systems हैं। DCL least privilege का सिद्धांत enforce करता है, data को unauthorised access और गलतियों से बचाता है। TCL DML को safe बनाता है — changes को transactions में group करके clear commit और rollback semantics देता है, और partial recovery के लिए savepoints support करता है। दोनों मिलकर database को simple data store से secure, reliable system में बदल देते हैं जो real-world use के लिए तैयार है।
  10. अभ्यास:
    1. एक role analyst बनाइए जिसे सिर्फ Student पर SELECT हो।
    2. Role को user को grant करके revoke कीजिए। असर देखिए।
    3. एक साधारण UPDATE से COMMIT और ROLLBACK demonstrate कीजिए।
    4. SAVEPOINT use करके तीन DML statements में से सिर्फ दूसरी undo कीजिए।
    5. Isolation levels concurrent transactions को कैसे प्रभावित करते हैं समझाइए।

10. SQL – Views, Indexes, Stored Procedures, Triggers

English

  1. Problem: Real applications repeatedly need the same complex query, restricted views of data for security, fast lookups on large tables, and business logic that must run inside the database. Writing the same SQL everywhere leads to duplication, inconsistency, and performance problems. A way to encapsulate and accelerate database logic is needed.
  2. Definition: Advanced SQL objects:
    • View: A stored query that behaves like a virtual table.
    • Index: A data structure (usually B-tree) that speeds up lookups and joins.
    • Stored Procedure / Function: Named, precompiled blocks of SQL logic.
    • Trigger: Code that fires automatically on INSERT/UPDATE/DELETE.
  3. Example: A view, an index, a procedure, and a trigger:
    -- VIEW: hide sensitive columns
    CREATE VIEW StudentPublic AS
    SELECT student_id, name, dept_id
    FROM Student;
    
    -- INDEX: accelerate search by email
    CREATE INDEX idx_student_email ON Student(email);
    
    -- STORED PROCEDURE
    CREATE PROCEDURE PromoteStudents(IN minAge INT)
    BEGIN
      UPDATE Student SET dept_id = 2
      WHERE age >= minAge;
    END;
    
    -- TRIGGER: audit updates
    CREATE TRIGGER trg_student_audit
    AFTER UPDATE ON Student
    FOR EACH ROW
    INSERT INTO StudentAudit(student_id, changed_at)
    VALUES (OLD.student_id, NOW());
  4. Types:

    A. Views:

    • Simple view: One table, no aggregates; usually updatable.
    • Complex view: Joins, aggregates, GROUP BY; usually read-only.
    • Materialized view: Physically stored; needs refresh; fast reads.

    B. Indexes:

    Type Use
    B-tree Default for equality and range.
    Hash Equality only; very fast lookups.
    Bitmap Low-cardinality columns (gender, status).
    Composite Multiple columns; column order matters.
    Partial / filtered Index only a subset of rows.
    Full-text Text search (LIKE '%…%' with language rules).

    C. Stored routines and triggers: Procedures (callable by name), functions (return a value), and triggers (fire on events).

  5. Advantages:
    • Views: Security, simplification, abstraction.
    • Indexes: Massive speedups for reads and joins.
    • Procedures: Reuse, precompilation, encapsulate logic.
    • Triggers: Automatic audits, derived columns, integrity rules.
    • Central logic: Business rules live in one place.
  6. Disadvantages:
    • Views: Complex views can be slow; updatable views have limits.
    • Indexes: Slow down writes and take space.
    • Procedures: Vendor-specific syntax; hard to version and test.
    • Triggers: Hidden magic; hard to debug; can cascade unexpectedly.
    • Over-engineering: Logic scattered between app and DB.
  7. Characteristics:
    • Views are virtual: They run the underlying query each time (unless materialized).
    • Indexes trade write for read: Faster SELECT, slower INSERT/UPDATE.
    • Procedures are precompiled: Faster than ad-hoc SQL.
    • Triggers run in the same transaction: Rollback undoes their effects.
    • Naming conventions: v_, idx_, sp_, trg_ help maintainability.
  8. Diagram: Views and indexes in the architecture
        Application
            │  SELECT * FROM StudentPublic
            ▼
        ┌──────────────────────┐
        │  View: StudentPublic │  ← virtual table
        └─────────┬────────────┘
                  │
                  ▼
        ┌──────────────────────┐
        │  Base Table: Student │
        │  Index: idx_email    │  ← speeds lookups
        └──────────────────────┘
    
        Trigger flow (AFTER UPDATE):
    
          UPDATE Student …
               │
               ▼
          Trigger trg_student_audit fires
               │
               ▼
          INSERT INTO StudentAudit …
  9. Conclusion: Views, indexes, procedures, and triggers extend SQL into a full application platform inside the database. Use views to expose the right shape of data and hide sensitive columns. Index the columns you filter and join on, but do not over-index. Put business logic in procedures when it truly belongs in the database — but keep critical rules testable in your application too. Triggers are powerful, but use them carefully: invisible side effects are a common source of bugs. Well-chosen advanced SQL objects make a database both fast and safe.
  10. Exercise:
    1. Create a view that hides salary from an Employee table.
    2. Create an index on Student(email) and compare query plans before/after.
    3. Write a stored procedure that raises salaries by a percentage.
    4. Write an AFTER UPDATE trigger that logs changes to an audit table.
    5. Explain when a materialized view is preferable to a regular view.

हिंदी (सरल)

  1. समस्या: असली applications को बार-बार वही complex query चाहिए, security के लिए data का restricted view, बड़ी tables पर तेज़ lookups, और business logic जो database के अंदर चले। हर जगह वही SQL लिखने से duplication, inconsistency और performance problems होते हैं। Database logic को encapsulate और accelerate करने का तरीका चाहिए।
  2. परिभाषा: Advanced SQL objects:
    • View: Stored query जो virtual table की तरह behave करती है।
    • Index: Data structure (आमतौर पर B-tree) जो lookups और joins तेज़ करता है।
    • Stored Procedure / Function: Named, precompiled SQL logic के blocks।
    • Trigger: Code जो INSERT/UPDATE/DELETE पर अपने आप fire होता है।
  3. उदाहरण: View, index, procedure और trigger:
    -- VIEW: sensitive columns छिपाएँ
    CREATE VIEW StudentPublic AS
    SELECT student_id, name, dept_id
    FROM Student;
    
    -- INDEX: email से search तेज़
    CREATE INDEX idx_student_email ON Student(email);
    
    -- STORED PROCEDURE
    CREATE PROCEDURE PromoteStudents(IN minAge INT)
    BEGIN
      UPDATE Student SET dept_id = 2
      WHERE age >= minAge;
    END;
    
    -- TRIGGER: audit updates
    CREATE TRIGGER trg_student_audit
    AFTER UPDATE ON Student
    FOR EACH ROW
    INSERT INTO StudentAudit(student_id, changed_at)
    VALUES (OLD.student_id, NOW());
  4. प्रकार:

    A. Views:

    • Simple view: एक table, no aggregates; आमतौर पर updatable।
    • Complex view: Joins, aggregates, GROUP BY; आमतौर पर read-only।
    • Materialized view: Physically stored; refresh चाहिए; reads तेज़।

    B. Indexes:

    प्रकार उपयोग
    B-tree Equality और range के लिए default।
    Hash सिर्फ equality; बहुत तेज़ lookups।
    Bitmap Low-cardinality columns (gender, status)।
    Composite कई columns; column order मायने रखता है।
    Partial / filtered सिर्फ rows के subset पर index।
    Full-text Text search (LIKE '%…%' with language rules)।

    C. Stored routines और triggers: Procedures (नाम से callable), functions (value return), triggers (events पर fire)।

  5. लाभ:
    • Views: Security, simplification, abstraction।
    • Indexes: Reads और joins में भारी speedups।
    • Procedures: Reuse, precompilation, encapsulate logic।
    • Triggers: Automatic audits, derived columns, integrity rules।
    • Central logic: Business rules एक जगह।
  6. नुकसान:
    • Views: Complex views slow; updatable views की सीमाएँ।
    • Indexes: Writes slow और space लेते हैं।
    • Procedures: Vendor-specific syntax; version और test करना कठिन।
    • Triggers: Hidden magic; debug मुश्किल; unexpected cascades।
    • Over-engineering: Logic app और DB में बिखर जाती है।
  7. विशेषताएँ:
    • Views virtual हैं: हर बार underlying query चलाते हैं (जब तक materialized न हों)।
    • Indexes write के लिए read trade: SELECT तेज़, INSERT/UPDATE धीमे।
    • Procedures precompiled: Ad-hoc SQL से तेज़।
    • Triggers same transaction में: Rollback उनका असर भी undo करता है।
    • Naming conventions: v_, idx_, sp_, trg_ maintainability बढ़ाते हैं।
  8. आरेख: Architecture में views और indexes
        Application
            │  SELECT * FROM StudentPublic
            ▼
        ┌──────────────────────┐
        │  View: StudentPublic │  ← virtual table
        └─────────┬────────────┘
                  │
                  ▼
        ┌──────────────────────┐
        │  Base Table: Student │
        │  Index: idx_email    │  ← lookups तेज़
        └──────────────────────┘
    
        Trigger flow (AFTER UPDATE):
    
          UPDATE Student …
               │
               ▼
          Trigger trg_student_audit fire
               │
               ▼
          INSERT INTO StudentAudit …
  9. निष्कर्ष: Views, indexes, procedures और triggers SQL को database के अंदर पूर्ण application platform तक extend करते हैं। Views से data का सही shape expose करें और sensitive columns छिपाएँ। जिन columns पर filter और join करते हैं उन पर index लगाएँ, पर over-index न करें। Business logic procedures में तभी रखें जब वाकई database में belong करे — पर critical rules को application में भी testable रखें। Triggers powerful हैं, सावधानी से use करें: invisible side effects bugs का आम source हैं। अच्छी तरह चुने गए advanced SQL objects database को fast और safe दोनों बनाते हैं।
  10. अभ्यास:
    1. Employee table से salary छिपाने वाला view बनाइए।
    2. Student(email) पर index बनाकर before/after query plans की तुलना कीजिए।
    3. एक stored procedure लिखिए जो salaries को percentage से बढ़ाए।
    4. AFTER UPDATE trigger लिखिए जो changes को audit table में log करे।
    5. बताइए कब materialized view regular view से बेहतर है।

11. Transactions & ACID Properties

English

  1. Problem: Real applications perform multi-step operations: transfer money, place an order, register a user with a profile. If the system crashes halfway, or another user reads the data mid-operation, we get inconsistent results: money vanishes, orders lose items, users exist without profiles. A unit of work is needed that either completes fully or not at all, and that isolates concurrent users from each other.
  2. Definition: A transaction is a logical unit of work consisting of one or more SQL statements that must be executed atomically. Transactions satisfy ACID properties: Atomicity, Consistency, Isolation, and Durability. The DBMS guarantees ACID via logging, locking, and recovery mechanisms.
  3. Example: A money transfer of ₹100 from A to B:
    BEGIN;
    UPDATE Account SET balance = balance - 100 WHERE id = 'A';
    UPDATE Account SET balance = balance + 100 WHERE id = 'B';
    COMMIT;
    
    If the second UPDATE fails, the first must be undone,
    otherwise ₹100 disappears. That's Atomicity.
    
    If another session reads balance in between, it must
    not see the intermediate state. That's Isolation.
    
    After COMMIT, even if the system crashes, the new
    balances must be recoverable. That's Durability.
    
    The invariant "sum of balances = constant" must
    hold before and after. That's Consistency.
  4. Types:

    A. ACID properties:

    Property Meaning Guaranteed By
    Atomicity All or nothing. Undo log / rollback.
    Consistency Preserves invariants and constraints. Constraints + application logic + triggers.
    Isolation Concurrent transactions do not interfere. Locks, MVCC, isolation levels.
    Durability Committed data survives crashes. Write-ahead log + fsync + replication.

    B. Transaction states:

    State Meaning
    Active Executing statements.
    Partially committed Last statement executed; log not yet flushed.
    Committed Changes permanent; log flushed.
    Failed Error occurred; needs rollback.
    Aborted Rolled back; can be retried.

    C. Isolation levels:

    Level Dirty Read Non-Repeatable Read Phantom Read
    READ UNCOMMITTED Yes Yes Yes
    READ COMMITTED No Yes Yes
    REPEATABLE READ No No Yes
    SERIALIZABLE No No No
  5. Advantages:
    • Reliability: Application can trust the data.
    • Concurrency: Many users work simultaneously without corruption.
    • Recovery: Crashes do not leave partial work.
    • Simpler code: Applications do not need to fix partial writes.
    • Correctness under failure: Well-understood guarantees.
  6. Disadvantages:
    • Contention: Stronger isolation = more locking = less concurrency.
    • Deadlocks: Concurrent transactions can wait on each other.
    • Overhead: Logging and locking consume resources.
    • Long transactions: Increase lock contention and log growth.
    • Isolation vs speed: Higher isolation levels slow reads.
  7. Characteristics:
    • Begin / Commit / Rollback: Standard transaction boundaries.
    • Savepoints: Partial rollback within a transaction.
    • Auto-commit: Default for single statements.
    • Anomalies: Dirty read, non-repeatable read, phantom read, lost update.
    • MVCC: Many DBMSs use multi-version concurrency control to reduce blocking.
  8. Diagram: Transaction lifecycle and anomalies
        Active  →  Partially Committed  →  Committed
            │                    │
            │                    │
            ▼                    ▼
          Failed  ──────────►  Aborted
    
        Anomalies:
    
          T1:   Read(A)  Write(A)  Commit
          T2:        Read(A)  →  dirty read (if T1 aborts)
    
          T1: Read(A)              Read(A)
          T2:          Update(A)                 ← non-repeatable
    
          T1: SELECT … WHERE age < 30
          T2: INSERT age=25  → phantom row seen next time
  9. Conclusion: Transactions and ACID are the reason databases can be trusted under failures and concurrency. Every multi-step operation must be wrapped in a transaction, and the right isolation level must be chosen for the workload. Long transactions are the enemy of concurrency — keep them short, and commit quickly. Understand the anomalies each isolation level prevents, and the cost of preventing them. This is the foundation on which reliable systems are built.
  10. Exercise:
    1. Write a transaction for a bank transfer with proper COMMIT/ROLLBACK.
    2. Demonstrate a dirty read under READ UNCOMMITTED and its absence under READ COMMITTED.
    3. Explain each ACID property with a real-world example.
    4. Draw the state transition diagram for transactions.
    5. Compare isolation levels with a table of anomalies.

हिंदी (सरल)

  1. समस्या: असली applications multi-step operations करती हैं: money transfer, order place, user और profile register। अगर बीच में system crash हो, या दूसरा user बीच के data को read करे, तो inconsistent results मिलते हैं: money गायब, orders आधे, user बिना profile। काम की एक unit चाहिए जो या तो पूरी हो या बिल्कुल न हो, और concurrent users को एक-दूसरे से isolate रखे।
  2. परिभाषा: एक transaction काम की logical unit है जिसमें एक या ज़्यादा SQL statements होती हैं जो atomically execute होनी चाहिए। Transactions ACID properties को satisfy करती हैं: Atomicity, Consistency, Isolation, और Durability। DBMS logging, locking और recovery के ज़रिए ACID guarantee करता है।
  3. उदाहरण: A से B को ₹100 transfer:
    BEGIN;
    UPDATE Account SET balance = balance - 100 WHERE id = 'A';
    UPDATE Account SET balance = balance + 100 WHERE id = 'B';
    COMMIT;
    
    अगर दूसरी UPDATE fail हो, पहली undo होनी चाहिए,
    वरना ₹100 गायब। यही Atomicity है।
    
    अगर बीच में कोई दूसरा session balance पढ़े, उसे
    intermediate state नहीं दिखनी चाहिए। यही Isolation है।
    
    COMMIT के बाद system crash हो, नए balances recover
    होने चाहिए। यही Durability है।
    
    "sum of balances = constant" invariant पहले और बाद
    में hold करे। यही Consistency है।
  4. प्रकार:

    A. ACID properties:

    Property मतलब किससे Guaranteed
    Atomicity All or nothing। Undo log / rollback।
    Consistency Invariants और constraints preserve। Constraints + app logic + triggers।
    Isolation Concurrent transactions interfere नहीं। Locks, MVCC, isolation levels।
    Durability Committed data crash के बाद भी रहे। Write-ahead log + fsync + replication।

    B. Transaction states:

    State मतलब
    Active Statements execute हो रही हैं।
    Partially committed Last statement execute; log flush नहीं।
    Committed Changes permanent; log flush।
    Failed Error; rollback चाहिए।
    Aborted Rolled back; retry हो सकता है।

    C. Isolation levels:

    Level Dirty Read Non-Repeatable Read Phantom Read
    READ UNCOMMITTED हाँ हाँ हाँ
    READ COMMITTED नहीं हाँ हाँ
    REPEATABLE READ नहीं नहीं हाँ
    SERIALIZABLE नहीं नहीं नहीं
  5. लाभ:
    • Reliability: Application data पर भरोसा कर सकती है।
    • Concurrency: कई users साथ काम करें बिना corruption।
    • Recovery: Crashes partial काम नहीं छोड़ते।
    • Simpler code: Applications को partial writes ठीक नहीं करने पड़ते।
    • Correctness under failure: Well-understood guarantees।
  6. नुकसान:
    • Contention: Stronger isolation = ज़्यादा locking = कम concurrency।
    • Deadlocks: Concurrent transactions एक-दूसरे पर wait।
    • Overhead: Logging और locking resources लेते हैं।
    • Long transactions: Lock contention और log growth बढ़ाते हैं।
    • Isolation vs speed: Higher isolation reads slow करते हैं।
  7. विशेषताएँ:
    • Begin / Commit / Rollback: Standard transaction boundaries।
    • Savepoints: Transaction के अंदर partial rollback।
    • Auto-commit: Single statements के लिए default।
    • Anomalies: Dirty read, non-repeatable read, phantom read, lost update।
    • MVCC: कई DBMSs multi-version concurrency control से blocking कम करते हैं।
  8. आरेख: Transaction lifecycle और anomalies
        Active  →  Partially Committed  →  Committed
            │                    │
            │                    │
            ▼                    ▼
          Failed  ──────────►  Aborted
    
        Anomalies:
    
          T1:   Read(A)  Write(A)  Commit
          T2:        Read(A)  →  dirty read (if T1 aborts)
    
          T1: Read(A)              Read(A)
          T2:          Update(A)                 ← non-repeatable
    
          T1: SELECT … WHERE age < 30
          T2: INSERT age=25  → phantom row next time
  9. निष्कर्ष: Transactions और ACID ही वजह हैं कि databases failures और concurrency के तहत भरोसेमंद रह सकते हैं। हर multi-step operation transaction में wrap होनी चाहिए, और workload के हिसाब से सही isolation level चुननी चाहिए। Long transactions concurrency की दुश्मन हैं — छोटी रखें और जल्दी commit करें। हर isolation level कौन सी anomalies रोकती है और उसकी लागत क्या है, यह समझें। यही reliable systems की नींव है।
  10. अभ्यास:
    1. Bank transfer के लिए proper COMMIT/ROLLBACK वाला transaction लिखिए।
    2. READ UNCOMMITTED में dirty read और READ COMMITTED में उसकी अनुपस्थिति demonstrate कीजिए।
    3. हर ACID property को real-world उदाहरण के साथ समझाइए।
    4. Transactions का state transition diagram बनाइए।
    5. Isolation levels की anomalies वाली table से तुलना कीजिए।

12. Concurrency Control – Locks, 2PL, Deadlocks

English

  1. Problem: When many transactions run at the same time, they may read and write overlapping data. Without control, we get lost updates (two updates overwrite each other), uncommitted reads (reading data later rolled back), and non-repeatable reads. But over-controlling kills concurrency. We need a mechanism that allows maximum parallelism while preserving the illusion that each transaction runs alone (serialisability).
  2. Definition: Concurrency control is the set of techniques DBMSs use to ensure that concurrent transactions produce a result equal to some serial order. Common techniques: locking (shared/exclusive), two-phase locking (2PL), timestamp ordering, optimistic concurrency control, and multiversion concurrency control (MVCC).
  3. Example: Two transactions updating the same row:
    -- Without locking, Lost Update:
    T1: READ A (100)
    T2: READ A (100)
    T1: WRITE A = 110
    T2: WRITE A = 120     ← T1's update lost
    
    -- With 2PL, T2 waits until T1 commits:
    T1: LOCK-X A → WRITE A = 110 → UNLOCK
    T2:                 LOCK-X A → WRITE A = 120 → UNLOCK
    Final A = 120 (correct)
  4. Types:

    A. Lock modes:

    Lock Use Conflict
    Shared (S) Read Conflicts with X only.
    Exclusive (X) Write Conflicts with S and X.
    Intent (IS, IX) Hierarchical locking (rows/tables). Prevents conflicts at coarser levels.

    B. Protocols:

    Protocol Idea
    2PL (Basic) Growing phase acquires locks; shrinking phase releases them.
    Strict 2PL Holds X-locks until commit → no dirty reads.
    Rigorous 2PL Holds all locks until commit → strictest.
    Timestamp ordering Each T has a timestamp; order enforced by timestamp.
    Optimistic (OCC) Read → Validate → Write. Good when conflicts rare.
    MVCC Readers see a snapshot; writers create new versions.

    C. Anomalies prevented: lost update, dirty read, unrepeatable read, phantom read, write skew.

  5. Advantages:
    • Correctness: Ensures serialisable outcomes.
    • Concurrency: S-locks let many readers proceed together.
    • Choice of protocols: Pessimistic when conflicts common; optimistic when rare.
    • MVCC: Readers never block writers and vice versa.
    • Predictable: Standardised isolation levels.
  6. Disadvantages:
    • Deadlocks: Circular waits between transactions.
    • Starvation: A transaction may wait indefinitely.
    • Overhead: Lock manager consumes CPU and memory.
    • Reduced parallelism: More locks = less throughput.
    • Retry storms: Under OCC, many retries when conflicts spike.
  7. Characteristics:
    • Serialisability: Gold standard for correctness.
    • Two-phase rule: Once you release, you cannot acquire again.
    • Deadlock detection: Wait-for graphs, timeouts.
    • Deadlock prevention: Timestamp-based wound-wait, wait-die.
    • Granularity: Row, page, table, database.
  8. Diagram: 2PL phases and deadlock cycle
        2PL lifecycle:
    
          GROWING PHASE            SHRINKING PHASE
          Acquire locks →          → Release locks
          (no releases allowed)    (no new acquires)
    
        Deadlock cycle:
    
          T1 holds A, wants B
                 │
                 ▼
          T2 holds B, wants A
                 │
                 ▼
          Circular wait → deadlock
    
        Detection: build wait-for graph; if cycle, abort one T.
  9. Conclusion: Concurrency control is the machinery behind the "I" in ACID. Two-phase locking remains the classic correct protocol, while MVCC dominates modern databases for read-heavy workloads. Every production DBMS lets you choose isolation levels and lock granularity, and detects or prevents deadlocks. Understanding locks, 2PL, and deadlocks is essential for writing applications that scale under heavy concurrent load. Keep transactions short, access rows in a consistent order, and choose the weakest isolation level your correctness requires.
  10. Exercise:
    1. Show with a diagram how lost update occurs without locking.
    2. Explain 2PL and why it guarantees serialisability.
    3. Construct a wait-for graph with a deadlock cycle.
    4. Compare strict 2PL with MVCC in a short table.
    5. Describe two deadlock-prevention schemes (wound-wait, wait-die).

हिंदी (सरल)

  1. समस्या: जब कई transactions एक साथ चलती हैं, वे overlapping data पढ़/लिख सकती हैं। Control के बिना lost updates (दो updates एक-दूसरे को overwrite करें), uncommitted reads (जो बाद में rollback हो), non-repeatable reads होती हैं। पर over-control concurrency मार देता है। ऐसा mechanism चाहिए जो maximum parallelism देते हुए यह illusion रखे कि हर transaction अकेली चल रही है (serialisability)।
  2. परिभाषा: Concurrency control वे techniques हैं जिनसे DBMS सुनिश्चित करता है कि concurrent transactions का result किसी serial order के बराबर हो। प्रमुख techniques: locking (shared/exclusive), two-phase locking (2PL), timestamp ordering, optimistic concurrency control, और multiversion concurrency control (MVCC)।
  3. उदाहरण: एक ही row को दो transactions update कर रही हैं:
    -- Locking के बिना Lost Update:
    T1: READ A (100)
    T2: READ A (100)
    T1: WRITE A = 110
    T2: WRITE A = 120     ← T1 का update खो गया
    
    -- 2PL के साथ, T2, T1 के commit तक wait:
    T1: LOCK-X A → WRITE A = 110 → UNLOCK
    T2:                 LOCK-X A → WRITE A = 120 → UNLOCK
    Final A = 120 (सही)
  4. प्रकार:

    A. Lock modes:

    Lock उपयोग Conflict
    Shared (S) Read सिर्फ X से conflict।
    Exclusive (X) Write S और X दोनों से conflict।
    Intent (IS, IX) Hierarchical locking (rows/tables)। Coarser levels पर conflicts रोकता है।

    B. Protocols:

    Protocol Idea
    2PL (Basic) Growing phase locks acquire; shrinking phase release।
    Strict 2PL X-locks commit तक hold → कोई dirty read नहीं।
    Rigorous 2PL सभी locks commit तक hold → strictest।
    Timestamp ordering हर T का timestamp; order timestamp से।
    Optimistic (OCC) Read → Validate → Write. Conflicts कम हों तो अच्छा।
    MVCC Readers को snapshot; writers नई versions बनाते हैं।

    C. Anomalies prevented: lost update, dirty read, unrepeatable read, phantom read, write skew।

  5. लाभ:
    • Correctness: Serialisable outcomes।
    • Concurrency: S-locks कई readers को साथ चलने देते हैं।
    • Protocol choice: Conflicts आम हों तो pessimistic; कम हों तो optimistic।
    • MVCC: Readers writers को block नहीं करते।
    • Predictable: Standardised isolation levels।
  6. नुकसान:
    • Deadlocks: Transactions का circular wait।
    • Starvation: कोई transaction अनिश्चित काल तक wait।
    • Overhead: Lock manager CPU और memory लेता है।
    • कम parallelism: ज़्यादा locks = कम throughput।
    • Retry storms: OCC में conflicts बढ़ने पर कई retries।
  7. विशेषताएँ:
    • Serialisability: Correctness का gold standard।
    • Two-phase rule: एक बार release, फिर acquire नहीं।
    • Deadlock detection: Wait-for graphs, timeouts।
    • Deadlock prevention: Timestamp-based wound-wait, wait-die।
    • Granularity: Row, page, table, database।
  8. आरेख: 2PL phases और deadlock cycle
        2PL lifecycle:
    
          GROWING PHASE            SHRINKING PHASE
          Locks acquire →          → Locks release
          (release नहीं)           (नए acquire नहीं)
    
        Deadlock cycle:
    
          T1 के पास A, चाहिए B
                 │
                 ▼
          T2 के पास B, चाहिए A
                 │
                 ▼
          Circular wait → deadlock
    
        Detection: wait-for graph; cycle मिले तो एक T abort।
  9. निष्कर्ष: Concurrency control ACID के "I" के पीछे की machinery है। Two-phase locking classic correct protocol है, जबकि MVCC आधुनिक read-heavy workloads में dominante है। हर production DBMS isolation levels और lock granularity चुनने देता है, और deadlocks detect या prevent करता है। Locks, 2PL और deadlocks समझना heavy concurrent load पर scale करने वाली applications लिखने के लिए ज़रूरी है। Transactions छोटी रखें, rows को consistent order में access करें, और weakest isolation level चुनें जो correctness के लिए ज़रूरी हो।
  10. अभ्यास:
    1. Locking के बिना lost update कैसे होता है diagram से दिखाइए।
    2. 2PL समझाइए और क्यों यह serialisability देता है।
    3. Deadlock cycle वाला wait-for graph बनाइए।
    4. Strict 2PL और MVCC की छोटी table में तुलना कीजिए।
    5. दो deadlock-prevention schemes (wound-wait, wait-die) describe कीजिए।

13. Recovery & Logging – WAL, Checkpoints, ARIES

English

  1. Problem: Systems crash — power failures, OS bugs, disk errors, application bugs. At the moment of a crash, a transaction may be halfway through. Without recovery machinery, the database would be left in an inconsistent state: some effects of an aborted transaction persisted, some committed transactions lost. We need a way to restore the database to a consistent state after any crash, and to guarantee that committed data is not lost.
  2. Definition: Recovery is the set of techniques DBMSs use to restore a consistent state after a failure and to ensure durability of committed transactions. It relies on logging: recording changes in a write-ahead log (WAL) before modifying the database. Recovery uses checkpoints to limit how much log must be replayed, and the ARIES algorithm (Analysis → Redo → Undo) as the industry-standard approach.
  3. Example: WAL entries for a money transfer:
    -- WAL rules:
    -- 1. Undo entries flushed before any data page is written
    -- 2. Redo entries flushed before COMMIT returns
    
    Log records:
      LSN 1:  T1 BEGIN
      LSN 2:  T1 UPDATE A: 100 → 90 (old=100, new=90)
      LSN 3:  T1 UPDATE B: 200 → 210 (old=200, new=210)
      LSN 4:  T1 COMMIT
    
    Crash → Recovery:
      Analysis : find last checkpoint
      Redo     : replay committed changes from log
      Undo     : roll back uncommitted changes
  4. Types:

    A. Failure types:

    Failure Effect Recovery
    Transaction failure Bad input, deadlock, constraint violation. Rollback that T only.
    System crash RAM lost, disk intact. Redo committed; undo uncommitted.
    Media failure Disk lost or corrupted. Restore from backup + redo log.

    B. Log records: BEGIN, UPDATE (with old/new values), COMMIT, ABORT, CLR (compensation log record), CHECKPOINT.

    C. Algorithms:

    Algorithm Idea
    Deferred update (NO-UNDO/REDO) Write only after commit; redo on crash.
    Immediate update (UNDO/REDO) Write during transaction; undo uncommitted, redo committed.
    Shadow paging (NO-UNDO/NO-REDO) Copy-on-write pages; switch pointer on commit.
    ARIES Analysis + Redo + Undo with LSN and CLRs.
  5. Advantages:
    • Durability: Committed data survives crashes.
    • Atomicity: Uncommitted work is rolled back.
    • Consistency: Database returns to a valid state.
    • Incremental: Only since last checkpoint is replayed.
    • Industry standard: ARIES widely implemented.
  6. Disadvantages:
    • Log overhead: Every change is written twice (log + data).
    • Checkpoint cost: Can pause the system briefly.
    • Recovery time: Long transaction = longer undo.
    • Complexity: Correct implementation is non-trivial.
    • Storage: Logs must be retained for media recovery.
  7. Characteristics:
    • WAL rule: Log first, then data.
    • LSN: Log Sequence Number identifies each record.
    • Idempotence: Redo can be applied repeatedly.
    • CLR: Undo actions themselves are logged to prevent re-undo.
    • Fuzzy checkpoints: Do not require quiescing transactions.
  8. Diagram: ARIES three-pass recovery
        Crash
          │
          ▼
        1. ANALYSIS
           - Read from last checkpoint
           - Build Dirty Page Table and Transaction Table
          │
          ▼
        2. REDO
           - Replay all updates (even of aborted T)
           - Idempotent, using LSN
          │
          ▼
        3. UNDO
           - Roll back uncommitted transactions
           - Write CLRs so crash during undo is safe
    
        WAL ordering:
    
          Log record flushed  ──►  Data page written  ──►  COMMIT returns
  9. Conclusion: Recovery and logging are what make ACID's Durability and Atomicity real. WAL is the core technique: write the log before the data. Checkpoints bound recovery time. ARIES, with its three passes and compensation log records, is the reference algorithm used in modern databases. When designing applications: do not keep transactions open for long, commit promptly, and rely on the DBMS to handle crashes — but understand what it is doing so you can reason about failure scenarios and test recovery.
  10. Exercise:
    1. Write sample WAL records for a bank transfer.
    2. Explain the WAL rule and why it is critical.
    3. Describe the three passes of ARIES with a diagram.
    4. Compare UNDO/REDO, NO-UNDO/REDO, and NO-UNDO/NO-REDO.
    5. Explain how a fuzzy checkpoint works.

हिंदी (सरल)

  1. समस्या: Systems crash होते हैं — power failure, OS bugs, disk errors, application bugs। Crash के समय transaction आधे रास्ते हो सकती है। Recovery machinery के बिना database inconsistent state में छूट जाएगा: aborted transaction के कुछ effects रह जाएँ, कुछ committed transactions खो जाएँ। हर crash के बाद database को consistent state में लाने और committed data न खोने की guarantee चाहिए।
  2. परिभाषा: Recovery वे techniques हैं जिनसे DBMS failure के बाद consistent state restore करता है और committed transactions की durability सुनिश्चित करता है। यह logging पर निर्भर है: database modify करने से पहले changes को write-ahead log (WAL) में record करना। Recovery checkpoints से replay कम करता है, और ARIES algorithm (Analysis → Redo → Undo) industry-standard है।
  3. उदाहरण: Money transfer के लिए WAL entries:
    -- WAL rules:
    -- 1. Undo entries कोई data page लिखने से पहले flush
    -- 2. Redo entries COMMIT return से पहले flush
    
    Log records:
      LSN 1:  T1 BEGIN
      LSN 2:  T1 UPDATE A: 100 → 90 (old=100, new=90)
      LSN 3:  T1 UPDATE B: 200 → 210 (old=200, new=210)
      LSN 4:  T1 COMMIT
    
    Crash → Recovery:
      Analysis : last checkpoint ढूँढो
      Redo     : log से committed changes replay
      Undo     : uncommitted changes roll back
  4. प्रकार:

    A. Failure types:

    Failure असर Recovery
    Transaction failure Bad input, deadlock, constraint violation। सिर्फ वह T rollback।
    System crash RAM गई, disk ठीक। Committed redo; uncommitted undo।
    Media failure Disk खोया/खराब। Backup restore + redo log।

    B. Log records: BEGIN, UPDATE (old/new values), COMMIT, ABORT, CLR (compensation log record), CHECKPOINT।

    C. Algorithms:

    Algorithm Idea
    Deferred update (NO-UNDO/REDO) सिर्फ commit के बाद write; crash पर redo।
    Immediate update (UNDO/REDO) Transaction के दौरान write; uncommitted undo, committed redo।
    Shadow paging (NO-UNDO/NO-REDO) Copy-on-write pages; commit पर pointer switch।
    ARIES Analysis + Redo + Undo with LSN and CLRs।
  5. लाभ:
    • Durability: Committed data crashes के बाद भी।
    • Atomicity: Uncommitted काम rollback।
    • Consistency: Database valid state में लौटता है।
    • Incremental: सिर्फ last checkpoint के बाद replay।
    • Industry standard: ARIES widely implemented।
  6. नुकसान:
    • Log overhead: हर change दो बार लिखा (log + data)।
    • Checkpoint cost: System थोड़ी देर pause।
    • Recovery time: लंबी transaction = लंबा undo।
    • Complexity: सही implementation आसान नहीं।
    • Storage: Media recovery के लिए logs रखने पड़ते हैं।
  7. विशेषताएँ:
    • WAL rule: पहले log, फिर data।
    • LSN: Log Sequence Number हर record को identify करता है।
    • Idempotence: Redo दोबारा apply हो सकता है।
    • CLR: Undo actions भी log होते हैं ताकि re-undo रुके।
    • Fuzzy checkpoints: Transactions quiesce करने की ज़रूरत नहीं।
  8. आरेख: ARIES three-pass recovery
        Crash
          │
          ▼
        1. ANALYSIS
           - Last checkpoint से पढ़ो
           - Dirty Page Table और Transaction Table बनाओ
          │
          ▼
        2. REDO
           - सभी updates replay (aborted T के भी)
           - Idempotent, LSN से
          │
          ▼
        3. UNDO
           - Uncommitted transactions roll back
           - CLRs लिखो ताकि undo के दौरान crash safe हो
    
        WAL ordering:
    
          Log record flush  ──►  Data page write  ──►  COMMIT return
  9. निष्कर्ष: Recovery और logging ही ACID की Durability और Atomicity को असली बनाते हैं। WAL core technique है: data से पहले log लिखो। Checkpoints recovery time सीमित करते हैं। ARIES, अपने तीन passes और compensation log records के साथ, modern databases में reference algorithm है। Applications design करते समय: transactions लंबी न रखें, जल्दी commit करें, और crashes DBMS पर छोड़ें — पर समझें कि वह क्या कर रहा है ताकि failure scenarios पर सोच सकें और recovery test कर सकें।
  10. अभ्यास:
    1. Bank transfer के लिए sample WAL records लिखिए।
    2. WAL rule समझाइए और यह क्यों critical है।
    3. ARIES के तीन passes diagram के साथ describe कीजिए।
    4. UNDO/REDO, NO-UNDO/REDO और NO-UNDO/NO-REDO की तुलना कीजिए।
    5. Fuzzy checkpoint कैसे काम करता है समझाइए।

14. Indexing & Hashing – B+ Trees, Hash Indexes, Covering Indexes

English

  1. Problem: A table with millions of rows cannot be scanned line by line for every query — full table scans are far too slow. We need auxiliary data structures that let the DBMS find rows by a key (or a range of keys) in near-constant or logarithmic time, and that also support efficient inserts and deletes as data changes.
  2. Definition: An index is an auxiliary data structure that maps values of one or more columns to the physical locations of rows. Indexes dramatically speed up lookups, joins, and range queries. Common types: B+ tree (default for most DBMSs — great for equality and range), hash index (equality only), bitmap (low-cardinality columns), full-text (text search), and covering index (contains all columns needed by a query).
  3. Example: A B+ tree index on Student(email):
    CREATE INDEX idx_student_email ON Student(email);
    
    Query (uses index):
      SELECT * FROM Student WHERE email = 'a@x.com';
      → O(log n) instead of O(n)
    
    Range query (uses index):
      SELECT * FROM Student WHERE email BETWEEN 'a' AND 'b';
    
    Covering index (no table lookup needed):
      CREATE INDEX idx_dept_name ON Student(dept_id, name);
      SELECT dept_id, name FROM Student WHERE dept_id = 1;
  4. Types:

    A. Index types:

    Type Good For Notes
    B+ tree Equality + range Default; balanced; ordered.
    Hash Equality only Very fast lookups; no range scans.
    Bitmap Low-cardinality columns Compact; good for analytics.
    Composite Multi-column queries Column order matters (leftmost prefix).
    Covering Read-heavy queries No table lookup if all columns in index.
    Full-text Word search Supports stemming and ranking.
    Partial / filtered Subset of rows Smaller, faster; e.g., WHERE active = TRUE.

    B. Hash-based structures: static hashing, extendible hashing, linear hashing. Used for in-memory and equality lookups.

  5. Advantages:
    • Massive speedups: SELECT, JOIN, ORDER BY, GROUP BY.
    • Range scans: B+ trees give sorted order for free.
    • Covering indexes: Eliminate table lookups.
    • Unique enforcement: Unique indexes back PRIMARY KEY / UNIQUE.
    • Flexible: Different indexes for different workloads.
  6. Disadvantages:
    • Write overhead: Every INSERT/UPDATE/DELETE updates indexes too.
    • Storage: Indexes can be as large as the table.
    • Maintenance: Fragmentation; rebuilds needed over time.
    • Planner misuse: The wrong index can slow queries.
    • Over-indexing: Too many indexes hurt write throughput.
  7. Characteristics:
    • B+ trees: Balanced, all leaves at same depth, linked leaves for range scans.
    • Clustered vs non-clustered: Clustered index orders the table itself; only one per table.
    • Cardinality: Higher cardinality = better index efficiency.
    • Selectivity: A highly selective filter is ideal for an index.
    • Composite order: Leftmost prefix rule — index(a,b) can help WHERE a=? and WHERE a=? AND b=?, but not WHERE b=? alone.
  8. Diagram: B+ tree structure and index access
        B+ Tree (order 3):
    
                  [ 20 | 40 ]
                 /     |     \
            [5|10]   [25|35]   [45|60]
            / | \     / | \     / | \
           5 10 15  20 25 35  40 45 60   ← leaves (linked)
           ◄────────────────────────────►  range scan
    
        Query access paths:
    
          WHERE id = 42         → index seek (O(log n))
          WHERE id BETWEEN 10 AND 40 → index range scan
          WHERE name LIKE '%a%' → full scan (index unusable)
    
        Clustered vs non-clustered:
    
          Clustered:   table rows physically sorted by index key
          Non-clustered: index stores pointers to rows
  9. Conclusion: Indexes are the single biggest lever for query performance in relational databases. B+ trees are the default for a reason — they handle equality, range, and ordered scans elegantly. Choose indexes based on real query patterns: the columns you filter, join, and sort on. Prefer covering and composite indexes where they eliminate table lookups. But remember: every index is a tax on writes and storage, so never index blindly. Measure with EXPLAIN, and remove unused indexes.
  10. Exercise:
    1. Create a B+ tree index on Student(email) and explain why equality and range queries both benefit.
    2. Design a covering index for a report query and show that it eliminates table access.
    3. Explain the leftmost prefix rule for composite indexes.
    4. Compare clustered and non-clustered indexes with a diagram.
    5. List three situations where an index would hurt more than help.

हिंदी (सरल)

  1. समस्या: लाखों rows वाली table को हर query के लिए line-by-line scan नहीं कर सकते — full table scans बहुत slow हैं। ऐसी auxiliary data structures चाहिए जो DBMS को किसी key (या keys के range) से rows लगभग constant या logarithmic time में ढूँढने दें, और data बदलने पर efficient inserts/deletes भी support करें।
  2. परिभाषा: Index एक auxiliary data structure है जो एक या ज़्यादा columns की values को rows के physical locations से map करता है। Indexes lookups, joins और range queries को बहुत तेज़ करते हैं। प्रमुख types: B+ tree (ज़्यादातर DBMSs का default — equality और range के लिए बेहतरीन), hash index (सिर्फ equality), bitmap (low-cardinality columns), full-text (text search), और covering index (जिसमें query की सभी columns हों)।
  3. उदाहरण: Student(email) पर B+ tree index:
    CREATE INDEX idx_student_email ON Student(email);
    
    Query (index use):
      SELECT * FROM Student WHERE email = 'a@x.com';
      → O(n) के बजाय O(log n)
    
    Range query (index use):
      SELECT * FROM Student WHERE email BETWEEN 'a' AND 'b';
    
    Covering index (table lookup नहीं):
      CREATE INDEX idx_dept_name ON Student(dept_id, name);
      SELECT dept_id, name FROM Student WHERE dept_id = 1;
  4. प्रकार:

    A. Index types:

    Type किसके लिए अच्छा Notes
    B+ tree Equality + range Default; balanced; ordered।
    Hash सिर्फ equality बहुत तेज़ lookups; range नहीं।
    Bitmap Low-cardinality columns Compact; analytics के लिए अच्छा।
    Composite Multi-column queries Column order मायने रखता है (leftmost prefix)।
    Covering Read-heavy queries सभी columns index में हों तो table lookup नहीं।
    Full-text Word search Stemming और ranking support।
    Partial / filtered Subset of rows छोटा, तेज़; जैसे WHERE active = TRUE।

    B. Hash-based structures: static hashing, extendible hashing, linear hashing। In-memory और equality lookups के लिए।

  5. लाभ:
    • भारी speedups: SELECT, JOIN, ORDER BY, GROUP BY।
    • Range scans: B+ trees sorted order मुफ्त देते हैं।
    • Covering indexes: Table lookups खत्म।
    • Unique enforcement: Unique indexes PRIMARY KEY / UNIQUE back करते हैं।
    • Flexible: अलग workloads के लिए अलग indexes।
  6. नुकसान:
    • Write overhead: हर INSERT/UPDATE/DELETE indexes भी update।
    • Storage: Indexes table जितने बड़े हो सकते हैं।
    • Maintenance: Fragmentation; समय-समय पर rebuild।
    • Planner misuse: गलत index queries slow कर सकता है।
    • Over-indexing: बहुत indexes write throughput खराब करते हैं।
  7. विशेषताएँ:
    • B+ trees: Balanced, सभी leaves same depth पर, range scans के लिए linked leaves।
    • Clustered vs non-clustered: Clustered index table को ही order करता है; एक प्रति table।
    • Cardinality: ज़्यादा cardinality = बेहतर index efficiency।
    • Selectivity: Highly selective filter index के लिए ideal।
    • Composite order: Leftmost prefix rule — index(a,b) WHERE a=? और WHERE a=? AND b=? में मदद करता है, पर WHERE b=? अकेला नहीं।
  8. आरेख: B+ tree structure और index access
        B+ Tree (order 3):
    
                  [ 20 | 40 ]
                 /     |     \
            [5|10]   [25|35]   [45|60]
            / | \     / | \     / | \
           5 10 15  20 25 35  40 45 60   ← leaves (linked)
           ◄────────────────────────────►  range scan
    
        Query access paths:
    
          WHERE id = 42         → index seek (O(log n))
          WHERE id BETWEEN 10 AND 40 → index range scan
          WHERE name LIKE '%a%' → full scan (index unusable)
    
        Clustered vs non-clustered:
    
          Clustered:   rows physically index key से sorted
          Non-clustered: index pointers to rows रखता है
  9. निष्कर्ष: Indexes relational databases में query performance का सबसे बड़ा lever हैं। B+ trees default क्यों हैं — वे equality, range और ordered scans elegantly संभालते हैं। असली query patterns के आधार पर indexes चुनें: जिन columns पर filter, join और sort करते हैं। जहाँ table lookups खत्म हों वहाँ covering और composite indexes prefer करें। पर याद रखें: हर index writes और storage पर tax है, इसलिए अंधाधुंध index न लगाएँ। EXPLAIN से measure करें और unused indexes हटाएँ।
  10. अभ्यास:
    1. Student(email) पर B+ tree index बनाइए और बताइए equality और range दोनों को फायदा क्यों।
    2. एक report query के लिए covering index design कीजिए और दिखाइए कि table access खत्म।
    3. Composite indexes का leftmost prefix rule समझाइए।
    4. Clustered और non-clustered indexes की diagram के साथ तुलना कीजिए।
    5. तीन situations बताइए जहाँ index नुकसान ही करेगा।

15. Query Optimization – Plans, Cost Model, EXPLAIN

English

  1. Problem: A single SQL query can be executed in many different ways — the order of joins, the join algorithms (nested loop, hash, sort-merge), the access paths (index vs full scan), and the order of filters. Some plans are 1000× faster than others. The user should not have to specify the plan; the DBMS must choose a good one automatically.
  2. Definition: Query optimization is the process by which the DBMS converts a declarative SQL query into an efficient execution plan. It uses relational algebra for logical transformations, statistics (histograms, cardinality) for cost estimation, and a cost model (I/O + CPU) to compare alternative plans. The result is a physical plan the executor runs. EXPLAIN shows the plan.
  3. Example: Two plans for the same query:
    SELECT c.name
    FROM Customer c JOIN Orders o ON c.id = o.cust_id
    WHERE o.date >= '2025-01-01';
    
    Plan A (bad): full scan Orders, full scan Customer,
                  nested loop join
    Plan B (good): use index on Orders(date),
                   hash join with Customer
    
    View plans in PostgreSQL / MySQL:
      EXPLAIN ANALYZE SELECT ...
  4. Types:

    A. Join algorithms:

    Algorithm Best When
    Nested loop join Small outer table, indexed inner.
    Block nested loop No indexes, memory-limited.
    Hash join Large tables, equality join.
    Sort-merge join Inputs already sorted or need order.

    B. Optimization phases:

    Phase Purpose
    Parsing Syntax + semantic checks; build parse tree.
    Logical rewrite Relational algebra transformations; predicate pushdown; view expansion.
    Physical planning Choose access paths, join algorithms, join order.
    Cost estimation Use statistics to estimate I/O + CPU; pick cheapest.
    Execution Run the chosen plan; produce results.

    C. Heuristics: Push selections down; project early; avoid Cartesian products; use indexes when selective; join smaller relations first.

  5. Advantages:
    • Performance: Orders of magnitude difference between plans.
    • Declarative: Users write what, not how.
    • Adaptive: Statistics drive current-data choices.
    • Transparent: EXPLAIN lets you inspect and tune.
    • Extensible: New algorithms and indexes plug in.
  6. Disadvantages:
    • Statistics drift: Stale stats cause bad plans.
    • Cost model imperfect: Correlated columns, skewed data mislead.
    • Planning time: Complex queries take milliseconds to plan.
    • Hint dependence: Sometimes hints are needed to fix bad plans.
    • Parameter sniffing: Plan tuned for one parameter can hurt another.
  7. Characteristics:
    • Cost-based: Chooses plan with lowest estimated cost.
    • Rules + cost: Heuristics narrow the search; cost picks the best.
    • Statistics: Row counts, distinct values, histograms, index height.
    • Search space pruning: Only promising join orders explored.
    • Plan cache: Reuse plans for identical queries.
  8. Diagram: Query optimization pipeline
        SQL text
           │
           ▼
        Parser  →  Parse Tree
           │
           ▼
        Rewriter  →  Logical Plan (relational algebra)
           │
           ▼
        Optimizer
           │  ├── Statistics (table, columns, indexes)
           │  ├── Cost model  (I/O + CPU + network)
           │  ├── Search (join orders, algorithms, access paths)
           │  └── Choose lowest cost plan
           │
           ▼
        Physical Plan
           │
           ▼
        Executor  →  Results
    
        EXPLAIN output (simplified):
    
          Hash Join  (cost=… rows=…)
            ├─ Seq Scan on Customer
            └─ Index Scan on Orders (date >= …)
  9. Conclusion: Query optimization is what makes SQL feel magical — the same declarative query can be executed efficiently without the user specifying how. The optimizer relies on statistics, a cost model, and search heuristics to pick a plan. When performance problems arise, the first step is always to look at the plan with EXPLAIN, verify statistics are up to date, and check whether the plan uses the indexes you expect. Sometimes the fix is a better index; sometimes it is a query rewrite; occasionally it is a hint. Learn to read plans — it is the single most valuable skill for database performance tuning.
  10. Exercise:
    1. Run EXPLAIN on a simple join in your DBMS and identify the join algorithm.
    2. Compare plans for the same query with and without an index.
    3. Explain predicate pushdown with an example.
    4. Describe when a hash join is preferred over a nested loop join.
    5. List three reasons the optimizer might choose a bad plan.

हिंदी (सरल)

  1. समस्या: एक ही SQL query कई तरीकों से execute हो सकती है — joins का order, join algorithms (nested loop, hash, sort-merge), access paths (index vs full scan), और filters का order। कुछ plans 1000× तेज़ होते हैं। User को plan नहीं बताना चाहिए; DBMS को अपने आप अच्छा plan चुनना चाहिए।
  2. परिभाषा: Query optimization वह process है जिससे DBMS declarative SQL query को efficient execution plan में बदलता है। यह relational algebra से logical transformations, statistics (histograms, cardinality) से cost estimation, और एक cost model (I/O + CPU) से alternative plans compare करता है। Result physical plan होता है जिसे executor चलाता है। EXPLAIN plan दिखाता है।
  3. उदाहरण: एक ही query के दो plans:
    SELECT c.name
    FROM Customer c JOIN Orders o ON c.id = o.cust_id
    WHERE o.date >= '2025-01-01';
    
    Plan A (खराब): Orders full scan, Customer full scan,
                  nested loop join
    Plan B (अच्छा): Orders(date) पर index use,
                   hash join with Customer
    
    PostgreSQL / MySQL में plan देखें:
      EXPLAIN ANALYZE SELECT ...
  4. प्रकार:

    A. Join algorithms:

    Algorithm कब अच्छा
    Nested loop join छोटी outer, indexed inner।
    Block nested loop Index नहीं, memory-limited।
    Hash join बड़ी tables, equality join।
    Sort-merge join Inputs पहले से sorted या order चाहिए।

    B. Optimization phases:

    Phase उद्देश्य
    Parsing Syntax + semantic checks; parse tree।
    Logical rewrite Relational algebra transformations; predicate pushdown; view expansion।
    Physical planning Access paths, join algorithms, join order चुनें।
    Cost estimation Statistics से I/O + CPU estimate; सबसे सस्ता चुनें।
    Execution Chuna gaya plan चलाएँ; results।

    C. Heuristics: Selections नीचे push करें; जल्दी project करें; Cartesian products से बचें; selective हो तो index use करें; छोटी relations पहले join करें।

  5. लाभ:
    • Performance: Plans में orders of magnitude फर्क।
    • Declarative: User क्या लिखता है, कैसे नहीं।
    • Adaptive: Statistics current-data choices देते हैं।
    • Transparent: EXPLAIN से inspect और tune।
    • Extensible: नए algorithms और indexes plug in।
  6. नुकसान:
    • Statistics drift: Stale stats खराब plans।
    • Cost model imperfect: Correlated columns, skewed data भ्रमित करते हैं।
    • Planning time: Complex queries में milliseconds।
    • Hint dependence: कभी-कभी hints ज़रूरी।
    • Parameter sniffing: एक parameter के लिए tuned plan दूसरे को नुकसान।
  7. विशेषताएँ:
    • Cost-based: Lowest estimated cost वाला plan।
    • Rules + cost: Heuristics search सीमित करते हैं; cost best चुनता है।
    • Statistics: Row counts, distinct values, histograms, index height।
    • Search space pruning: सिर्फ promising join orders explore।
    • Plan cache: Identical queries के plans reuse।
  8. आरेख: Query optimization pipeline
        SQL text
           │
           ▼
        Parser  →  Parse Tree
           │
           ▼
        Rewriter  →  Logical Plan (relational algebra)
           │
           ▼
        Optimizer
           │  ├── Statistics (table, columns, indexes)
           │  ├── Cost model  (I/O + CPU + network)
           │  ├── Search (join orders, algorithms, access paths)
           │  └── Lowest cost plan चुनें
           │
           ▼
        Physical Plan
           │
           ▼
        Executor  →  Results
    
        EXPLAIN output (सरलीकृत):
    
          Hash Join  (cost=… rows=…)
            ├─ Seq Scan on Customer
            └─ Index Scan on Orders (date >= …)
  9. निष्कर्ष: Query optimization ही SQL को magical बनाता है — वही declarative query efficiently execute होती है बिना user को plan बताए। Optimizer statistics, cost model और search heuristics से plan चुनता है। Performance problems आने पर पहला कदम EXPLAIN से plan देखना, statistics up-to-date verify करना, और यह check करना कि plan वे indexes use कर रहा है जो आप expect करते हैं। कभी fix बेहतर index है; कभी query rewrite; कभी hint। Plans पढ़ना सीखें — database performance tuning का यह सबसे valuable skill है।
  10. अभ्यास:
    1. अपने DBMS में एक simple join पर EXPLAIN चलाकर join algorithm पहचानिए।
    2. एक ही query के plans index के साथ और बिना compare कीजिए।
    3. Predicate pushdown एक उदाहरण के साथ समझाइए।
    4. बताइए कब hash join nested loop join से बेहतर है।
    5. तीन कारण list कीजिए जिनसे optimizer खराब plan चुन सकता है।

16. NoSQL & Modern Databases – Types, CAP, Use Cases

English

  1. Problem: Relational databases excel at structured data and strong consistency, but modern applications often face challenges they were not designed for: massive write throughput (IoT, logs), huge scale-out across many servers, flexible schemas (evolving product catalogs), and graph-shaped data (social networks). Insisting on a single relational schema became a bottleneck. A family of alternative databases emerged to address these needs.
  2. Definition: NoSQL ("Not only SQL") is a broad category of databases that do not use the traditional relational model. They prioritise horizontal scalability, flexible schema, and specific data models: document, key-value, column-family, and graph. Modern NewSQL databases keep SQL and ACID but add horizontal scalability. CAP theorem describes the trade-off between Consistency, Availability, and Partition tolerance.
  3. Example: Choosing a database for different needs:
    -- Document (MongoDB): flexible JSON-like documents
    db.users.insertOne({
      name: "Amit",
      emails: ["a@x.com", "amit@y.com"],
      address: { city: "Delhi" }
    });
    
    -- Key-Value (Redis):
    SET session:123 "user_id=42"
    GET session:123
    
    -- Column-family (Cassandra):
    CREATE TABLE events (user_id UUID, ts TIMESTAMP,
                         event TEXT, PRIMARY KEY (user_id, ts));
    
    -- Graph (Neo4j):
    MATCH (a:Person)-[:FRIEND]->(b:Person)
    WHERE a.name = 'Amit' RETURN b.name;
  4. Types:

    A. NoSQL categories:

    Category Model Examples Best For
    Document JSON/BSON docs MongoDB, CouchDB Catalogs, CMS, user profiles
    Key-value Map of key → value Redis, DynamoDB, Riak Sessions, cache, queues
    Column-family Rows with flexible columns Cassandra, HBase, ScyllaDB Time series, IoT, logs
    Graph Nodes + edges + properties Neo4j, JanusGraph Social, recommendations, fraud
    Search Inverted index Elasticsearch, Solr Full-text search, analytics
    Time-series Timestamped data InfluxDB, TimescaleDB Metrics, IoT, monitoring

    B. CAP theorem: Under a network partition, choose either CP (Consistency + Partition tolerance) or AP (Availability + Partition tolerance). You cannot have all three.

    C. NewSQL: CockroachDB, Google Spanner, TiDB — SQL + ACID + horizontal scaling.

  5. Advantages:
    • Horizontal scalability: Add nodes to handle more load.
    • Flexible schema: Add fields without migrations.
    • High write throughput: Sharded by design (Cassandra, DynamoDB).
    • Specialised queries: Graph traversal, full-text, time series.
    • Latency: In-memory (Redis) gives sub-millisecond reads.
    • Availability: AP systems stay online during partitions.
  6. Disadvantages:
    • Weaker consistency: Eventual consistency is common.
    • Limited query language: No standard SQL (though improving).
    • No joins in many stores: Denormalisation required.
    • Operational complexity: Distributed systems to manage.
    • Ecosystem: Fewer tools compared to RDBMS.
    • Eventual consistency surprises: Applications must handle stale reads.
  7. Characteristics:
    • BASE model: Basically Available, Soft state, Eventual consistency.
    • Sharding: Data partitioned by key across nodes.
    • Replication: Multiple copies for durability and availability.
    • Denormalisation: Precomputed, duplicated data for fast reads.
    • Schema-on-read: Structure applied by the application.
    • Polyglot persistence: Use different DBs for different jobs.
  8. Diagram: CAP and polyglot persistence
        CAP Theorem:
    
            Consistency
                 ▲
                ╱ ╲
               ╱   ╲
              ╱ CA  ╲
             ╱  (RDBMS)╲
            ╱            ╲
       CP  ╱──────────────╲  AP
          ╱ MongoDB, Redis ╲ Cassandra,
         ╱  HBase            ╲ DynamoDB
        ▼────────────────────▼
           Partition Tolerance
    
        Polyglot persistence:
    
          App → Users      → PostgreSQL (ACID)
              → Sessions   → Redis
              → Catalog    → MongoDB
              → Metrics    → InfluxDB
              → Social     → Neo4j
  9. Conclusion: NoSQL databases are not a replacement for relational — they are complementary. Choose based on the workload: RDBMS for structured, transactional data with complex queries; document stores for flexible JSON; key-value for caching and sessions; column-family for high-write time series; graph for connected data; search for full-text; time-series for metrics. Understand the CAP trade-off and design applications to tolerate eventual consistency where appropriate. Modern architecture often combines several databases (polyglot persistence) and increasingly adopts NewSQL for the best of both worlds.
  10. Exercise:
    1. List the four main NoSQL categories with one example each.
    2. Explain the CAP theorem with a diagram and examples.
    3. Compare MongoDB and PostgreSQL for a product catalog.
    4. Describe three workloads where a time-series database is preferable.
    5. Design a polyglot persistence architecture for a social app.

हिंदी (सरल)

  1. समस्या: Relational databases structured data और strong consistency में बेहतरीन हैं, पर modern applications अक्सर ऐसी चुनौतियों से मिलती हैं जिनके लिए वे नहीं बनी थीं: massive write throughput (IoT, logs), कई servers पर scale-out, flexible schemas (evolving product catalogs), और graph-shaped data (social networks)। एक ही relational schema पर अड़े रहना bottleneck बन गया। इन ज़रूरतों के लिए alternative databases की family उभरी।
  2. परिभाषा: NoSQL ("Not only SQL") databases की एक broad category है जो traditional relational model use नहीं करती। ये horizontal scalability, flexible schema और specific data models को priority देती हैं: document, key-value, column-family, और graph। आधुनिक NewSQL databases SQL और ACID रखते हुए horizontal scalability जोड़ते हैं। CAP theorem Consistency, Availability और Partition tolerance के trade-off को describe करता है।
  3. उदाहरण: अलग-अलग ज़रूरतों के लिए database चुनना:
    -- Document (MongoDB): flexible JSON-like documents
    db.users.insertOne({
      name: "अमित",
      emails: ["a@x.com", "amit@y.com"],
      address: { city: "दिल्ली" }
    });
    
    -- Key-Value (Redis):
    SET session:123 "user_id=42"
    GET session:123
    
    -- Column-family (Cassandra):
    CREATE TABLE events (user_id UUID, ts TIMESTAMP,
                         event TEXT, PRIMARY KEY (user_id, ts));
    
    -- Graph (Neo4j):
    MATCH (a:Person)-[:FRIEND]->(b:Person)
    WHERE a.name = 'अमित' RETURN b.name;
  4. प्रकार:

    A. NoSQL categories:

    Category Model Examples Best For
    Document JSON/BSON docs MongoDB, CouchDB Catalogs, CMS, user profiles।
    Key-value Map of key → value Redis, DynamoDB, Riak Sessions, cache, queues।
    Column-family Flexible columns वाली rows Cassandra, HBase, ScyllaDB Time series, IoT, logs।
    Graph Nodes + edges + properties Neo4j, JanusGraph Social, recommendations, fraud।
    Search Inverted index Elasticsearch, Solr Full-text search, analytics।
    Time-series Timestamped data InfluxDB, TimescaleDB Metrics, IoT, monitoring।

    B. CAP theorem: Network partition में या CP (Consistency + Partition tolerance) चुनें या AP (Availability + Partition tolerance)। तीनों एक साथ नहीं।

    C. NewSQL: CockroachDB, Google Spanner, TiDB — SQL + ACID + horizontal scaling।

  5. लाभ:
    • Horizontal scalability: Load के लिए nodes जोड़ें।
    • Flexible schema: बिना migration fields जोड़ें।
    • High write throughput: Design से sharded (Cassandra, DynamoDB)।
    • Specialised queries: Graph traversal, full-text, time series।
    • Latency: In-memory (Redis) sub-millisecond reads।
    • Availability: AP systems partitions में भी online।
  6. नुकसान:
    • कमज़ोर consistency: Eventual consistency आम।
    • Limited query language: Standard SQL नहीं (सुधर रहा है)।
    • कई stores में joins नहीं: Denormalisation ज़रूरी।
    • Operational complexity: Distributed systems manage करने पड़ते हैं।
    • Ecosystem: RDBMS से कम tools।
    • Eventual consistency surprises: Applications को stale reads संभालने पड़ते हैं।
  7. विशेषताएँ:
    • BASE model: Basically Available, Soft state, Eventual consistency।
    • Sharding: Key से data nodes में partitioned।
    • Replication: Durability और availability के लिए कई copies।
    • Denormalisation: तेज़ reads के लिए precomputed, duplicated data।
    • Schema-on-read: Structure application लगाती है।
    • Polyglot persistence: अलग कामों के लिए अलग DBs।
  8. आरेख: CAP और polyglot persistence
        CAP Theorem:
    
            Consistency
                 ▲
                ╱ ╲
               ╱   ╲
              ╱ CA  ╲
             ╱  (RDBMS)╲
            ╱            ╲
       CP  ╱──────────────╲  AP
          ╱ MongoDB, Redis ╲ Cassandra,
         ╱  HBase            ╲ DynamoDB
        ▼────────────────────▼
           Partition Tolerance
    
        Polyglot persistence:
    
          App → Users      → PostgreSQL (ACID)
              → Sessions   → Redis
              → Catalog    → MongoDB
              → Metrics    → InfluxDB
              → Social     → Neo4j
  9. निष्कर्ष: NoSQL databases relational का replacement नहीं — complementary हैं। Workload के आधार पर चुनें: structured, transactional data और complex queries के लिए RDBMS; flexible JSON के लिए document stores; caching और sessions के लिए key-value; high-write time series के लिए column-family; connected data के लिए graph; full-text के लिए search; metrics के लिए time-series। CAP trade-off समझें और applications को eventual consistency tolerate करने लायक design करें जहाँ उपयुक्त हो। Modern architecture अक्सर कई databases combine करती है (polyglot persistence) और NewSQL को adopt कर रही है दोनों दुनियाओं का best पाने के लिए।
  10. अभ्यास:
    1. चार मुख्य NoSQL categories और हर एक का उदाहरण दीजिए।
    2. CAP theorem diagram और उदाहरणों के साथ समझाइए।
    3. Product catalog के लिए MongoDB और PostgreSQL की तुलना कीजिए।
    4. तीन workloads बताइए जहाँ time-series database बेहतर है।
    5. Social app के लिए polyglot persistence architecture design कीजिए।