Overview
Chapter: Database Concepts (Class 11, Informatics Practices) Introduction: This chapter introduces the fundamentals of databases — organized collections of interrelated data — and the software that manages them (DBMS/RDBMS). It distinguishes data from information and shows how databases support efficient storage, retrieval, manipulation and sharing of data in multi-user environments. Importance: Understanding databases is essential for building information systems used in schools, businesses and government. Knowledge of database concepts reduces data redundancy, enforces data integrity, enables concurrent access, improves security and forms the foundation for learning SQL and application development. Key themes: core database terminology (database, DBMS, RDBMS), advantages of DBMS, architecture and components of DBMS, data models (especially relational model), schema vs instance, keys and integrity constraints, Entity-Relationship (ER) modelling, normalization (removing redundancy), and database languages (DDL, DML, DCL, TCL). The chapter also touches on transaction management, backup/recovery and basic security concepts. What the student will learn: students will be able to…
Learning Objectives
- Define basic database terms such as data, database, DBMS, RDBMS, schema, table, field, and record.
- Explain the purpose and functions of a DBMS and distinguish it from file-based data storage.
- Describe different types of database relationships (one-to-one, one-to-many, many-to-many) and represent them in ER diagrams.
- State the concepts of primary key, candidate key, foreign key and referential integrity with examples.
- Identify common data types and column constraints (NOT NULL, UNIQUE, CHECK, DEFAULT) used in table design.
- Demonstrate creation and modification of simple table structures using CREATE TABLE and ALTER TABLE statements.
- Construct basic SQL queries using SELECT with WHERE, ORDER BY, DISTINCT and LIMIT clauses to retrieve required data.
- Write SQL statements for data manipulation: INSERT, UPDATE and DELETE, and explain their effects on tables.
Topics in this chapter
15 topics · tap a topic title to jump straight to it.
Introduction to Database
What is a Database? A database is an organized collection of related data stored so it can be accessed, managed and updated easily. It removes redundancy, improves consistency and supports fast retrieval.
What is a DBMS? A Database Management System (DBMS) is software that interacts with users, applications, and the database to capture and analyze data. Examples: MySQL, PostgreSQL, SQLite, Oracle.
- Basic terms (Relational model focus)
- Relation (Table): A table with rows and columns.
- Tuple: A single row in a table (one record).
- Attribute: A column in a table (a field).
- Degree: Number of attributes (columns) in a relation.
- Cardinality: Number of tuples (rows) in a relation.
- Keys & Constraints
- Primary Key: Uniquely identifies a tuple in a table.
- Candidate Key: A minimal attribute set that can be a primary key.
- Foreign Key: Attribute(s) in one table that reference a primary key in another table (enforces referential integrity).
- Integrity constraints: Rules (like NOT NULL, UNIQUE, FK relationships) preserving correctness of data.
- Operations & Queries
- CRUD: Create (INSERT), Read (SELECT), Update (UPDATE), Delete (DELETE).
- Basic relational algebra operators: Selection (σ), Projection (π), Join (⋈), Union (∪), Difference (−), Cartesian product (×).
- Why use a Database?
- Reduces data redundancy and inconsistency.
- Makes data sharing and concurrent access safe.
- Supports backups, recovery and security.
- Enables powerful querying and reporting.
- Normalization (brief)
- 1NF: Atomic (no repeating groups).
- 2NF: 1NF + no partial dependency on part of a composite key.
- 3NF: 2NF + no transitive dependency (non-key attributes depend only on key).
Simple SQL example (read student names from Student table):
SELECT name, roll_no FROM Student WHERE class = '11';
Important distinction: Data are raw facts (e.g., '25', 'Alice'); Information is processed data that is meaningful (e.g., 'Alice scored 25 in Maths').
- Library management: Tables for Books, Members, Loans. Loan table uses foreign keys to reference BookID and MemberID to track who borrowed which book and when.
- Banking: Customer, Account, Transaction tables. Transactions table records deposits/withdrawals linked to Account via AccountID.
- University student records: Students, Courses, Enrollments. Enrollment implements many-to-many between Students and Courses.
- Hospital information system: Patients, Doctors, Appointments, Prescriptions. Appointments link Patients and Doctors with dates.
- E-commerce website: Products, Customers, Orders, OrderItems. OrderItems connects Orders to multiple Products with quantity and price.
- Degree (n) = number of attributes (columns) in a relation
- Cardinality (m) = number of tuples (rows) in a relation
- Record size (bytes) = sum of sizes of all fields in a record (approx.)
- File size (bytes) = Record size × Number of records
- Number of records = File size / Record size (useful for storage estimates)
- Cartesian product size = m × n (if R has m tuples and S has n tuples)
File Processing Systems vs DBMS
Overview
A File Processing System stores data in separate files. Programs are written to read, write and update these files directly. A Database Management System (DBMS) is specialized software that stores, manages and provides controlled access to a centralized collection of related data (a database).
File Processing Systems — Key characteristics
- Data stored in independent files (flat files, text, CSV, binary).
- High redundancy: same data duplicated in multiple files.
- Data inconsistency due to duplicates and isolated updates.
- Program–data dependence: changes in file format often require program changes.
- Poor support for concurrent access, security, backup/recovery and complex queries.
DBMS — Key characteristics
- Centralized/shared database that many applications use.
- Minimizes redundancy by normalization and controlled schema.
- Enforces integrity constraints (e.g., primary keys, foreign keys).
- Provides data independence: logical/physical changes need not affect applications.
- Supports concurrency control, transactions (ACID), security, backup & recovery and powerful query languages (SQL).
Direct comparison (short)
| Feature | File Processing System | DBMS |
|---|---|---|
| Data organization | Independent files | Centralized, related tables |
| Redundancy | High | Low (after normalization) |
| Data consistency | Hard to maintain | Maintained via constraints |
| Concurrent access | Poor | Supported (locking, transactions) |
| Security & Recovery | Limited | Robust |
| Querying | Programmed ad hoc | Declarative SQL queries |
When to use which
- File systems can be acceptable for small, single-purpose applications with simple data and few users.
- DBMS is preferred for multi-user applications, large datasets, complex queries, and when data integrity and security are important (e.g., banks, hospitals, e-commerce).
Important concepts connected to DBMS
- ACID properties: Atomicity, Consistency, Isolation, Durability — ensure reliable transactions.
- Normalization: process to remove redundancy by organizing tables and relationships.
- Indexing: data structure to speed up searches (e.g., B-tree, hashing).
- School report cards: In a file system, each teacher maintains separate student files leading to many duplicates. In a DBMS, one centralized student table stores student details and separate tables store marks, attendance—queries can generate consolidated report cards.
- Banking: Using files for accounts can lead to inconsistent balances and poor concurrency when multiple tellers update the same account. A DBMS provides transactions and locking to ensure correct concurrent updates and ACID guarantees.
- Library management: With flat files every book and member record may be duplicated across branches. A DBMS centralizes books, members and loans producing accurate availability and faster searches.
- Retail (inventory): File-based systems require manual reconciliation of stock across stores. A DBMS maintains up-to-date inventory, supports complex queries like 'top-selling products' and enables simultaneous sales across outlets.
- E-commerce websites: Require fast searches, joins across customers/orders/products, concurrency and secure storage — DBMS is mandatory; file systems are inadequate.
- Storage required = number_of_records × record_size (bytes). Example: 10,000 records × 200 bytes = 2,000,000 bytes (~1.9 MB).
- Linear search time (file processing, no index) ≈ n × t_r, where n = number of records and t_r = time to examine one record (O(n)).
- Binary search time (sorted file with binary search) ≈ log2(n) × t_comp (O(log n)).
- Indexed search (balanced tree index, e.g., B-tree) ≈ O(log n); Hash index average ≈ O(1) for key lookups.
- Redundancy ratio (%) = (size_of_duplicate_data / total_data_size) × 100
DBMS and RDBMS
DBMS (Database Management System)
A DBMS is software that stores, retrieves and manages data in databases. It provides an interface between users/applications and the physical data, handling data storage, retrieval, security, backup and concurrency.
- Components: Storage manager, query processor, transaction manager, metadata/catalog, authorization manager.
- Functions: Data definition, data manipulation, security, integrity, backup & recovery, concurrency control.
RDBMS (Relational Database Management System)
An RDBMS is a DBMS that implements the relational model (tables/relations). Data is organized into tables of rows (tuples) and columns (attributes). Relationships among tables are defined using keys.
- Key concepts: Tables (relations), rows (records/tuples), columns (attributes), primary key, foreign key, constraints.
- Query language: SQL (Structured Query Language) for creating, querying and modifying relational data.
Important relational features
- Keys: Primary key uniquely identifies a row. Foreign key creates a link between tables.
- Relationships: One-to-one, One-to-many, Many-to-many (often implemented with a junction table).
- ACID properties: Atomicity, Consistency, Isolation, Durability — they ensure reliable transactions.
- Normalization: Process of organizing data to reduce redundancy and avoid anomalies (1NF, 2NF, 3NF are commonly taught at Class 11 level).
DBMS vs RDBMS — quick comparison
- DBMS: Can use file-based or non-relational structures; may allow duplicate records and complex storage formats. Examples: some simple file-based systems, early DBMSs.
- RDBMS: Uses structured tables, enforces relationships and constraints, supports SQL, usually supports ACID transactions. Examples: MySQL, PostgreSQL, Oracle, SQL Server.
Common SQL examples
-- Create a table CREATE TABLE Students (RollNo INT PRIMARY KEY, Name VARCHAR(50), Class VARCHAR(10)); -- Insert INSERT INTO Students VALUES (1, 'Asha', '11A'); -- Join example (Students + Marks) SELECT s.Name, m.Subject, m.Marks FROM Students s JOIN Marks m ON s.RollNo = m.RollNo;
Why learn DBMS/RDBMS?
Most applications (websites, banks, schools, e-commerce) need persistent, consistent and queryable storage. RDBMS provides a well-defined, scalable and robust way to store and manage such structured data.
- Library system: Books table, Members table, Issue table (Many-to-many via Issue). RDBMS enforces integrity (no issuing non-existent book) and supports queries like 'which member borrowed this book?'.
- School database: Students, Classes, Teachers, Attendance. Use primary keys for student IDs and foreign keys to link attendance records to students.
- E-commerce: Customers, Products, Orders, OrderItems. A single Order linked to many OrderItems implements one-to-many relationship.
- Banking: Accounts, Customers, Transactions. ACID properties ensure money transfers are atomic and consistent.
- Hospital: Patients, Doctors, Appointments. Relational tables help avoid duplicate patient records and keep treatment history consistent.
- Storage size (approx) = number_of_rows * average_row_size
- Maximum possible tuples (if each attribute has domain size d_i) = Π d_i (product of domain sizes)
- Cartesian join size = n1 * n2 (n1, n2 are row counts of two tables) Equijoin estimate (simplified) ≈ (n1 * n2) / max(distinct_values_in_join_column_table1, distinct_values_in_join_column_table2)
- Redundancy percentage = (redundant_records / total_records) * 100
- Normalization rule (1NF): Each attribute must be atomic (no repeating groups). 2NF/3NF are expressed via functional dependencies: 2NF removes partial dependency on part of a composite key; 3NF removes transitive dependencies.
Database Models
What is a Database Model?
A database model is a way to organize, store and represent data and the relationships between data in a database system. A model defines the logical structure and rules by which data can be created, stored, retrieved and updated. Different models suit different application needs (performance, complexity, relationships, data types).
Major Database Models (with brief characteristics)
- Hierarchical model – Data is organized in a tree-like structure (parent-child). Each child has one parent. Good for one-to-many relationships.
- Network model – Flexible graph-like structure where records can have many-to-many relationships via sets (edges). More complex pointers than hierarchical.
- Relational model – Data organized in tables (relations) of rows (tuples) and columns (attributes). Relationships are represented using keys. Most widely used (SQL databases).
- Object-oriented model – Data represented as objects (like in OOP): encapsulates attributes and methods. Useful when behavior and complex data types matter.
- Document (NoSQL) model – Stores semi-structured data (JSON, XML documents). Flexible schema; good for hierarchical and variable data.
- Key–Value model – Simple pairs (key → value). Very fast for simple lookups (caching, session stores).
- Graph model – Data represented as nodes and edges; ideal for highly connected data (social networks, route planning).
Key concepts common to models
- Entity / Record: a real-world object represented in the database (e.g., Student).
- Attribute / Field: property of an entity (e.g., Roll_No, Name).
- Relationship: how entities are related (one-to-one, one-to-many, many-to-many).
- Key: attribute(s) that uniquely identify a record (primary key, candidate key, foreign key).
- Schema vs Instance: schema is the structure/definition; instance is the actual data at a moment.
When to choose which model?
- Relational: general business applications, ACID transactions, structured data.
- Document/Key–Value: flexible, evolving schemas, web apps, caching, high write/read throughput.
- Graph: relationships are first-class—social networks, recommendation engines, fraud detection.
- Hierarchical/Network: older systems and some specialized legacy applications; hierarchical fits clear tree structures.
Example mapping (simple)
Consider a university: Relational model represents Students, Courses and Enrollments as tables linked by keys. A graph model would represent Students and Courses as nodes with ENROLLED_IN edges (good for shortest-path or recommendation queries). A document model could store a Student with an embedded list of enrolled courses in a single JSON document.
- Hierarchical: File system directories (folders contain files and subfolders) — tree parent-child structure.
- Network: Telecommunications routing where nodes (switches) connect to many other nodes (many-to-many).
- Relational: Banking system where Customer, Account and Transaction are tables linked by keys (use SQL).
- Object-oriented: CAD/CAM or multimedia applications storing complex objects with methods and relationships.
- Document (NoSQL): Online store product catalogs stored as JSON documents (varying attributes per product).
- Key–Value: Session storage or caching (e.g., Redis) where session_id → session_data is stored and retrieved quickly.
- Relation degree = number of attributes (columns) in a table; degree = n
- Relation cardinality = number of tuples (rows) in a table; cardinality = m
- Possible tuples (upper bound) = product of domain sizes: |D1| × |D2| × ... × |Dn|
- Functional dependency notation: A → B means attribute(s) A uniquely determine B (used in normalization).
- Relational algebra (common operators): σ (selection), π (projection), × (Cartesian product), ⋈ (join), ∪ (union), − (difference), ρ (rename)
- Example relational algebra expression: Students ⋈ Enrollments (on StudentID) to get student-course pairs
Relational Model (Relations and Tables)
What is the Relational Model?
The relational model represents data as relations. A relation is conceptually a table consisting of rows and columns. Each row is a tuple (one record) and each column is an attribute (a named property). The relational model provides a simple, mathematical foundation for storing and querying structured data.
Key terms
- Relation schema: R(A1, A2, ..., An) — the name of the relation and its attributes.
- Instance: A specific set of tuples (rows) in the relation at a moment in time.
- Attribute: A named column. Each attribute has a domain (set of valid values).
- Tuple: A single row — an ordered set of attribute values.
- Degree (arity): Number of attributes (columns) in a relation, often written n.
- Cardinality: Number of tuples (rows) in a relation, often written as |R|.
- Primary key: An attribute or set of attributes that uniquely identifies each tuple in a relation.
- Candidate key: A minimal superkey (possible primary key).
- Foreign key: An attribute in one relation that refers to the primary key of another relation (used to represent relationships).
Important properties of relations
- Attributes (columns) have atomic values from their domains (no repeating groups).
- Tuples are unordered — the order of rows does not matter.
- Attributes are unordered — the order of columns is not significant for the model.
- No duplicate tuples — every tuple in a relation must be unique.
- Null values may be used to represent missing or unknown information (care needed in queries).
Integrity constraints
- Entity integrity: Primary key attributes cannot be NULL.
- Referential integrity: A foreign key must either be NULL or match a primary key value in the referenced relation.
Relational algebra (basic operations)
- Selection (σ): choose rows that satisfy a condition — σ_condition(R)
- Projection (π): choose columns — π_attr1,attr2,...(R)
- Union (∪), Set difference (−), Intersection (∩): set operations on compatible relations
- Cartesian product (×): combine each row of one relation with each row of another
- Join (⋈): combine related rows from two relations using a condition (often equality of keys)
Example relation (Student)
| StudentID (PK) | Name | Class | DOB |
|---|---|---|---|
| S101 | Asha | 11A | 2007-03-12 |
| S102 | Ravi | 11B | 2007-09-05 |
Here StudentID is the primary key (uniquely identifies each student). A separate table (e.g., Enrollment) can store which students are enrolled in which subjects; it will use StudentID as a foreign key to relate to the Student table.
Relation schema vs relation instance
Relation schema is the structure (attribute names and types). Relation instance is the current set of tuples that conform to that schema.
Why use the relational model?
- Simple, tabular representation that is easy to understand and query.
- Mathematically well-defined operations (relational algebra) enable powerful queries and optimizations.
- Integrity constraints support data consistency (keys and referential integrity).
Short workflow example (how relations model real systems)
To model a library: create relations such as Book(BookID PK, Title, Author, Year), Member(MemberID PK, Name, Contact), Borrow(BorrowID PK, BookID FK, MemberID FK, BorrowDate, ReturnDate). Use joins to list which member has borrowed which book, and use selection to find overdue books.
- Student and Enrollment: Student(StudentID PK, Name, Class). Enrollment(EnrollID, StudentID FK, Subject, Grade). Use StudentID as foreign key in Enrollment to link each enrollment to a student.
- E-commerce: Customer(CustomerID PK, Name, Email), Orders(OrderID PK, CustomerID FK, Date), OrderItems(OrderItemID, OrderID FK, ProductID FK, Quantity). Join Customer and Orders to get all orders by a customer.
- Library system: Book(BookID PK, Title, Author), Member(MemberID PK, Name), Borrow(BorrowID PK, BookID FK, MemberID FK, BorrowDate). Referential integrity ensures a Borrow record always references an existing Book and Member.
- Class timetable: Timetable(Class, Day, Period, Subject, Teacher). Use composite key (Class, Day, Period) to ensure only one subject-teacher pair is scheduled per slot.
- Degree (arity) of relation R = number of attributes = n
- Cardinality of relation R = number of tuples = |R|
- Relation schema notation: R(A1, A2, ..., An)
- Tuple membership: t ∈ R (t is a tuple in relation R)
- Functional dependency: X → Y (values of X determine values of Y)
- Entity integrity: PRIMARY_KEY ≠ NULL
Attributes and Domains
Attributes are the named properties or characteristics of an entity (or relation) that describe it. In a table (relation), attributes correspond to columns (fields). Each attribute has a name and every tuple (row) gives a value for that attribute.
Attribute components:
- Attribute name — the column name (e.g., RollNo, StudentName).
- Attribute value — the actual value for a tuple (e.g., 102, "Anita").
- Domain — the set of all permissible values for an attribute (explained below).
Types of attributes:
- Simple (atomic) — cannot be divided further (e.g., Age, Salary).
- Composite — made up of subparts (e.g., Address can be Street, City, PIN).
- Single-valued — exactly one value per tuple (e.g., DateOfBirth).
- Multi-valued — may have multiple values (e.g., PhoneNumbers for a person).
- Derived — value computed from other attributes (e.g., Age derived from DateOfBirth).
- NULL — indicates unknown, unavailable or not applicable value.
- Key attribute — uniquely identifies a tuple (e.g., StudentID as primary key).
Domain (definition): The domain of an attribute is the set of all valid values that the attribute can take. A domain is characterized by data type, allowable range, format, and constraints (for example: INTEGER 1..100, VARCHAR(50), DATE in yyyy-mm-dd).
Domain properties and constraints:
- Data type: integer, float, string, date, boolean, etc.
- Range/size: numeric ranges or maximum lengths (e.g., Age 0–120, Name length ≤ 50).
- Format: pattern constraints (e.g., email: user@domain).
- Integrity constraints: NOT NULL, UNIQUE, PRIMARY KEY, CHECK conditions.
- Default values: a value used when none is provided.
Why attributes and domains matter:
- Ensure data integrity and consistency by restricting values to meaningful sets.
- Enable validation at data-entry time (prevent invalid types/formats).
- Support query optimization and correct results (e.g., meaningful comparisons).
- Define keys and relationships between tables (domains must be compatible for foreign keys).
How attributes and domains appear in a relation schema: A relation schema R(A1:D1, A2:D2, ..., An:Dn) lists attributes Ai together with their domains Di. Each tuple t in relation R must satisfy t[Ai] ∈ Di for every attribute Ai.
- Student database: Attributes — StudentID (domain: integer, positive, unique), Name (domain: string, max length 50), DOB (domain: date yyyy-mm-dd), Gender (domain: {M, F, O}), PhoneNumbers (multi-valued, domain: string matching phone pattern).
- Library system: Book entity attributes — ISBN (domain: 13-digit string, unique), Title (string), Author (string or multi-valued), CopiesAvailable (domain: integer ≥ 0), PublishedYear (domain: integer, e.g., 1500..2025).
- Employee table: EmpID (primary key, integer), EmpName (string), Salary (domain: decimal ≥ 0), DeptID (foreign key whose domain must match Dept table's DeptID domain), JoiningDate (date).
- E-commerce product: ProductID (string), Price (domain: decimal > 0), Category (domain: set {Electronics, Clothing, Books, ...}), Ratings (multi-valued or aggregated numeric).
- Domain membership: For relation R and attribute A with domain D(A), for every tuple t in R: t[A] ∈ D(A).
- \[Maximum possible number of distinct tuples in relation R with attributes A1..An: ≤ ∏_{i=1..n} |D(Ai)| (product of domain cardinalities).\]
- Uniqueness constraint for primary key K: ∀ t1,t2 ∈ R, t1 ≠ t2 ⇒ t1[K] ≠ t2[K].
- Functional dependency notation (attributes X determine Y): X → Y. This means for any two tuples t1 and t2, if t1[X] = t2[X] then t1[Y] = t2[Y].
Keys
What is a Key?
In a database relation (table), a key is an attribute or a set of attributes that uniquely identifies a tuple (row). Keys enforce uniqueness and help maintain data integrity and relationships between tables.
Essential properties of a key
- Uniqueness: No two distinct rows can have the same key value(s).
- Minimality: A key contains no extra attribute; removing any attribute destroys the uniqueness property (applies to candidate keys).
- Non-null (usually): A primary key must not contain NULL values (ensures identification).
Types of Keys
- Superkey: A set of one or more attributes that, taken together, can uniquely identify a tuple in a relation. (May contain extra attributes.)
- Candidate key: A minimal superkey — no subset of it is also a superkey. A relation can have multiple candidate keys.
- Primary key: A chosen candidate key used as the main identifier for tuples in a table. Typically declared in SQL with PRIMARY KEY.
- Composite (Compound) key: A key that consists of two or more attributes combined to uniquely identify a tuple (e.g., (student_id, course_id)).
- Alternate key: Any candidate key that is not chosen as the primary key.
- Unique key: An attribute or set of attributes that must be unique across tuples but can allow a single NULL (behavior depends on DBMS).
- Foreign key: An attribute (or set) in one table that refers to the primary key of another table; enforces referential integrity.
- Surrogate key: System-generated key (like auto-increment ID) with no business meaning, used to uniquely identify tuples.
Relation to Functional Dependency
If attribute set A functionally determines all attributes of relation R (A → R), then A is a superkey for R. If A → R and A is minimal, A is a candidate key.
How to choose a Primary Key (practical rules)
- Prefer single-attribute keys that are stable and immutable (e.g., student roll number) over attributes that can change (e.g., address).
- Avoid attributes with business meaning that might change; use surrogate keys if natural keys are unstable or composite keys are large.
- Primary keys should be short (for indexing efficiency) and never NULL.
Example table notation
For a Student table: <Student> (roll_no PK, name, dob, class, address) — here roll_no is the primary key and is underlined in ER diagrams.
Why keys matter
Keys enforce uniqueness, enable fast lookup (indexes), maintain relationships across tables (foreign keys), and are essential for normalization and query correctness.
- Student table: roll_no as Primary Key (unique for each student).
- Library books: ISBN is a natural Primary Key for the Book table; copies may use (ISBN, copy_number) as a Composite Key.
- Course registration: Enrollment table uses a Composite Key (student_id, course_id) to record which students register for which courses.
- Employee table: employee_id (Surrogate Primary Key) while email might be an Alternate/Unique Key.
- Orders: OrderLine table uses Composite Key (order_id, product_id); order_id is a Foreign Key referencing Orders(order_id).
- Uniqueness definition: For key K of relation R, for any two tuples t1 and t2 in R, if t1[K] = t2[K] then t1 = t2.
- Functional dependency: A → B means attribute set A functionally determines B. If A → all attributes of R then A is a Superkey.
- Candidate key condition: A is a candidate key ⇔ (A → R) AND (no proper subset of A → R).
- Composite key: K = {A1, A2, ..., An} where combined values uniquely identify tuples.
- SQL declarations: PRIMARY KEY(column1[, column2,...]); FOREIGN KEY(col) REFERENCES OtherTable(col).
Integrity Constraints and Rules
Integrity constraints are rules applied to database tables to ensure accuracy, consistency and validity of data. They prevent invalid or inconsistent data from being entered and help maintain relationships among tables. Constraints are enforced by the DBMS automatically when data is inserted, updated or deleted.
Why they matter: They guarantee data quality, enforce business rules, avoid duplicates, maintain relationships (e.g., parent/child tables), and protect referential consistency.
Common types of integrity constraints
- Domain constraint: Values stored in a column must come from a predefined set or type (data type, range, format). Example: age must be integer between 0 and 120. SQL example:
age INT CHECK (age BETWEEN 0 AND 120). - Entity (or row) integrity: Each row must be uniquely identifiable. Implemented by declaring a primary key. Rule: primary key value cannot be NULL and must be unique. SQL example:
PRIMARY KEY (student_id). - Key constraint: Ensures uniqueness of certain columns (candidate key, unique key). SQL example:
UNIQUE (email). - Referential integrity: Foreign key values in a child table must match primary key values in the parent table (or be NULL if allowed). Also includes actions like ON DELETE CASCADE. SQL example:
FOREIGN KEY (course_id) REFERENCES courses(course_id) ON DELETE CASCADE. - NOT NULL constraint: Prevents NULL values in a column. SQL example:
name VARCHAR(50) NOT NULL. - CHECK constraint: Enforces a specific condition on column values. SQL example:
salary DECIMAL CHECK (salary >= 0). - Default values: Provide a default if none is supplied. SQL example:
status VARCHAR(10) DEFAULT 'active'. - Business rules and triggers: Complex rules that cannot be expressed by standard constraints can be enforced with triggers or application logic (for example, limit total loan amount per customer). Triggers execute procedural code on insert/update/delete.
How constraints are enforced: On INSERT, UPDATE and DELETE the DBMS checks relevant constraints. If a constraint would be violated, the operation is rejected (or a specified action is taken, like cascading deletes).
Best practices: define appropriate primary and foreign keys, use domain and check constraints to stop invalid entries early, prefer DB-level constraints over relying solely on application checks, and document business rules clearly.
- Student database: student(student_id PRIMARY KEY, name NOT NULL, age INT CHECK (age BETWEEN 5 AND 25)). Enrollment(enroll_id, student_id FOREIGN KEY REFERENCES student(student_id), course_id). Referential integrity ensures an enrollment cannot reference a non-existent student.
- Bank accounts: Account(account_no PRIMARY KEY, balance DECIMAL CHECK (balance >= 0)). Transaction table uses account_no as foreign key; triggers may ensure withdrawals do not make balance negative.
- Library system: Book(book_id PRIMARY KEY), Borrow(borrow_id, book_id FOREIGN KEY REFERENCES Book(book_id) ON DELETE RESTRICT, member_id FOREIGN KEY REFERENCES Member(member_id)). ON DELETE RESTRICT prevents deleting a book that is currently borrowed.
- Inventory: Product(product_id PRIMARY KEY, price DECIMAL CHECK (price > 0)), Stock(product_id FOREIGN KEY REFERENCES Product(product_id), quantity INT DEFAULT 0 CHECK (quantity >= 0)). Domain and check constraints keep quantities and prices valid.
- Domain constraint: For each tuple t in relation R and attribute A, t.A belongs to Domain(A). Written: ∀t ∈ R, t.A ∈ Dom(A).
- Entity integrity: Primary key must be unique and not null. ∀t1,t2 ∈ R, if t1.PK = t2.PK then t1 = t2; and ∀t ∈ R, t.PK ≠ NULL.
- Referential integrity: For child relation C with foreign key FK referencing parent P with primary key PK: ∀t ∈ C, t.FK = NULL OR t.FK ∈ π_PK(P).
- Unique constraint: ∀t1,t2 ∈ R, if t1[U] = t2[U] then t1 = t2, where U is a set of attributes declared UNIQUE.
- CHECK constraint example (salary): ∀t ∈ Employee, t.salary >= 0.
- SQL constraint patterns: CREATE TABLE Employee (id INT PRIMARY KEY, email VARCHAR(50) UNIQUE, salary DECIMAL CHECK (salary >= 0), dept_id INT, FOREIGN KEY (dept_id) REFERENCES Dept(id) ON DELETE SET NULL);
Schemas, Instances and Three-Level Architecture
Overview
In DBMS, a schema is the structure or design of the database (its metadata). An instance (or state) is the actual data in the database at a particular moment. The Three‑Level Architecture separates database description and access into three abstraction levels — Internal (physical), Conceptual (logical) and External (view) — to provide data independence and simplify application development.
Schemas vs Instances
- Schema: A formal definition of the database. It describes entities, attributes, types, relationships, constraints and views. Schemas change rarely (schema evolution).
- Instance: A snapshot of the data that conforms to the schema. Instances change frequently (insert/update/delete).
- Example notation: relation schema R(A1:Type1, A2:Type2, ...). An instance r(R) is the set of tuples {t1, t2, ..., tn} that satisfy R.
Three‑Level Architecture
- Internal Level (Physical Schema): How data are physically stored (files, indexes, encryption, storage paths). It is concerned with performance, storage structures and access methods.
- Conceptual Level (Logical/Conceptual Schema): Global logical view of the entire database; contains definitions of entities, attributes, relationships, integrity constraints, and data types independent of physical storage.
- External Level (Views / User Schemas): Multiple user views of the database tailored to application or user needs. Each external schema shows a subset or a transformed view of the conceptual schema.
Data Independence
- Physical (or Internal) Data Independence — changes in the internal level (storage structures, indexing) should not require changes to the conceptual schema or external views.
- Logical (or Conceptual) Data Independence — changes in the conceptual schema (adding/removing attributes, relations) should not require changes to external views or application programs (as long as the external view requirements are preserved).
How a Query Travels
A user issues a query against an external view; the DBMS maps the external request to the conceptual schema, then to the internal schema for execution; results are mapped back to the external view.
Why this matters (benefits)
- Hides physical complexity from users and programmers.
- Supports multiple user views tailored to different needs.
- Enables evolution of storage and logical design with minimal application impact.
Simple Concrete Example (in HTML form)
Conceptual schema:
Student(ID:int, Name:string, Class:int, DOB:date)Instance (snapshot):
Student = { (101, 'Anita', 11, '2008-02-12'),
(102, 'Ravi', 12, '2007-05-03') }
An external view for teachers might show only (ID, Name, Class) while an external view for admin might include DOB and parents' contact info (if present in conceptual schema). - Library Management: Conceptual schema defines Books(ISBN, Title, Author), Members(MemID, Name, Phone). An instance is the current set of book and member records. External views: member view (shows checked-out books per member), librarian view (shows overdue list). Internal level: file layout, indexes on ISBN for fast lookup.
- University: Conceptual schema includes Student, Course, Enrollment relations. Instances are current enrollment rows. Department staff see only students of their department (external view). Changes to storage (e.g., adding an index) should not change the enrollment view.
- Online Store: Conceptual schema with Products, Orders, Customers. Customer-facing website uses an external view (product catalog and order history). Warehouse system uses another view (stock levels, SKU locations). Physical storage and replication strategies are hidden from both views.
- Banking: Conceptual schema holds Accounts(AccountNo, Balance, Holder). Teller application shows account balance and transaction history (external view). Internal level manages secure storage, encryption and logs. Schema updates (adding a new field 'account_type') should not break the ATM interface if the external view is preserved.
- Relation schema: R(A1:Type1, A2:Type2, ..., An:TypeN)
- Instance of R: r(R) = { t1, t2, ..., tm } where each t is a tuple conforming to R
- Cardinality of instance: |r(R)| = m (number of tuples/rows in the relation instance)
- Primary key constraint: ∀ t1,t2 ∈ r(R), t1[PK] ≠ t2[PK]
- Mappings (conceptual): f_internal→conceptual and f_conceptual→external (abstract mapping functions used by DBMS to transform requests/results between levels)
Normalization (Introduction)
What is Normalization?
Normalization is a systematic process in database design to organize tables and their relationships to reduce redundancy and eliminate undesirable characteristics like insertion, update and deletion anomalies. It uses concepts of functional dependency and keys to split a large table into smaller, related tables while preserving data and dependencies.
Why normalize?
- Remove data redundancy (avoid storing same data in many places).
- Prevent anomalies: update anomaly (inconsistent updates), insertion anomaly (can't add data without other data), deletion anomaly (deleting needed data unintentionally).
- Improve data integrity and make maintenance easier.
Key concepts
- Attribute – a column in a table.
- Tuple – a row in a table.
- Primary key – an attribute (or set) that uniquely identifies tuples.
- Functional dependency (FD) – X → Y means attribute(s) X determine attribute(s) Y.
- Candidate key – a minimal set of attributes that uniquely identifies tuples.
Normal forms (introductory)
- First Normal Form (1NF): Table has atomic (indivisible) values and each field contains only one value. No repeating groups or arrays in a single column.
- Second Normal Form (2NF): Table is in 1NF and every non-prime attribute is fully functionally dependent on the whole primary key (i.e., no partial dependency on part of a composite key).
- Third Normal Form (3NF): Table is in 2NF and no non-prime attribute is transitively dependent on the primary key (i.e., A → B and B → C means remove transitive dependency so that A directly determines C only if A is a key).
- Boyce–Codd Normal Form (BCNF) (advanced intro): For every FD X → Y, X should be a superkey.
How to normalize (basic steps)
- Ensure table is in 1NF: make values atomic and remove repeating groups.
- Identify primary key(s) and all functional dependencies.
- If there is a partial dependency (non-prime attribute depends on part of composite key), decompose into smaller tables to achieve 2NF.
- If there is a transitive dependency (non-prime attribute depends on another non-prime attribute), decompose to achieve 3NF.
- Verify lossless join and preservation of dependencies after decomposition.
Short example (conceptual)
Consider a table STUDENT_COURSE(student_id, student_name, course_id, course_name, instructor). If course_name and instructor repeat for many students, we split into STUDENT(student_id, student_name), COURSE(course_id, course_name, instructor) and ENROLLMENT(student_id, course_id). This removes redundancy and anomalies.
- Student enrollment: A single table storing student details and course details leads to repeated course names and instructors. Normalization splits this into STUDENT, COURSE and ENROLLMENT tables so course data is stored once.
- Library system: Table with (BookID, BookTitle, AuthorName, Publisher, BorrowerID, BorrowerName). Normalizing separates BOOK(BookID, BookTitle, AuthorID), AUTHOR(AuthorID, AuthorName), BORROWER(BorrowerID, BorrowerName), ISSUE(BookID, BorrowerID, IssueDate).
- Employee-project assignment: EMP_PROJ(EmployeeID, EmployeeName, ProjectID, ProjectName, Manager). Normalize into EMPLOYEE(EmployeeID, EmployeeName), PROJECT(ProjectID, ProjectName, ManagerID), MANAGER(ManagerID, ManagerName), ASSIGN(EmployeeID, ProjectID).
- Online orders: ORDERS(OrderID, CustomerName, CustomerAddress, ProductID, ProductName, Quantity). Normalize into CUSTOMER, PRODUCT and ORDER and ORDER_LINE tables to avoid repeating customer and product info.
- Functional dependency: X → Y (attributes X determine attributes Y).
- Attribute closure: X+ = set of attributes functionally determined by X (used to find keys).
- Partial dependency (definition): For composite key (A,B), attribute C has partial dependency if A → C or B → C (C depends on part of key).
- Transitive dependency (definition): A → B and B → C implies A → C; if B is non-prime this causes violation of 3NF.
- 1NF condition: All attributes atomic (no repeating groups).
- 2NF condition: 1NF + no partial dependencies of non-prime attributes on part of a composite key.
Entity-Relationship (ER) Model
What is the ER Model?
The Entity-Relationship (ER) Model is a high-level conceptual data model used to describe the data requirements and structure of a database in a simple, intuitive way. It models real-world objects (entities), their properties (attributes), and the associations between them (relationships). ER models are commonly represented as ER diagrams (ERDs).
Core components
- Entity: An object or thing in the real world with independent existence (e.g., Student, Book, Account). Represented by a rectangle in ER diagrams.
- Entity set: A collection of similar entities (e.g., all Students).
- Attribute: A property that describes an entity (e.g., StudentID, Name, DOB). Represented by an ellipse.
- Key attribute: An attribute (or set of attributes) that uniquely identifies an entity in an entity set (e.g., StudentID).
- Relationship: An association among two or more entities (e.g., Student ENROLLS_IN Course). Represented by a diamond.
- Relationship set: A collection of similar relationships.
Types of attributes
- Simple (atomic): Indivisible value (e.g., Age).
- Composite: Can be divided into subparts (e.g., Name -> First, Middle, Last).
- Multi-valued: Can have multiple values (e.g., PhoneNumbers). Shown as a double ellipse.
- Derived: Computed from other attributes (e.g., Age from DOB). Shown as a dashed ellipse.
Types of relationships (by degree)
- Unary (recursive): Relationship among instances of the same entity (e.g., Employee supervises Employee).
- Binary: Between two entity sets (most common) (e.g., Student - Course).
- Ternary (or n-ary): Between three or more entity sets (e.g., Supplier supplies Part to Project).
Cardinality constraints describe how many instances of one entity can be associated with instances of another:
- One-to-One (1:1): Each entity A relates to at most one B and vice versa.
- One-to-Many (1:N): One A can relate to many B, but a B relates to at most one A.
- Many-to-Many (M:N): Many A can relate to many B.
Participation constraints
- Total (mandatory) participation: Every entity in the entity set must participate in the relationship (shown by a double line).
- Partial (optional) participation: Some entities may not participate (single line).
Weak entity and identifying relationship
A weak entity cannot be uniquely identified by its own attributes alone and depends on a strong (owner) entity. Drawn as a double rectangle; the identifying relationship is a double diamond. Example: Dependent depends on Employee.
Higher-level constructs
- Generalization / Specialization: Represents inheritance: a general entity (e.g., Person) and specialized sub-entities (e.g., Student, Teacher).
- Aggregation: Treats a relationship as an abstract entity to express relationships involving relationships.
ER Diagram notation summary
- Rectangle: Entity
- Ellipse: Attribute (double = multi-valued; dashed = derived)
- Underline attribute name: Key attribute
- Diamond: Relationship (double diamond: identifying)
- Double rectangle: Weak entity
- Lines: Link entities to attributes and relationships; double line for total participation
- Crow's-foot or cardinality numbers may be used to show 1, N, M etc.
Steps to design an ER model
- Identify entities from the problem statement.
- List attributes and identify primary keys.
- Find relationships between entities and determine cardinality and participation.
- Identify weak entities, composite/multi-valued/derived attributes.
- Draw the ER diagram and review for completeness and correctness.
Why ER Model?
It helps communicate database structure to users and developers, forms the basis for relational schema design, and ensures data requirements are captured before implementation.
- Student-Course: Entities: Student (StudentID, Name, DOB), Course (CourseID, Title). Relationship: ENROLLS_IN (grade). Cardinality: Student to Course is Many-to-Many (M:N) — solved by an associative entity Enrollment with attributes (StudentID, CourseID, Grade).
- Library System: Entities: Book (BookID, Title, Author), Member (MemberID, Name), Issue (IssueID, IssueDate, ReturnDate). Issue is a weak/associative entity linking Book and Member; cardinality: Member can issue many Books (1:N), Book can be issued many times over time (1:N) — Issue ties a specific member & copy to dates.
- Bank: Entities: Branch (BranchID, Name), Account (AccountNo, Balance), Customer (CustomerID, Name). Relationship: Customer OWNS Account (1 Customer can own many Accounts — 1:N). Account has a composite attribute HolderName (First, Last).
- Hospital: Entities: Doctor (DoctorID), Patient (PatientID), Appointment (AppointmentID, Date, Time). Relationship: Doctor schedules Appointment with Patient (Doctor-Patient-Appointment can be modeled as a ternary or via Appointment as an associative entity).
- Employee-Manager (recursive): Entity: Employee (EmpID, Name). Relationship: MANAGES (an employee manages other employees). This is a unary (recursive) relationship; cardinality might be 1:N (one manager can manage many employees).
- Entity set E = {e1, e2, e3, ...} where each ei is an entity instance.
- Relationship set R ⊆ E1 × E2 (for a binary relationship between entity sets E1 and E2). For n-ary: R ⊆ E1 × E2 × ... × En.
- Attribute as a function: A: E → Dom(A) (each entity maps to a value in attribute domain).
- Key definition: K ⊆ Attributes such that ∀e1, e2 ∈ E, e1 ≠ e2 ⇒ projection_K(e1) ≠ projection_K(e2).
- Cardinality examples expressed formally: - 1:1 between A and B: ∀a ∈ A, |{b | (a,b) ∈ R}| ≤ 1 and ∀b ∈ B, |{a | (a,b) ∈ R}| ≤ 1. - 1:N from A to B: ∀b ∈ B, |{a | (a,b) ∈ R}| ≤ 1 (each B links to at most one A); A may link to many B. - M:N: no such single-side restriction; many-to-many.
Components and Services of a DBMS
Overview: A Database Management System (DBMS) is software that stores, retrieves and manages data in databases. To do this reliably and efficiently it is made up of several internal components and provides many user-oriented services. Understanding these components and services helps you see how DBMS ensures data integrity, security, concurrency and recoverability.
Major Components:
- Database Engine / Storage Manager: Core component that handles actual reading/writing of data on disk, buffer management, file organization and indexing. It implements storage structures and access methods.
- Query Processor: Accepts and processes queries (usually SQL). It includes a parser, query optimizer (to choose efficient execution plans), and query executor.
- DDL Compiler / Data Dictionary (Catalog) Manager: Processes Data Definition Language (DDL) commands (CREATE, ALTER, DROP) and stores metadata (schema, table definitions, indexes, constraints) in the data dictionary.
- DML Compiler / Interpreter: Translates Data Manipulation Language (DML) statements (INSERT, UPDATE, DELETE, SELECT) into low-level instructions the engine can execute.
- Transaction Manager: Ensures ACID properties for transactions. It controls transaction begin/commit/rollback, concurrency control and coordinates with recovery manager.
- Concurrency Control Manager: Manages concurrent access by multiple users/processes to prevent conflicts and ensure consistency (techniques include locking, timestamp ordering, optimistic concurrency control).
- Recovery Manager: Provides backup and recovery mechanisms so the database can be restored after failures (uses logs, checkpoints, undo/redo operations).
- Authorization & Integrity Manager: Enforces security (authentication and access control) and integrity constraints (primary key, foreign key, unique, check constraints) declared on data.
- Utilities: Tools for loading data, import/export, performance monitoring, reorganization, and backup.
Key Services Provided by a DBMS:
- Data Abstraction & Independence: Separates logical schema from physical storage so applications are insulated from changes in storage structures (logical and physical data independence).
- Data Definition & Manipulation: Allows users to define schemas (DDL) and manipulate data (DML) using standard languages like SQL.
- Data Security & Authorization: Controls which users can perform which operations on which data (roles, privileges, grants).
- Integrity Enforcement: Ensures correctness of data via constraints and triggers.
- Transaction Management (ACID): Atomicity, Consistency, Isolation, Durability ensure reliable transaction processing even under failures and concurrency.
- Concurrency Control: Allows multiple users to access the database concurrently without leading to inconsistent data.
- Backup & Recovery: Periodic backups and recovery procedures to restore the database after crashes, media failures or human errors.
- Performance & Query Optimization: Optimizer chooses efficient query plans; indexing and caching improve response times.
- Data Dictionary / Metadata Management: Central repository of schema information used by DBMS internals and users.
How components work together (short flow): User issues SQL → Parser/DDL or DML compiler checks syntax → Query optimizer chooses execution plan using catalog statistics → Storage manager reads/writes data using indexes & buffer manager → Transaction & concurrency managers ensure ACID and isolation → Recovery manager logs actions for durability and crash recovery.
CBSE-class-level note: Focus on understanding what each component does and how services like ACID, security, backup and query optimization help real applications (banks, libraries, hospitals) keep data correct and available.
- Banking system: Transaction manager and concurrency control ensure multiple tellers can update accounts safely; recovery manager and logs allow rollbacks after failures.
- Library management: Data dictionary stores book and member schemas; queries find available books; integrity constraints prevent borrowing more books than allowed.
- Online shopping: Query optimizer and indexes speed up searches for products; authentication and authorization manage user accounts and purchases.
- Hospital records: Security and access control restrict patient data to authorized doctors; backups and recovery protect patient history from data loss.
- University management: DDL defines tables for students, courses and enrollments; referential integrity enforces valid enrollments (foreign keys).
- Cardinality (|R|): Number of tuples (rows) in relation R.
- Disk blocks required = ceil((record_size_bytes * number_of_records) / block_size_bytes).
- Selectivity of predicate P = (number of rows satisfying P) / (total number of rows). Lower selectivity → more effective filter.
- Estimate of equi-join size: |R ⋈ S| ≈ (|R| * |S|) / max(V(R,A), V(S,A)) where V(R,A) is number of distinct values of attribute A in R.
- Simple cost model (conceptual): cost(plan) ≈ I/O_cost + CPU_cost. DBMS optimizers compare such costs to pick plans.
Transactions, Concurrency and Recovery
Overview
A transaction is a logical unit of work on a database — a sequence of one or more operations (reads/writes) that must be executed as a single unit. Transactions ensure correctness when multiple operations together change the database (for example, transferring money between bank accounts).
ACID properties
- Atomicity: All operations of a transaction succeed together or the system rolls back to the state before the transaction started.
- Consistency: A transaction transforms the database from one valid state to another, preserving all integrity constraints.
- Isolation: Concurrent transactions do not interfere with each other; the effect is as if transactions were executed serially.
- Durability: Once a transaction commits, its changes survive subsequent failures.
Transaction states (brief)
Typical states: active → partially committed → committed or on error → failed → aborted → terminated. Visualize as a simple directed-state diagram.
Why concurrency control is needed
Databases allow many users to run transactions at the same time to improve resource use and response time. Without control, concurrent execution may produce incorrect results because operations interleave in harmful ways.
Typical concurrency problems
- Lost update: Two transactions read the same value, both update it, and one update overwrites the other.
- Dirty read: A transaction reads data written by another uncommitted transaction that later aborts.
- Unrepeatable read: A transaction reads the same item twice and finds different values because another committed transaction modified it in between.
- Phantom read: A transaction re-executes a query and finds new rows inserted by another committed transaction.
Concurrency control techniques
- Locking
- Shared (S) lock: many transactions may read concurrently but cannot write.
- Exclusive (X) lock: only one transaction can write (and read if exclusive prevents others).
- Two-Phase Locking (2PL): A transaction has a growing phase (acquires locks) and a shrinking phase (releases locks). 2PL guarantees serializability if strictly followed.
- Timestamp ordering: Each transaction gets a timestamp; conflicts are resolved using timestamps so that the schedule respects timestamp order.
- Optimistic concurrency control: Transactions execute without locks and validate at commit; if conflict is detected, a transaction is rolled back.
- Deadlock handling: Detect (e.g., wait-for graph and cycle detection) and resolve (abort one transaction), or prevent (timeout, ordering of resource acquisition).
Serializability
A concurrent schedule is serializable if its outcome is equivalent to some serial execution of the same transactions. One common test uses a precedence (conflict) graph: if the graph has no cycles, the schedule is conflict-serializable.
Recovery: purpose and methods
Recovery ensures the database can be restored to a correct state after failures (system crash, power failure, disk error). Key ideas:
- Transaction rollback/abort: Undo changes of a failed transaction so the database remains consistent.
- Write-Ahead Logging (WAL): All changes are first recorded in a log (with enough information to undo and/or redo) before being applied to the database. Logs survive crashes.
- Checkpoints: Periodic snapshots of progress (and log positions) to reduce recovery time — recovery only needs to process logs after the last checkpoint.
- Recovery phases (typical modern approach): Analysis (find transactions active at crash), Redo (reapply committed changes from log), Undo (rollback effects of uncommitted transactions).
- Backup and restore: Use backups plus log replay to restore a consistent state.
Putting it together
ACID + Concurrency control + Recovery mechanisms together ensure that transactions behave correctly even in presence of concurrent users and failures. For example, locking (or timestamping) provides isolation and serializability; logging plus checkpoints provide durability and recovery.
Further notes for Class 11
Focus on understanding definitions, common concurrency problems with simple examples, the idea of locks and 2PL, the role of logs and checkpoints in recovery, and how ACID properties are preserved by these mechanisms.
- Bank transfer: T1 subtracts 500 from A, T2 adds 500 to B. If operations interleave poorly, money can be lost — locks or transactions ensure atomic transfer.
- Online shopping inventory: Two customers try to buy the last item simultaneously. Concurrency control prevents selling the same item twice (locks or atomic check-and-update).
- Booking system (airline/theatre): Prevents double-booking of a seat by making reservation steps a transaction and using locking or optimistic checks.
- Multiplayer game leaderboard update: Concurrent updates to scores must be synchronized to avoid lost updates; logs help restore correct state after a server crash.
- ATM withdrawals: If one transaction fails after debiting but before commit, rollback ensures customer’s balance is not incorrectly reduced.
- Throughput = Number of committed transactions / Total time (transactions per second)
- Average response time = (Sum of response times of transactions) / Number of transactions
- Abort rate = Number of aborted transactions / Number of started transactions
- Utilization = Busy time of DB server / Total time period
- Approximate recovery time = Restore time (from backup) + Redo time (reapplying committed log records) + Undo time (rolling back uncommitted transactions)
- Serializability test (graph rule): A schedule is conflict-serializable if and only if its precedence/conflict graph has no cycles (not a numeric formula but an important condition).
Query Languages and Operations (Introductory)
What are Query Languages?
A query language is a formal language used to request information from a database. It lets users retrieve, insert, update and delete data. In relational databases the two main forms are relational algebra (a procedural, mathematical way) and SQL (Structured Query Language — declarative and widely used).
Core ideas and operations
- Selection (filter) — choose rows that satisfy a condition (relational algebra σ, SQL WHERE).
- Projection (choose columns) — return only specified columns (relational algebra π, SQL SELECT list).
- Union, Intersection, Difference — set operations that combine results from two compatible queries (relational: ∪, ∩, −; SQL: UNION, INTERSECT, EXCEPT/MINUS).
- Cartesian Product — combine every row of one table with every row of another (relational: ×). Often used as a step for joins.
- Join — combine rows from two tables based on a related column (INNER JOIN, LEFT/RIGHT/FULL OUTER JOIN in SQL).
- Rename — change the name/alias of relation or attributes (relational: ρ, SQL: AS).
Relational algebra vs SQL
Relational algebra provides the theoretical foundation — operations produce new relations from existing ones. SQL is a high-level language that expresses what to get (not how). Database engines translate SQL into execution plans that use relational-algebra-like operations.
Typical SQL query structure
Most common pattern: SELECT <columns or expressions> FROM <table(s)> WHERE <conditions> GROUP BY <columns> HAVING <group conditions> ORDER BY <columns>
Example workflow
To answer the question “Which students scored above 80 in Mathematics?” the DBMS does: read Students and Scores tables → filter rows for Mathematics and marks > 80 (selection) → choose student name and marks (projection) → possibly join Students and Scores on student_id (join).
Why learn these operations?
- They let you build precise queries to get exactly the data you need.
- Understanding them helps optimise queries and reason about results (avoid duplicates, reduce data transfer, use indexes).
- Relational algebra gives the formal tools used by query optimisers inside RDBMS.
Common pitfalls and tips
- For multiple tables always specify join conditions — otherwise you may get a very large Cartesian product.
- Use projection to return only needed columns (reduces network/processing cost).
- Use WHERE to filter early — fewer rows speed up later operations (join/group by).
- Be mindful of duplicates: SQL SELECT returns duplicates unless you use DISTINCT.
A short glossary
- Predicate — a condition that evaluates to true/false (used in WHERE/σ).
- Tuple — a row/record in a relation (table).
- Attribute — a column in a relation.
- Library: Find titles and authors of books published after 2015. SQL: SELECT title, author FROM Books WHERE year > 2015;
- School: List names of students who obtained marks > 80 in Maths. SQL: SELECT S.name, M.marks FROM Students S JOIN Marks M ON S.roll_no = M.roll_no WHERE M.subject = 'Mathematics' AND M.marks > 80;
- E‑commerce: Show product name and price for electronics under ₹5000 sorted by price. SQL: SELECT name, price FROM Products WHERE category = 'Electronics' AND price < 5000 ORDER BY price ASC;
- Bank: Get all transactions for account 12345 between two dates. SQL: SELECT date, amount, type FROM Transactions WHERE account_no = 12345 AND date BETWEEN '2025-01-01' AND '2025-06-30';
- Set operation: Combine two customer lists (no duplicates). SQL: SELECT email FROM Customers2023 UNION SELECT email FROM Customers2024;
- Selection (relational algebra): σ_condition(Relation) — example: σ_marks>80(Marks)
- Projection (relational algebra): π_attributes(Relation) — example: π_name,marks(σ_subject='Maths'(Marks))
- Cartesian product: R × S — pairs every tuple of R with every tuple of S
- \[Join (natural/conditional): R ⋈_{R.a = S.b} S — SQL equivalent: SELECT * FROM R JOIN S ON R.a = S.b\]
- Union/Intersection/Difference: R ∪ S, R ∩ S, R − S — SQL: UNION, INTERSECT, EXCEPT/MINUS
- Typical SQL pattern: SELECT <columns> FROM <table(s)> WHERE <condition> GROUP BY <columns> HAVING <group_condition> ORDER BY <columns>
Advantages and Disadvantages of DBMS
Definition: A Database Management System (DBMS) is software that enables creation, storage, retrieval, update and administration of databases. It acts as an interface between users/applications and the physical database, providing tools to manage data efficiently and securely.
Advantages:
- Reduced Data Redundancy: DBMS centralizes data storage, avoiding multiple copies of the same data. This saves storage and reduces inconsistencies. (Example: Customer details stored once and referenced by different applications.)
- Improved Data Integrity and Consistency: Constraints (primary keys, foreign keys, checks) ensure data follows rules and remains consistent across the system. (Example: Referential integrity prevents orphan records in orders and customers.)
- Data Security: Access control, authentication and authorization restrict who can view or modify data. (Example: Only HR can access salary columns.)
- Concurrent Access and Transaction Management: DBMS supports multiple users simultaneously while ensuring transactions follow ACID properties (Atomicity, Consistency, Isolation, Durability). This prevents conflicts and data corruption. (Example: Two bank tellers updating accounts safely.)
- Backup and Recovery: Built-in mechanisms automatically back up data and restore it after failures, reducing data loss risk. (Example: Point-in-time recovery after hardware failure.)
- Data Independence: Applications are insulated from physical data storage changes; schema changes can be handled by the DBMS without rewriting application code extensively.
- Powerful Querying and Reporting: Using query languages (SQL) complex data retrieval, aggregation and reports are easy to implement and optimize.
- Centralized Management and Standards: Policies, formats and access rules are uniformly enforced across the organization.
- Scalability: Modern DBMSs scale to large volumes of data and many users using indexing, partitioning and distributed architectures.
Disadvantages:
- Cost and Complexity: Setting up and administering a DBMS requires investment in software, hardware and skilled personnel. Small/simple applications may find the overhead unjustified.
- Performance Overhead: General-purpose DBMS features (security, concurrency control, logging) can add overhead; poorly designed schemas or missing indexes degrade performance.
- Single Point of Failure: If the central database server fails and there is no proper redundancy, many applications can be affected. (Mitigation: replication, clustering.)
- Vendor Lock-in: Using proprietary DBMS features can make migrating to another system costly and time-consuming.
- Maintenance Requirements: Regular tuning, backups, upgrades and security patches are necessary; requires trained DBAs.
- Security Risks if Misconfigured: A centralized DBMS is attractive to attackers; misconfiguration or weak policies can cause large breaches.
- Complex Migration and Integration: Integrating legacy systems or migrating large datasets can be difficult and error-prone.
Conclusion: A DBMS provides strong advantages for most medium-to-large applications by improving integrity, security, sharing and management of data. The decision to use one should weigh the operational benefits against costs, complexity and performance needs, and should include proper planning for backups, security and scaling.
- Banking system: Centralized customer accounts, transaction history and concurrency control prevent double withdrawal and ensure consistent balances.
- Airline reservation system: Shared seat inventory and transactions ensure that two agents cannot book the same seat concurrently.
- University student database: Single repository for student records, marks and attendance accessible to departments and administration with role-based access.
- E-commerce platform: Product catalog, inventory, orders and user profiles are managed centrally to support search, recommendations and reporting.
- Hospital management: Patient records, prescriptions, lab results and appointments stored centrally to enable coordinated care and secure access.
- Social media: User profiles, posts, relationships and messages managed in a DBMS (or distributed DB systems) to support fast queries and privacy controls.
- Storage size (bytes) = record_size (bytes) × number_of_records
- Redundancy reduction (%) = ((old_storage - new_storage) / old_storage) × 100
- Maximum number of unordered pairs (possible relationships) among n entities = n × (n - 1) / 2
- Search complexity without index = O(N); with balanced index (B-tree) ≈ O(log N)
- Approximate B-tree height h ≈ log_base_b (N), where b is branching factor and N is number of entries (used to estimate index lookup steps)
Key Concepts
- Database
- An organized collection of related data stored electronically for efficient retrieval and management.
- DBMS
- Database Management System — software that creates, manages and provides controlled access to databases.
- RDBMS
- Relational DBMS — a DBMS that stores data in tables (relations) and supports operations based on relational algebra.
- Table (Relation)
- A set of rows and columns where each row is a record and each column is an attribute; represents a relation.
- Row (Tuple)
- A single record in a table representing one instance of the entity described by the table.
- Column (Attribute)
- A field in a table that stores a particular type of data for all records (rows).
- Primary Key
- An attribute or set of attributes that uniquely identifies each row in a table.
- Foreign Key
- An attribute in one table that references the primary key of another table to establish a relationship.
- Candidate Key
- An attribute or minimal set of attributes that can uniquely identify rows; a table can have multiple candidate keys.
- Superkey
- Any set of attributes that uniquely identifies rows in a table; may include extra attributes beyond a candidate key.
- Composite Key
- A primary key made up of two or more attributes used together to uniquely identify a record.
- Index
- A data structure that improves the speed of data retrieval operations on a table column or set of columns.
- Schema
- The structure or blueprint of a database describing tables, columns, data types and relationships.
- Entity
- A real-world object or concept about which data is stored (e.g., person, product, event).
- ER Diagram
- Entity-Relationship diagram — a graphical representation of entities, their attributes and relationships.
- Normalization
- Process of organizing tables to reduce redundancy and improve data integrity using normal forms (1NF, 2NF, 3NF...).
- Functional Dependency
- A relationship where one attribute's value uniquely determines another attribute's value (A → B).
- SQL
- Structured Query Language — standard language for querying and manipulating relational databases.
- Transaction
- A sequence of one or more database operations treated as a single logical unit that must fully succeed or fail.
- ACID properties
- Set of properties ensuring reliable transactions: Atomicity, Consistency, Isolation, Durability.
End-of-Chapter Trial Paper & Test Questions
Topic-wise questions to test your understanding of every concept in this chapter.
-
Distinguish between data and information with an example. / उदाहरण सहित डेटा और सूचना में अंतर कीजिए।
Show answer
Data are raw, unprocessed facts such as '25' or 'Alice', while information is processed, meaningful data such as 'Alice scored 25 in Maths'. Information results from organizing and interpreting data. / डेटा कच्चे, असंसाधित तथ्य हैं जैसे '25' या 'Alice', जबकि सूचना संसाधित, अर्थपूर्ण डेटा है जैसे 'Alice ने गणित में 25 अंक प्राप्त किए'। सूचना डेटा को व्यवस्थित और व्याख्यायित करने से प्राप्त होती है।
-
List any three advantages a DBMS has over a traditional file processing system. / पारंपरिक फ़ाइल प्रसंस्करण प्रणाली पर DBMS के कोई तीन लाभ सूचीबद्ध कीजिए।
Show answer
A DBMS reduces data redundancy through a controlled centralized schema, maintains data consistency and integrity through constraints, and supports safe concurrent access with transactions and security, unlike isolated files with high duplication. / DBMS एक नियंत्रित केंद्रीकृत स्कीमा के माध्यम से डेटा अतिरेक घटाता है, बाधाओं के माध्यम से डेटा संगति और अखंडता बनाए रखता है, और लेन-देन व सुरक्षा के साथ सुरक्षित समवर्ती पहुँच का समर्थन करता है, जबकि पृथक फ़ाइलों में उच्च दोहराव होता है।
-
Differentiate between a candidate key, a primary key and a foreign key. / उम्मीदवार कुंजी (candidate key), प्राथमिक कुंजी (primary key) और विदेशी कुंजी (foreign key) में अंतर कीजिए।
Show answer
A candidate key is a minimal set of attributes that can uniquely identify a tuple; the primary key is the one candidate key chosen as the main identifier and cannot be NULL; a foreign key is an attribute in one table that references the primary key of another table to enforce referential integrity. / उम्मीदवार कुंजी विशेषताओं का न्यूनतम समुच्चय है जो एक टपल को विशिष्ट रूप से पहचान सकता है; प्राथमिक कुंजी मुख्य पहचानकर्ता के रूप में चुनी गई एक उम्मीदवार कुंजी है और NULL नहीं हो सकती; विदेशी कुंजी एक तालिका की विशेषता है जो संदर्भात्मक अखंडता लागू करने हेतु दूसरी तालिका की प्राथमिक कुंजी को संदर्भित करती है।
-
State the rules for entity integrity and referential integrity. / सत्ता अखंडता (entity integrity) और संदर्भात्मक अखंडता (referential integrity) के नियम बताइए।
Show answer
Entity integrity states that no part of a primary key may be NULL, ensuring each tuple is uniquely identifiable. Referential integrity states that a foreign key value must either be NULL or match an existing primary key value in the referenced relation. / सत्ता अखंडता कहती है कि प्राथमिक कुंजी का कोई भाग NULL नहीं हो सकता, जिससे प्रत्येक टपल विशिष्ट रूप से पहचाना जा सके। संदर्भात्मक अखंडता कहती है कि विदेशी कुंजी मान या तो NULL होना चाहिए या संदर्भित संबंध में किसी मौजूदा प्राथमिक कुंजी मान से मेल खाना चाहिए।
-
Define degree and cardinality of a relation. If a Student table has 5 columns and 30 rows, state its degree and cardinality. / किसी संबंध की कोटि (degree) और कार्डिनैलिटी (cardinality) परिभाषित कीजिए। यदि एक Student तालिका में 5 स्तंभ और 30 पंक्तियाँ हैं, तो उसकी कोटि और कार्डिनैलिटी बताइए।
Show answer
Degree is the number of attributes (columns) in a relation and cardinality is the number of tuples (rows). For this Student table, degree = 5 and cardinality = 30. / कोटि किसी संबंध में विशेषताओं (स्तंभों) की संख्या है और कार्डिनैलिटी टपल (पंक्तियों) की संख्या है। इस Student तालिका के लिए कोटि = 5 और कार्डिनैलिटी = 30।
-
What is normalization, and which anomaly is removed by achieving 2NF? / सामान्यीकरण (normalization) क्या है, और 2NF प्राप्त करने से कौन-सी विसंगति दूर होती है?
Show answer
Normalization is the process of organizing tables and relationships to reduce redundancy and avoid insertion, update and deletion anomalies. Achieving 2NF removes partial dependency, where a non-prime attribute depends on only part of a composite primary key. / सामान्यीकरण तालिकाओं और संबंधों को व्यवस्थित करने की प्रक्रिया है ताकि अतिरेक घटे और सम्मिलन, अद्यतन व विलोपन विसंगतियाँ रोकी जा सकें। 2NF प्राप्त करने से आंशिक निर्भरता (partial dependency) दूर होती है, जहाँ एक गैर-प्रमुख विशेषता संयुक्त प्राथमिक कुंजी के केवल एक भाग पर निर्भर होती है।
-
Explain the three levels of the DBMS architecture and which level provides logical data independence. / DBMS आर्किटेक्चर के तीन स्तरों को समझाइए और कौन-सा स्तर तार्किक डेटा स्वतंत्रता प्रदान करता है।
Show answer
The three levels are the internal (physical storage) level, the conceptual (global logical) level, and the external (user views) level. Logical data independence lies between the conceptual and external levels, allowing changes to the conceptual schema without affecting external views or application programs. / तीन स्तर हैं: आंतरिक (भौतिक भंडारण) स्तर, संकल्पनात्मक (वैश्विक तार्किक) स्तर, और बाह्य (उपयोगकर्ता दृश्य) स्तर। तार्किक डेटा स्वतंत्रता संकल्पनात्मक और बाह्य स्तरों के बीच होती है, जो बाह्य दृश्यों या अनुप्रयोग प्रोग्रामों को प्रभावित किए बिना संकल्पनात्मक स्कीमा में परिवर्तन की अनुमति देती है।
-
A many-to-many relationship exists between Students and Courses. How is it represented in the relational model? / Students और Courses के बीच अनेक-से-अनेक (many-to-many) संबंध मौजूद है। इसे संबंधपरक मॉडल में कैसे दर्शाया जाता है?
Show answer
A many-to-many relationship is represented using a separate junction (associative) table, such as Enrollment, which holds foreign keys to both Students and Courses, often as a composite primary key (student_id, course_id). / अनेक-से-अनेक संबंध को एक अलग जंक्शन (साहचर्य) तालिका, जैसे Enrollment, का उपयोग करके दर्शाया जाता है, जो Students और Courses दोनों की विदेशी कुंजियाँ रखती है, प्रायः एक संयुक्त प्राथमिक कुंजी (student_id, course_id) के रूप में।
Related Laws & Principles
Explore allFoundational laws & principles behind this chapter. Each one opens a full page — what it says, why it matters, five practice questions and the mistakes to avoid.