L
LLLOS.ai
Learn
L

Chapter 8 — Relational Databases

Class 12 · Computer Science

Overview

Chapter 8 — Relational Databases Master Diagram

This chapter introduces relational databases — a structured way to store, retrieve and manage interrelated data using tables (relations). It covers core concepts of the relational model (relations, tuples, attributes), keys (primary, candidate, foreign), constraints and integrity rules, and normalization (1NF, 2NF, 3NF) to produce well-designed schemas. Students learn SQL fundamentals (DDL, DML, DCL, TCL) including creating tables, querying data (SELECT, WHERE, JOINs, GROUP BY, ORDER BY), aggregate functions and transactions, plus basic indexing and performance considerations. Practical skills include connecting Python programs to a database (using sqlite3 or a connector), performing CRUD operations, handling exceptions and transactions, and designing simple databases from requirements using ER diagrams. The chapter is important because relational databases underpin most real-world applications — mastering them builds logical design skills, improves data integrity understanding, and prepares students for practical projects and board examinations.

Learning Objectives

  • Define fundamental terms such as relation, tuple, attribute, domain and schema.
  • Explain core relational model concepts including degree, cardinality and relation state.
  • Differentiate between keys: super key, candidate key, primary key, composite key and foreign key.
  • Explain integrity constraints: entity integrity, referential integrity, domain constraints and key constraints.
  • Apply normalization techniques to convert relations into 1NF, 2NF and 3NF to eliminate redundancy and update anomalies.
  • Demonstrate mapping of ER diagrams to relational schemas, handling 1:1, 1:N, M:N relationships and weak entities.
  • Write SQL DDL and DML statements including CREATE TABLE, ALTER TABLE, DROP TABLE, INSERT, UPDATE and DELETE.
  • Construct SQL SELECT queries using WHERE, ORDER BY, GROUP BY, HAVING, DISTINCT and aggregate functions (SUM, AVG, COUNT, MIN, MAX).

Topics in this chapter

14 topics · tap a topic title to jump straight to it.

💻1

Relations

💻 COMPUTER SCIENCE / IT

Relations

Key Point: Relation schema: R(A1, A2, ..., An)

Definition: In a relational database, a relation is a table that represents a set of tuples (rows) having the same attributes (columns). A relation is formally a subset of the Cartesian product of attribute domains.

Components and notation

  • Relation schema: R(A1, A2, ..., An) — the name R and its attributes A1..An.
  • Relation instance: r(R) ⊂ Dom(A1) × Dom(A2) × ... × Dom(An) — a specific set of tuples at a moment in time.
  • Tuple: a single row in the relation, e.g., (v1, v2, ..., vn).
  • Attribute: a column; each attribute Ai has a domain Dom(Ai) (set of allowed values).
  • Degree: number of attributes (n) of the relation.
  • Cardinality: number of tuples (|r|) in the relation instance.

Example relation (STUDENT)

RollNoNameAgeClass
101Rita17XII
102Arun18XII
103Maya17XII

Here degree = 4, cardinality = 3. RollNo is a primary key (unique, non-null).

Key concepts

  • Domain constraint: every attribute value must be from its domain.
  • Entity (primary key) constraint: primary key uniquely identifies tuples; no two tuples have same primary-key value and primary key cannot be NULL.
  • Referential integrity (foreign key): a foreign key in one relation must either be NULL or match a primary key value in the referenced relation.
  • Superkey / Candidate key / Primary key: A superkey is a set of attributes that uniquely identifies tuples. A candidate key is a minimal superkey. One candidate key is chosen as the primary key.
  • Functional dependency: A -> B means if two tuples agree on attribute set A they must agree on attribute B (used in normalization).

Properties of relations

  • Tuples (rows) are unordered; attributes (columns) are unordered.
  • No duplicate tuples are allowed (set semantics).
  • Attribute values are atomic (first normal form requirement).

Basic relational algebra operators (short)

  • Selection: σ(condition)(R) — choose rows satisfying condition.
  • Projection: π(A1, A2,...)(R) — choose columns.
  • Cartesian product: R × S.
  • Join: R ⋈ S (commonly equijoin or natural join).
  • Union: R ∪ S, Difference: R − S, Intersection: R ∩ S.

Why relations are useful: They provide a simple, mathematical, and flexible way to represent structured data; relations + keys + constraints = reliable data storage and powerful query capability (SQL maps directly to relational concepts).

📌 Examples
  • School: STUDENT(RollNo, Name, Age, Class) — RollNo is primary key; ENROLMENT(EnrollID, RollNo, SubjectCode) — RollNo is a foreign key referencing STUDENT.
  • Bank: ACCOUNT(AccountNo, HolderName, Balance) — AccountNo is primary key; TRANSACTION(TxnID, AccountNo, Amount, Date) — AccountNo is a foreign key.
  • Library: BOOK(BookID, Title, Author); ISSUE(IssueID, BookID, MemberID, IssueDate) with BookID and MemberID as foreign keys.
  • E-commerce: CUSTOMER(CustID, Name, Email) and ORDERS(OrderID, CustID, OrderDate) linking customers to their orders (CustID as foreign key).
  • Many-to-many mapping: STUDENT and COURSE with a JOIN table STUDENT_COURSE(StudentID, CourseID) representing enrollment relationships.
🧮 Formulas
  1. \[Relation schema: R(A1\]
    \[A2, ...\]
    \[An)\]
  2. \[Relation instance: r(R) ⊆ Dom(A1) × Dom(A2) × ... × Dom(An)\]
  3. \[Degree = n (number of attributes)\]
    \[Cardinality = |r| (number of tuples)\]
  4. \[Primary key constraint: ∀ t1\]
    \[t2 ∈ r\]
    \[t1[PK] = t2[PK] ⇒ t1 = t2\]
  5. \[Functional dependency: A → B (if two tuples agree on A they must agree on B)\]
  6. \[Selection: σ_condition(R)\]
    \[Projection: π_A1,A2(R)\]
    \[Join: R ⋈ S\]
    \[Cartesian product: R × S\]
💻2

Components of a Relation

💻 COMPUTER SCIENCE / IT

Components of a Relation

Key Point: Relation schema notation: R(A1:D1, A2:D2, ..., An:Dn) where Ai are attributes and Di are domains.

Definition: A relation in a relational database is a set of tuples (rows) having the same attributes (columns). Conceptually it is a table with a name, a heading (attributes and their domains) and a body (the set of tuples).

Main components:

  • Relation name: Identifier for the relation (table) — e.g., Student, Employee.
  • Heading (Schema): The list of attributes (A1, A2, ..., An) and each attribute's domain (possible values). Notation: R(A1:D1, A2:D2, ..., An:Dn).
  • Attributes: Columns of the relation. Attributes are expected to be atomic values (1NF). Example attributes: StudentID, Name, DOB.
  • Domains: A domain Di is the set of allowed values for attribute Ai (e.g., Integer, Date, Varchar(50)).
  • Body (Instance): The current set of tuples (rows) in the relation. Each tuple assigns one value from the domain to each attribute.
  • Tuple (Record): A single row of the relation: t = <v1, v2, ..., vn> where vi ∈ Di.
  • Degree (Arity): Number of attributes in the relation (n).
  • Cardinality: Number of tuples (rows) in the relation, usually denoted |R|.
  • Primary key (Tuple identifier): One or more attributes whose values uniquely identify tuples in the relation. Enforces entity integrity (no duplicate primary-key values, no NULLs in PK).
  • Foreign key: Attribute(s) that reference a primary key in another relation to enforce referential integrity.
  • Null values: A special marker indicating unknown or inapplicable values; allowed but must be handled carefully for constraints and keys.

Properties of a relation (mathematical model):

  • Tuples form a set — no duplicate tuples.
  • Order of tuples is not significant (set semantics).
  • Order of attributes is not significant for the relation as a set (though tables display an order).
  • Every tuple value comes from the domain declared for that attribute.

Short example (HTML table view):

Student (Relation name)
StudentID (PK)NameDOBMajor
1001Asha2004-05-12Physics
1002Rahul2003-11-04Math

Here: relation name = Student, heading = {StudentID:Integer, Name:Varchar, DOB:Date, Major:Varchar}, degree = 4, cardinality = 2, primary key = StudentID, each row is a tuple.

📌 Examples
  • Student relation: Attributes = {StudentID: Integer (PK), Name: String, DOB: Date, Major: String}. Example tuples: <1001, 'Asha', '2004-05-12', 'Physics'>.
  • Employee relation: Attributes = {EmpID: Integer (PK), Name: String, DeptID: Integer (FK), Salary: Float}. DeptID is a foreign key referencing Dept(DeptID).
  • Book relation (Library): Attributes = {ISBN: String (PK), Title: String, Author: String, Copies: Integer}. Cardinality = number of book records.
  • BankAccount relation: Attributes = {AccountNo: String (PK), HolderName: String, Balance: Decimal, OpenDate: Date}. Domain for Balance = non-negative decimals.
  • Patient relation (Hospital): Attributes = {PatientID: Integer (PK), Name: String, BloodGroup: Enum, Allergies: String (nullable)} — Allergies may be NULL if none.
🧮 Formulas
  1. \[Relation schema notation: R(A1:D1\]
    \[A2:D2, ...\]
    \[An:Dn) where Ai are attributes and Di are domains.\]
  2. \[Degree (arity): n = number of attributes in the heading.\]
  3. \[Cardinality: |R| = number of tuples (rows) currently in the relation.\]
  4. \[Tuple constraint: For any tuple t ∈ R\]
    \[t = <v1\]
    \[v2, ...\]
    \[vn> where vi ∈ Di for i = 1..n.\]
  5. \[Key uniqueness: For primary key PK, ∀t1\]
    \[t2 ∈ R\]
    \[t1.PK = t2.PK ⇒ t1 = t2 (i.e.\]
    \[PK values uniquely identify tuples).\]
💻3

Relation Schema and Relation Instance

💻 COMPUTER SCIENCE / IT

Relation Schema and Relation Instance

Key Point: Relation schema notation: R(A1, A2, ..., An)

Relation Schema: A relation schema is the logical description (structure) of a relation. It specifies the relation name and a list of attributes with their domains. It is a metadata-level concept and does not change frequently. Notation: R(A1, A2, ..., An) where R is the relation name and each Ai is an attribute having a domain Di.

Relation Instance: A relation instance (or relation variable instance) is a set of tuples that conform to the relation schema at a particular moment in time. An instance is the actual data — rows in a table. If R is a schema and Di are domains, an instance r of R is a subset r ⊆ D1 × D2 × ... × Dn.

Key concepts:

  • Attributes: columns of the relation; each attribute has a domain (allowed values).
  • Tuple: a single row in the instance; an ordered list of attribute values.
  • Degree (arity): number of attributes (n) in the schema.
  • Cardinality: number of tuples (|r|) in the instance.
  • Primary key: a minimal set of attributes that uniquely identify a tuple in every valid instance of the relation.
  • Constraints: domain constraints (values must come from attribute domains), key constraints (uniqueness), and entity-integrity (primary key values cannot be NULL).

Difference (short): Schema = structure (definition, fixed until changed by DBA). Instance = content (current set of tuples, changes frequently with insert/update/delete).

Formal view (set-theoretic): If R(A1,...,An) with domains D1,...,Dn, then any instance r of R is r ⊆ D1 × D2 × ... × Dn. Each tuple t in r is of the form (v1, v2, ..., vn) where vi ∈ Di.

Example explained: Schema Student(AdmNo, Name, Class, DOB) has degree 4. An instance might contain 200 tuples today (cardinality 200). AdmNo is the primary key — no two tuples can have the same AdmNo and it cannot be NULL. Tomorrow some students graduate, so the instance changes but the schema remains Student(AdmNo, Name, Class, DOB).

📌 Examples
  • Student schema: Student(AdmNo, Name, Class, DOB). Instance (tuples): 1, "Asha", 12A, 2007-03-12 2, "Rohan", 12B, 2007-11-02 3, "Maya", 11A, 2008-05-21 (Here degree = 4, cardinality = 3; AdmNo is primary key.)
  • Library schema: Book(ISBN, Title, Author, CopiesAvailable). Instance: 978-0140449136, "Odyssey", "Homer", 5 978-0199535569, "Pride and Prejudice", "Austen", 2 (ISBN primary key; degree = 4; cardinality = 2.)
  • Enrollment schema: Enroll(StudentID, CourseID, Semester, Grade). Instance: S101, C201, 2024-S1, A S102, C201, 2024-S1, B+ S101, C305, 2024-S1, A- (Primary key could be composite: {StudentID, CourseID, Semester}).
  • Employee schema: Employee(EmpID, Name, Dept, Salary). Instance example: E001, "Neha", HR, 45000 E002, "Vikram", IT, 60000 (Here degree = 4; cardinality depends on current rows.)
🧮 Formulas
  1. \[Relation schema notation: R(A1\]
    \[A2, ...\]
    \[An)\]
  2. \[Instance as subset: r(R) ⊆ D1 × D2 × ... × Dn\]
  3. \[Degree (arity): degree(R) = n (number of attributes)\]
  4. \[Cardinality: card(r) = |r| (number of tuples in instance r)\]
  5. \[Uniqueness (primary key K): ∀ t1\]
    \[t2 ∈ r\]
    \[if t1[K] = t2[K] then t1 = t2\]
  6. \[Entity integrity: ∀ t ∈ r\]
    \[t[PK] ≠ NULL\]
💻4

Keys

💻 COMPUTER SCIENCE / IT

Keys

Key Point: Functional dependency: X → Y (X determines Y)

What is a Key?
A key is one or more attributes of a relation that uniquely identify a tuple (row). Keys enforce uniqueness and help establish relationships between tables in a relational database.

Core concepts and formalism

  • Functional dependency: X → Y means attribute set X functionally determines attribute set Y (each value of X corresponds to exactly one value of Y).
  • Superkey: Any attribute set X such that X → all attributes of the relation (i.e., X uniquely identifies tuples). A superkey may contain extra attributes.
  • Candidate key: A minimal superkey (no proper subset of it is a superkey). A relation can have multiple candidate keys.
  • Primary key: A candidate key chosen by database designer to be the main identifier. It must be unique and not NULL.
  • Alternate key: Any candidate key that is not selected as the primary key.
  • Composite (concatenated) key: A key made up of two or more attributes used together to uniquely identify tuples.
  • Foreign key: An attribute (or attribute set) in one relation that references a candidate/primary key in another relation to establish referential integrity.
  • Surrogate key: An artificial key (often system-generated, e.g., an auto-increment integer) used as the primary key when no natural key is convenient.

Properties

  • Uniqueness: Key values must be unique across tuples.
  • Minimality (for candidate keys): No subset of a candidate key should be able to uniquely identify tuples.
  • Non-nullability (usually for primary keys): Primary key attributes should not be NULL.
  • Referential integrity: A foreign key value must either match an existing primary key value in the referenced relation or be NULL (if allowed).

How to check a key (practical steps)

  1. Identify functional dependencies between attributes.
  2. Compute the attribute closure X+ for candidate sets X (attributes determined by X using dependencies).
  3. If X+ includes all attributes of the relation, X is a superkey. If no proper subset of X is a superkey, X is a candidate key.

Short example (conceptual)
For relation Student(SID, RollNo, Name, DOB, Email):

  • SID → all attributes (if SID is unique) so SID is a superkey; if no subset of SID (itself single attribute) is a superkey then SID is a candidate key and can be chosen as primary key.
  • {RollNo, Branch, Year} might together be a composite key if RollNo alone is not unique across branches/years.
  • In an Enrollment relation Enrollment(EnrollID, StudentSID, CourseID): StudentSID is a foreign key referring to Student(SID).

Why keys matter: Keys ensure data integrity, enable fast lookup/indexing, and define relationships between tables for joins and referential constraints.

📌 Examples
  • Student(SID, Name, DOB, Email): SID is a primary key (unique, non-null). Email could be an alternate key if unique.
  • Book(ISBN, Title, Author, Edition): ISBN uniquely identifies a book — primary key. If a library tracks copies: LibraryBook(ISBN, CopyNo, Shelf) — (ISBN, CopyNo) is a composite key.
  • Employee(EmpID, PAN, Name, Dept): EmpID (surrogate) as primary key; PAN (national tax id) can be an alternate key if unique.
  • Order(OrderID, OrderDate, CustomerID): OrderID is primary key; CustomerID is a foreign key referencing Customer(CustomerID).
  • ClassRegistration(Year, Branch, RollNo, StudentName): If RollNo repeats every year but (Year, RollNo) together are unique, then (Year, RollNo) is a composite primary key.
🧮 Formulas
  1. \[Functional dependency: X → Y (X determines Y)\]
  2. \[Attribute closure: X+ = set of attributes functionally determined by X\]
    \[If X+ contains all attributes of relation R\]
    \[then X is a superkey.\]
  3. \[Minimality condition for candidate key: X is a candidate key if X+ = R and for all proper subsets S of X\]
    \[S+ ≠ R.\]
  4. \[Upper bound on subsets: For a relation with n attributes\]
    \[number of non-empty attribute subsets = 2^n - 1 (upper bound on possible superkeys).\]
  5. \[Referential integrity rule: For foreign key FK in child relation C referencing parent relation P with primary key PK\]
    \[every non-NULL FK value in C must exist as a PK value in P.\]
💻5

Integrity Constraints

💻 COMPUTER SCIENCE / IT

Integrity Constraints

Key Point: Functional dependency: A -> B (A functionally determines B).

Integrity Constraints are rules applied to a relational database to ensure accuracy, consistency and validity of the data. They prevent invalid or inconsistent data from being stored and enforce business rules at the database level.

Main types of integrity constraints:

  • Domain Constraint: Each attribute (column) has a domain — a set of permissible values (data type, length, allowed range or format). Example: age INT CHECK (age BETWEEN 0 AND 120).
  • Entity Integrity: No primary key (PK) value can be NULL. Every row must be uniquely identifiable. Example: in a Student table, roll_no PRIMARY KEY, roll_no cannot be NULL.
  • Key Constraints:
    • Superkey: A set of attributes that uniquely identifies a tuple.
    • Candidate key: Minimal superkey (no proper subset is a superkey).
    • Primary key: A chosen candidate key; unique and NOT NULL.
    • Alternate key: Candidate keys not chosen as primary.
    • Composite key: A key made of two or more attributes.
  • Referential Integrity: A foreign key (FK) in a child table must either be NULL (if allowed) or match a primary key value in the parent table. This keeps relationships consistent. Example: order.customer_id must exist in customer.customer_id.
  • CHECK Constraints and Business Rules: Custom conditions that rows must satisfy, e.g., CHECK (salary >= 0) or CHECK (start_date <= end_date).

How constraints are enforced: At INSERT, UPDATE and DELETE operations. The DBMS checks constraint rules and rejects operations that would violate them. Referential actions may be specified (ON DELETE CASCADE, ON UPDATE SET NULL) to manage dependent rows when parent rows change.

Why they matter: Integrity constraints maintain data quality, reduce application-level checks, prevent anomalies, and preserve correct relationships between tables.

Short SQL examples:

CREATE TABLE Student (
  roll_no INT PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  age INT CHECK (age BETWEEN 3 AND 100)
);

CREATE TABLE Department (
  dept_id INT PRIMARY KEY,
  dept_name VARCHAR(40)
);

CREATE TABLE Employee (
  emp_id INT PRIMARY KEY,
  name VARCHAR(50),
  dept_id INT,
  FOREIGN KEY (dept_id) REFERENCES Department(dept_id) ON DELETE SET NULL
);
📌 Examples
  • School database: Student(roll_no PK, name, class, age). Entity integrity ensures roll_no is not NULL; domain constraint enforces age range.
  • Banking: Account(account_no PK, balance). Check constraint balance >= 0 prevents negative balances. Referential integrity: Transaction.account_no must reference Account.account_no.
  • E-commerce: Orders(order_id PK, customer_id FK -> Customers.customer_id). Referential integrity ensures every order belongs to an existing customer.
  • Company: Employee(emp_id PK, dept_id FK -> Department.dept_id). ON DELETE CASCADE removes employees if a department is deleted (or better: prevent deletion) depending on business rule.
🧮 Formulas
  1. \[Functional dependency: A -> B (A functionally determines B).\]
  2. \[Primary key rule: PK is UNIQUE and NOT NULL (no two rows share same PK value\]
    \[no NULL PKs).\]
  3. \[Referential integrity rule: For a foreign key FK referencing parent PK: FK is NULL OR FK ∈ {values of PK in parent table}.\]
  4. \[Superkey ⊇ Candidate key\]
    \[Candidate key is minimal superkey.\]
  5. \[SQL constraint examples: CONSTRAINT pk_student PRIMARY KEY (roll_no)\]
    \[FOREIGN KEY (dept_id) REFERENCES Department(dept_id) ON DELETE CASCADE\]
    \[CHECK (salary >= 0).\]
🔣6

Relational Algebra — Basic Operations

💻 COMPUTER SCIENCE / IT

Relational Algebra — Basic Operations

Key Point: Selection: σ_condition(R)

Relational algebra is a procedural query language that operates on relations (tables). It provides a set of basic operations that produce new relations from existing ones. These operations form the theoretical foundation for SQL and relational databases.

Basic operations (with purpose and syntax):

  • Selection (σ) — selects rows that satisfy a condition. Syntax: σ_condition(R). Example: σ_city='Delhi'(Students) returns all student tuples with city = 'Delhi'. Selection is row-oriented and preserves all attributes.
  • Projection (π) — selects specified columns (attributes) and removes duplicates. Syntax: π_attr1,attr2,...(R). Example: π_name,roll_no(Students) returns only the name and roll_no columns.
  • Union (∪) — combines tuples from two relations with the same schema, removing duplicates. Syntax: R ∪ S. Both relations must have the same set of attributes (compatible).
  • Set Difference (−) — tuples in R that are not in S. Syntax: R - S. Schema must match.
  • Intersection (∩) — tuples common to both relations. Can be derived: R ∩ S = R - (R - S). Syntax: R ∩ S.
  • Cartesian Product (×) — pairs every tuple of R with every tuple of S, producing combined attributes. Syntax: R × S. Use carefully — result size = |R| * |S|.
  • Theta Join and Natural Join
    • Theta-join: R ⋈_θ S = σ_θ(R × S) — join with a general condition θ (e.g., R.id = S.rid).
    • Natural join (⋈): matches and merges tuples on all common attribute names, eliminating duplicate columns. Syntax: R ⋈ S.
  • Rename (ρ) — renames a relation or its attributes. Syntax: ρ_newName(oldRelation) or ρ_newAttrList(R). Useful to avoid name clashes before joins.
  • Division (÷) — used for queries like “find X that relate to all Y”. If R(A,B) and S(B), then R ÷ S returns all a in A such that for every b in S, (a,b) ∈ R. Syntax: R ÷ S.

Typical properties and useful identities (used to optimize or rewrite expressions):

  • Selection is commutative: σ_p(σ_q(R)) = σ_q(σ_p(R)) = σ_{p ∧ q}(R).
  • Projection is idempotent: π_L(π_L(R)) = π_L(R). Order of projections matters if attribute lists differ.
  • Union and intersection are commutative and associative: R ∪ S = S ∪ R; (R ∪ S) ∪ T = R ∪ (S ∪ T), similarly for ∩.
  • Cartesian product distributes over union: R × (S ∪ T) = (R × S) ∪ (R × T).
  • Theta-join as selection on Cartesian product: R ⋈_θ S = σ_θ(R × S).

Why these operations matter: they allow expression of all common queries — filtering, column selection, combining tables, and expressing “for all” conditions (division). They are the algebraic building blocks behind SQL's SELECT-FROM-WHERE constructs.

📌 Examples
  • Selection: Students table — σ_city='Mumbai' (Students) returns all students living in Mumbai.
  • Projection: From Employees table, π_name,salary (Employees) returns only employees' names and salaries (duplicates removed).
  • Union/Difference: Two relation snapshots — PastStudents ∪ CurrentStudents gives all students who were ever enrolled; CurrentStudents - Alumni gives current students who are not alumni (if schemas match appropriately).
  • Join: StudentEnroll(StudentID, CourseID) ⋈ Course(CourseID, CourseName) on CourseID gives student-course name pairs (natural join or θ-join on equality).
  • Division: If Taken(StudentID, CourseID) lists courses taken and Required(CourseID) lists all compulsory courses, then Taken ÷ Required returns StudentIDs who have taken all compulsory courses.
🧮 Formulas
  1. \[Selection: σ_condition(R)\]
  2. \[Projection: π_attr1,attr2,...(R)\]
  3. \[Union: R ∪ S (requires same schema)\]
  4. \[Difference: R - S (requires same schema)\]
  5. \[Intersection: R ∩ S = R - (R - S)\]
  6. \[Cartesian product: R × S\]
7

Relational Algebra — Additional Operations

💻 COMPUTER SCIENCE / IT

Relational Algebra — Additional Operations

Key Point: Intersection: R ∩ S = { t | t ∈ R AND t ∈ S } = R − (R − S)

Overview
Relational algebra provides a set of basic operations (selection, projection, union, difference, Cartesian product, rename) to query relations. 'Additional operations' are derived operators built from the basic ones to express common queries more conveniently: intersection, natural join, theta join, division, outer joins (left, right, full) and rename (as a formal operator). Each has a precise meaning and can be implemented using basic operators.

1. Intersection (R ∩ S)
Definition: Tuples that are present in both relations R and S. Both relations must be union-compatible (same attributes and domains).
Intuition: R ∩ S = R − (R − S).

2. Natural Join (R ⋈ S)
Definition: Combine tuples from R and S that have equal values on all common attributes; the common attributes appear once in the result. Natural join implicitly performs a Cartesian product followed by selection on equality of common attributes then projection to remove duplicate common columns.
Intuition: Join student and enrollment tables on StudentID to get student details with their courses.

3. Theta Join (R ⋈_{θ} S)
Definition: General join where tuples from R and S are combined when predicate θ (any comparison) holds between attributes of R and S (e.g., R.A > S.B). Natural join is a special case where θ is equality on all common attributes.

4. Division (R ÷ S)
Definition: Given R(X, Y) and S(Y) where Y attributes are a subset of R’s attributes, R ÷ S returns the set of X-values such that for every tuple y in S, the tuple (x,y) is in R. Used to answer 'for all' queries (e.g., students who have taken all required courses).
Intuition: Find suppliers who supply all parts listed in S.

5. Outer Joins (Left ⟕, Right ⟖, Full ⟗)
Definition: Like natural join but preserve unmatched tuples from one or both sides by padding NULLs for missing attributes. Left outer join keeps all tuples from R and matches from S (NULLs if no match). Right outer join keeps all from S. Full outer join keeps all tuples from both relations.

6. Rename (ρ)
Definition: Renames a relation or its attributes, used to avoid name conflicts or to make intermediate results referable. Syntax: ρ_NewName(Relation) or ρ_NewName(attr1,attr2,...)(Relation).

Why these matter (CBSE context)
These additional operations let you express common database questions succinctly: intersection for common membership, joins to combine related information, division for 'for all' queries, outer joins to retain unmatched rows (useful in reports), and rename to keep expressions clear. Each can be explained and implemented using the basic operations, which reinforces understanding of relational algebra's completeness.

📌 Examples
  • Intersection: Students who are in both 'ChessClub' and 'DebateClub' lists → ChessClub ∩ DebateClub.
  • Natural Join: Student(StudentID, Name) ⋈ Enrollment(StudentID, CourseID) gives student details with courses (StudentID appears only once).
  • Theta Join: Employee ⋈_{Employee.Salary > Manager.Salary} Manager finds employees earning more than some managers (example predicate).
  • Division: R(StudentID, CourseID) ÷ S(CourseID) returns StudentIDs of students who have taken every course in S (e.g., all compulsory courses).
  • Left Outer Join: Department ⟕ Employee returns all departments including those with no employees (Employee fields NULL).
  • Rename: ρ_Emp(empID, name)(TempEmp) renames TempEmp relation and its attributes for use in expressions.
🧮 Formulas
  1. \[Intersection: R ∩ S = { t | t ∈ R AND t ∈ S } = R − (R − S)\]
  2. \[Natural Join: R ⋈ S = { r ∪ s | r ∈ R\]
    \[s ∈ S\]
    \[and r[commonAttrs] = s[commonAttrs] }\]
  3. \[Theta Join: R ⋈_{θ} S = σ_{θ}(R × S) where θ is any predicate comparing attributes of R and S\]
  4. \[Division: Let R(X,Y) and S(Y)\]
    \[Then R ÷ S = { t_X | ∀ y ∈ S\]
    \[(t_X ∪ y) ∈ R }\]
    \[Equivalent relational algebra expression: π_X(R) − π_X((π_X(R) × S) − R)\]
  5. \[Left Outer Join: R ⟕ S = (R ⋈ S) ∪ (R − π_R(R ⋈ S)) padded with NULLs for S's attributes (similarly for right ⟖ and full ⟗)\]
  6. \[Rename: ρ_{NewName} (R) or ρ_{NewName(attr1,attr2,...)}(R) — changes the relation/attribute names\]
⚖️8

Joins and Set Operations

💻 COMPUTER SCIENCE / IT

Joins and Set Operations

Key Point: Relational algebra join: A ⋈_{A.key = B.key} B

Overview

In relational databases, joins and set operations are ways to combine rows from two (or more) relations (tables).

Joins combine tuples from different tables based on a related column (usually a key). They produce a result that typically contains columns from both input tables. Joins are implemented in SQL using the JOIN clause (or by listing tables in FROM with a WHERE condition).

  • Inner Join (Equi-join): Returns rows that have matching values in both tables. SQL: SELECT ... FROM A INNER JOIN B ON A.key = B.key;
  • Natural Join: A join on all columns with the same names in both tables. It implicitly matches those columns and removes duplicate columns in the result. Use with care because it depends on column names.
  • Theta Join: A join with an arbitrary condition (e.g., A.x > B.y). General form is A ⋈_{condition} B.
  • Cross Join (Cartesian Product): Every row of A paired with every row of B. SQL: SELECT ... FROM A CROSS JOIN B; or FROM A, B (without WHERE).
  • Outer Joins: Preserve non-matching rows from one or both tables by padding missing columns with NULLs.
    • Left Outer Join: All rows from left table + matching rows from right table; non-matches have NULL for right-side columns. SQL: FROM A LEFT JOIN B ON ...
    • Right Outer Join: All rows from right table + matching rows from left table.
    • Full Outer Join: All rows from both tables; non-matches padded with NULLs.
  • Self Join: A table joined with itself using aliases — useful for hierarchical or pairwise comparisons.

Set operations treat whole rows as set elements and combine the results of two queries (usually requiring the same number of columns and compatible types):

  • UNION: All distinct rows that appear in either result. SQL: Q1 UNION Q2. Removes duplicates by default.
  • UNION ALL: Like UNION but preserves duplicates (faster when duplicate removal not needed).
  • INTERSECT: Rows common to both results. SQL: Q1 INTERSECT Q2.
  • EXCEPT / MINUS: Rows in the first result but not in the second. SQL dialects differ: SQL Server and standard SQL use EXCEPT, Oracle uses MINUS. Example: Q1 EXCEPT Q2.

Important rules for set operations:

  • Both queries must return the same number of columns.
  • Corresponding columns must have compatible data types (can be implicitly converted or of same domain).
  • Column names in the final result come from the first query (Q1) in many systems.
  • UNION/INTERSECT/EXCEPT remove duplicates by default; use ALL suffix to keep duplicates (where supported).

Connection to relational algebra

  • Join in relational algebra is often written as A ⋈_{condition} B. Natural join is A ⋈ B (matching attributes). Cartesian product: A × B.
  • Set operations correspond to algebraic set ops: (union), (intersection), (difference).

Practical notes

  • Use INNER JOIN when you need only matching rows; use LEFT/RIGHT/FULL OUTER JOIN when you need to retain non-matching rows from one or both sides.
  • Prefer explicit JOIN ... ON syntax over comma-separated tables with WHERE — it is clearer and less error-prone.
  • Be careful with NATURAL JOIN and SELECT * with joins: column name collisions can produce unexpected results.
📌 Examples
  • Inner Join (Students and Marks): Tables Student(id, name) and Marks(sid, subject, marks). Query: SELECT Student.id, Student.name, Marks.subject, Marks.marks FROM Student INNER JOIN Marks ON Student.id = Marks.sid; — returns only students who have marks entries.
  • Left Outer Join (Employees and Departments): Tables Employee(emp_id, name, dept_id) and Dept(dept_id, dept_name). Query: SELECT e.emp_id, e.name, d.dept_name FROM Employee e LEFT JOIN Dept d ON e.dept_id = d.dept_id; — returns all employees; dept_name is NULL for employees without a department.
  • Cross Join (Products and Colors): Tables Product(p_id, p_name) and Color(c_id, color). Query: SELECT p.p_name, c.color FROM Product CROSS JOIN Color; — produces every combination of product and color (useful for generating option lists).
  • Self Join (Manager-Employee): Employee(emp_id, name, manager_id). Query: SELECT e.name AS employee, m.name AS manager FROM Employee e LEFT JOIN Employee m ON e.manager_id = m.emp_id; — pairs employees with their managers using the same table twice with aliases.
  • Set Operation - UNION (Campus Students): Table A: Students_2023(name, roll) and B: Students_2024(name, roll) with same columns. Query: SELECT name, roll FROM Students_2023 UNION SELECT name, roll FROM Students_2024; — lists unique students across both years. Use UNION ALL to keep duplicates.
  • Set Operation - INTERSECT (Common Customers): Q1: SELECT customer_id FROM Orders_Online; Q2: SELECT customer_id FROM Orders_Store; Q1 INTERSECT Q2 returns customers who ordered both online and in-store.
🧮 Formulas
  1. \[Relational algebra join: A ⋈_{A.key = B.key} B\]
  2. \[Natural join: A ⋈ B (matching common attribute names)\]
  3. \[Cartesian product: A × B\]
  4. \[Set union: R ∪ S (SQL: Q1 UNION Q2)\]
  5. \[Set intersection: R ∩ S (SQL: Q1 INTERSECT Q2)\]
  6. \[Set difference: R − S (SQL: Q1 EXCEPT Q2 or Q1 MINUS Q2)\]
🧪9

Relational Database Design and Anomalies

⚗️ CHEMICAL PRINCIPLE

Relational Database Design and Anomalies

Key Point: Functional dependency: X → Y (X determines Y).

Overview: Relational database design organizes data into relations (tables) so the information is stored efficiently, without unnecessary redundancy, and supports correct querying and updates. Good design uses functional dependencies, keys and normalization to eliminate anomalies (insertion, update, deletion) while preserving data integrity.

Key concepts

  • Relation: A table with rows (tuples) and columns (attributes).
  • Functional dependency (FD): For attributes X and Y of a relation R, X → Y means that if two tuples agree on X they must agree on Y.
  • Key: An attribute or minimal set of attributes that uniquely identifies a tuple (candidate key). A chosen candidate key is the primary key.
  • Closure (X+): The set of all attributes functionally determined by X given a set of FDs; used to test keys.
  • Decomposition: Splitting a relation into two or more relations to remove redundancy while aiming for lossless join and dependency preservation.

Anomalies

  • Insertion anomaly: Cannot add valid data because other required data is missing. Example: cannot add a new course if a student record is required for the table design.
  • Deletion anomaly: Deleting a row removes other valuable information. Example: deleting the last student enrolled in a course removes the course information entirely.
  • Update anomaly: Multiple copies of the same information require multiple updates; inconsistency can result if all copies aren't changed.

Normalization (common normal forms)

  • 1NF (First Normal Form): All attribute values are atomic (no repeating groups or arrays).
  • 2NF (Second Normal Form): Relation is in 1NF and every non-prime attribute is fully functionally dependent on the whole of every candidate key (no partial dependency on a part of a composite key).
  • 3NF (Third Normal Form): Relation is in 2NF and there is no transitive dependency of a non-prime attribute on a key. Formally, for each FD X → A, either X is a superkey or A is a prime attribute (part of some candidate key).
  • BCNF (Boyce–Codd Normal Form): For every non-trivial FD X → Y, X must be a superkey (stronger than 3NF).

Decomposition properties

  • Lossless-join decomposition: Decomposing R into R1 and R2 is lossless if R1 ∩ R2 → R1 or R1 ∩ R2 → R2 (the common attributes functionally determine one of the components).
  • Dependency preservation: After decomposition, it should be possible to enforce all original FDs using constraints on the decomposed relations (not always possible with BCNF).

Design process (practical steps)

  1. List attributes and identify candidate keys using attribute closures (X+).
  2. List functional dependencies by analyzing semantics of data.
  3. Apply normalization rules: remove partial dependencies (to reach 2NF), remove transitive dependencies (to reach 3NF), and consider BCNF when necessary.
  4. Check each decomposition for lossless join and try to preserve dependencies.

Why this matters (summary): Proper relational design reduces redundancy, avoids anomalies, improves integrity and makes queries and updates reliable and efficient. In practice you balance normalization with performance (sometimes denormalize for speed).

📌 Examples
  • Student-Course table (bad design): StudentID, StudentName, CourseID, CourseName, Instructor. Problems: If Instructor changes, must update many rows (update anomaly). If there are no students enrolled yet, you cannot add a Course (insertion anomaly). Deleting the last student enrolled removes the Course record (deletion anomaly). Normalize into Student(StudentID, StudentName), Course(CourseID, CourseName, Instructor), Enrollment(StudentID, CourseID).
  • Employee-Project table (composite key partial dependency): EmployeeID, ProjectID, EmployeeName, ProjectName, EmployeeDept. If primary key is (EmployeeID, ProjectID) then EmployeeName and EmployeeDept depend only on EmployeeID (partial dependency) — violates 2NF. Decompose to Employee(EmployeeID, EmployeeName, EmployeeDept) and ProjectAssignment(EmployeeID, ProjectID, ProjectName).
  • Online Orders (redundancy & update anomaly): OrderID, CustomerID, CustomerName, ProductID, ProductName, Price. CustomerName and ProductName repeated across many orders. Normalize to Customer, Product, Order, OrderItem to remove redundancy and anomalies.
  • Library system: Transactions table with BookID, BookTitle, Author, MemberID, MemberName, IssueDate. Author and BookTitle repeated; MemberName repeated. Decompose to Book, Member, Transaction to avoid anomalies.
🧮 Formulas
  1. \[Functional dependency: X → Y (X determines Y).\]
  2. \[Attribute closure (X+): Start with X+\]
    \[Repeatedly add attributes A when there exists a FD U → V such that U ⊆ X+\]
    \[add V to X+\]
    \[Stop when no new attributes can be added\]
    \[If X+ contains all attributes of R then X is a superkey.\]
  3. \[2NF condition: Relation is in 1NF and no non-prime attribute is partially dependent on any candidate key (i.e.\]
    \[no FD where part_of_key → non-prime_attribute).\]
  4. \[3NF condition: For every FD X → A\]
    \[at least one holds: (a) X is a superkey\]
    \[or (b) A is a prime attribute (part of some candidate key).\]
  5. \[BCNF condition: For every non-trivial FD X → Y\]
    \[X must be a superkey.\]
  6. \[Lossless-join test for decomposition R → (R1\]
    \[R2): (R1 ∩ R2) → R1 or (R1 ∩ R2) → R2 must hold (i.e.\]
    \[intersection is a key for one component).\]
💻10

Functional Dependency

📐 MATHEMATICAL FORMULA / THEOREM

Functional Dependency

Key Point: FD notation: X -> Y (X and Y are sets of attributes)

Definition: A functional dependency (FD) X -> Y between two sets of attributes X and Y of a relation R means: for any two tuples t1 and t2 in R, if t1[X] = t2[X] then t1[Y] = t2[Y]. X functionally determines Y, so X uniquely determines the values of Y.

Notation & basic idea: X -> Y (read ‘X determines Y’). If X is a candidate key, then X -> all attributes of R.

Types of functional dependencies:

  • Trivial FD: Y ⊆ X, e.g. (A,B) -> A.
  • Non-trivial FD: Y ⊄ X, e.g. A -> B where B is not in A.
  • Fully functional dependency: Y depends on whole of X and not on any proper subset of X. Example: (A,B) -> C is full if neither A -> C nor B -> C holds.
  • Partial dependency: Some proper subset of a composite key determines Y. Example: (A,B) -> C but A -> C holds → partial dependency.
  • Transitive dependency: X -> Y and Y -> Z implies X -> Z (indirect). Example: StudentID -> DeptID and DeptID -> HOD implies StudentID -> HOD.

Why it matters: FDs capture redundancy and are the basis for normalization (2NF, 3NF, BCNF). They help identify keys and determine safe decompositions.

Key concepts & procedures:

  • Closure of an attribute set (X+): The set of all attributes functionally determined by X given a set of FDs. Used to test if X is a key (if X+ includes all attributes of R).
  • Armstrong's axioms (sound & complete rules to infer FDs):
    • Reflexivity: If Y ⊆ X then X -> Y.
    • Augmentation: If X -> Y then XZ -> YZ for any Z.
    • Transitivity: If X -> Y and Y -> Z then X -> Z.
  • Additional useful rules: Union (if X -> Y and X -> Z then X -> YZ), Decomposition (X -> YZ implies X -> Y and X -> Z), Pseudotransitivity.
  • Minimal cover (canonical cover): A minimal equivalent set of FDs where: right sides are single attributes, extraneous attributes removed from left sides, and no FD is redundant.

How to compute X+ (algorithm): Start with X+ = X. Repeatedly add attributes B to X+ whenever there is an FD Y -> B with Y ⊆ X+. Stop when no more attributes can be added.

Relation to keys: X is a superkey iff X+ contains all attributes of the relation. X is a candidate key if it is a minimal superkey (no proper subset of X is a superkey).

Normalization role: Use FDs to decompose relations to eliminate undesirable dependencies (partial/transitive) and reduce redundancy while preserving data and dependencies when possible.

📌 Examples
  • Student(studentID, name, deptID, deptName): studentID -> name, studentID -> deptID. DeptID -> deptName. Here studentID -> deptName (transitive via deptID).
  • Library(BookISBN, title, author, publisher): BookISBN -> title, author, publisher. ISBN uniquely determines other attributes.
  • Employee(empID, name, deptID, deptName, manager): empID -> name, empID -> deptID. deptID -> deptName, deptID -> manager. empID -> manager is transitive.
  • Phone(phoneNumber, ownerName, address): phoneNumber -> ownerName, phoneNumber -> address (phone number uniquely identifies owner and address).
  • Marks(rollNo, subjectCode, teacher, marks): (rollNo, subjectCode) -> marks (composite key). If rollNo -> studentName, then partial dependency exists if studentName stored in same relation.
🧮 Formulas
  1. \[FD notation: X -> Y (X and Y are sets of attributes)\]
  2. \[Trivial: If Y ⊆ X then X -> Y\]
  3. \[Reflexivity (Armstrong): If Y ⊆ X then X -> Y\]
  4. \[Augmentation (Armstrong): If X -> Y then XZ -> YZ\]
  5. \[Transitivity (Armstrong): If X -> Y and Y -> Z then X -> Z\]
  6. \[Closure computation: X+ = X ∪ {B | there exists Y -> B and Y ⊆ X+} (repeat until fixed point)\]
💻11

Normalization — Normal Forms

💻 COMPUTER SCIENCE / IT

Normalization — Normal Forms

Key Point: Functional dependency: X → Y (X and Y are attribute sets).

What is normalization? Normalization is a systematic process in relational database design that organizes tables to reduce redundancy and eliminate undesirable anomalies (insertion, update, deletion). It uses functional dependencies (FDs) and keys to decompose relations into well-structured smaller relations while preserving data and dependencies when possible.

Key concepts

  • Functional dependency (FD): X → Y means attribute set X functionally determines attribute Y.
  • Superkey / Candidate key / Primary key: A superkey uniquely identifies a tuple. A candidate key is a minimal superkey. One candidate key is chosen as the primary key.
  • Partial dependency: In a relation with a composite key, an attribute is partially dependent if it depends on part of the key (violates 2NF).
  • Transitive dependency: A → B and B → C implies A → C transitively; if A is key and C is non-prime this can violate 3NF.
  • Decomposition properties: Lossless-join (no spurious tuples) and dependency preservation (able to enforce FDs on decomposed tables).

Normal forms (common ones studied in Class 12)

  • 1NF (First Normal Form): All attributes contain atomic (indivisible) values; no repeating groups or arrays in a single column.
  • 2NF (Second Normal Form): Table is in 1NF and every non-prime attribute is fully functionally dependent on the whole of every candidate key (i.e., no partial dependencies).
  • 3NF (Third Normal Form): Table is in 2NF and there are no transitive dependencies of non-prime attributes on candidate keys. Formal condition: for every FD X → A, either X is a superkey or A is a prime attribute (part of some candidate key).
  • BCNF (Boyce–Codd Normal Form): Stronger than 3NF. For every non-trivial FD X → A, X must be a superkey.

Why normalize? To avoid:

  • Update anomalies: multiple places to change the same data.
  • Insertion anomalies: inability to add data without extra unrelated data.
  • Deletion anomalies: loss of needed information when deleting tuples.

How to normalize (high-level steps)

  1. List attributes and determine all functional dependencies.
  2. Find candidate keys (use attribute closure X+ to test).
  3. Check 1NF, then 2NF (remove partial dependencies by decomposing), then 3NF (remove transitive dependencies), and if necessary BCNF.
  4. Ensure decompositions are lossless and try to preserve dependencies.

Notes: BCNF may break dependency preservation even though it is lossless. Practical design often aims for 3NF with dependency preservation and lossless decomposition.

📌 Examples
  • Example 1 — Student course enrollment (shows 1NF → 2NF → 3NF): Original table Enrollment(StudentID, StudentName, CourseID, CourseName, Instructor, Grade). If StudentID,CourseID is the primary key: StudentName depends only on StudentID (partial) and CourseName on CourseID (partial). Decompose to Student(StudentID, StudentName), Course(CourseID, CourseName, Instructor), Enrollment(StudentID, CourseID, Grade). Now tables are in 3NF.
  • Example 2 — Employee and Department (transitive dependency): Employee(EmpID, EmpName, DeptID, DeptName). EmpID → DeptID and DeptID → DeptName. DeptName is transitively dependent on EmpID. Decompose to Employee(EmpID, EmpName, DeptID) and Department(DeptID, DeptName). This removes update anomalies and achieves 3NF/BCNF.
  • Real-life scenario — Customer orders: A single Orders table holding OrderID, CustomerID, CustomerName, CustomerAddress, ItemID, ItemDesc causes repeated customer info for each order line. Normalize into Customer(CustomerID,...), Order(OrderID,CustomerID,...), OrderLine(OrderID,ItemID,Quantity).
🧮 Formulas
  1. \[Functional dependency: X → Y (X and Y are attribute sets).\]
  2. \[Attribute closure: X+ = all attributes functionally determined by X (used to test keys).\]
  3. \[Key test: X is a superkey if X+ contains all attributes of the relation.\]
  4. \[1NF condition: all attribute values are atomic (no repeating groups).\]
  5. \[2NF condition: relation in 1NF and no non-prime attribute is partially dependent on a candidate key.\]
  6. \[3NF condition: for every FD X → A\]
    \[X is a superkey OR A is a prime attribute (part of some candidate key).\]
🌬️12

SQL Basics (often paired with relational concepts)

💻 COMPUTER SCIENCE / IT

SQL Basics (often paired with relational concepts)

Key Point: Basic SELECT template: SELECT FROM

WHERE ORDER BY ;

What is SQL and the relational model?
SQL (Structured Query Language) is the standard language used to define, query and manipulate data in relational database systems. A relational database stores data in relations (tables). Each table has rows (tuples) and columns (attributes). A primary key uniquely identifies each row; a foreign key implements relationships between tables.

Core relational concepts

  • Relation (table): set of tuples having the same attributes.
  • Attribute (column): named field in a table.
  • Tuple (row): one record in a table.
  • Primary key: column(s) uniquely identifying tuples.
  • Foreign key: column(s) referencing primary key(s) of another table to express relationships.
  • Integrity constraints: rules such as NOT NULL, UNIQUE, CHECK to keep data valid.

SQL command categories

  • DDL (Data Definition Language): CREATE, ALTER, DROP (define schema).
  • DML (Data Manipulation Language): SELECT, INSERT, UPDATE, DELETE (work with data).
  • DCL (Data Control Language): GRANT, REVOKE (permissions).
  • TCL (Transaction Control Language): COMMIT, ROLLBACK, SAVEPOINT (transactions).

Basic SELECT/query structure

SELECT column_list
FROM table_name
WHERE conditions
GROUP BY column_list
HAVING group_conditions
ORDER BY column_list;

Notes: WHERE filters rows before grouping; HAVING filters groups after GROUP BY.

Common clauses and concepts

  • WHERE: filter rows with comparison and logical operators (=, <, >, <=, >=, <>, BETWEEN, IN, LIKE).
  • JOINs: combine rows from two or more tables using related columns.
    • INNER JOIN: rows matching in both tables.
    • LEFT (LEFT OUTER) JOIN: all rows from left table + matching rows from right (NULL for no match).
    • RIGHT (RIGHT OUTER) JOIN: all rows from right table + matching rows from left.
    • FULL OUTER JOIN: rows from either table, with NULLs for missing matches.
    • CROSS JOIN: Cartesian product of two tables.
  • Aggregate functions: COUNT, SUM, AVG, MIN, MAX operate on groups of rows.
  • ORDER BY: sort results; LIMIT (or TOP) restricts number of rows returned.

Data modification

INSERT INTO table_name (col1, col2) VALUES (val1, val2);
UPDATE table_name SET col = new_val WHERE condition;
DELETE FROM table_name WHERE condition;

Schema definition example

CREATE TABLE Students (
  student_id INT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  dob DATE,
  class INT
);

CREATE TABLE Marks (
  mark_id INT PRIMARY KEY,
  student_id INT,
  subject VARCHAR(50),
  score INT,
  FOREIGN KEY (student_id) REFERENCES Students(student_id)
);

Transactions and integrity
Use transactions to ensure multiple related changes succeed or fail together: BEGIN/START TRANSACTION, then COMMIT to save or ROLLBACK to undo. Use constraints and foreign keys to maintain referential integrity.

Normalization (brief)
Normalization is organizing tables to reduce redundancy: 1NF (atomic attributes), 2NF (no partial dependency on a composite key), 3NF (no transitive dependency). Normalized schemas make updates more consistent; denormalization may be used for performance.

Practical tips

  • Create indexes on columns used often in WHERE and JOIN conditions to speed queries.
  • Prefer explicit JOIN syntax (JOIN ... ON ...) over implicit joins in WHERE for clarity.
  • Always test UPDATE/DELETE with a SELECT using the same WHERE first to avoid unintended changes.
📌 Examples
  • Select names and classes of students older than a given date: SELECT name, class FROM Students WHERE dob < '2006-01-01';
  • Join Students and Marks to get student name with their scores: SELECT s.name, m.subject, m.score FROM Students s INNER JOIN Marks m ON s.student_id = m.student_id;
  • Get total sales per product (aggregate and GROUP BY): SELECT product_id, COUNT(*) AS units_sold, SUM(amount) AS total_revenue FROM Sales GROUP BY product_id HAVING SUM(amount) > 1000 ORDER BY total_revenue DESC;
  • Create table with constraints: CREATE TABLE Accounts ( acc_no INT PRIMARY KEY, holder_name VARCHAR(100) NOT NULL, balance DECIMAL(12,2) DEFAULT 0 CHECK (balance >= 0) );
  • Safe transfer between two bank accounts using a transaction: BEGIN TRANSACTION; UPDATE Accounts SET balance = balance - 500 WHERE acc_no = 101; UPDATE Accounts SET balance = balance + 500 WHERE acc_no = 202; -- if both succeed COMMIT; -- on failure ROLLBACK;
🧮 Formulas
  1. \[Basic SELECT template: SELECT <columns> FROM <table> WHERE <condition> ORDER BY <columns>;\]
  2. \[Join template: SELECT <cols> FROM A JOIN_TYPE B ON A.key = B.key;\]
  3. \[Group & aggregate template: SELECT <group_cols>\]
    \[AGG_FUNC(<col>) FROM <table> WHERE <cond> GROUP BY <group_cols> HAVING <agg_condition>\]
  4. \[Create table with keys: CREATE TABLE T (col1 TYPE PRIMARY KEY\]
    \[col2 TYPE\]
    \[col3 TYPE\]
    \[FOREIGN KEY (col3) REFERENCES OtherTable(pk))\]
  5. \[Transaction pattern: BEGIN TRANSACTION\]
    \[-- DML statements COMMIT\]
    \[-- or ROLLBACK\]
💻13

Views and Indexes

💻 COMPUTER SCIENCE / IT

Views and Indexes

Key Point: Selectivity = (matching_rows) / (total_rows) -- lower selectivity (smaller fraction) means index more useful

Overview
Views and Indexes are two important relational-database concepts that help present and access data efficiently. A view is a saved query that appears as a virtual table to users; an index is a data structure that speeds up retrieval of rows from a table.

Views

  • Definition: A view is a named, stored SELECT statement. It does not (normally) store the rows itself — it provides a virtual table computed on demand from base tables.
  • Syntax (SQL):
    CREATE VIEW view_name AS
    SELECT column1, column2
    FROM table_name
    WHERE condition;
  • Types:
    • Simple (derived from a single table, no aggregates) — often updatable.
    • Complex (joins, aggregates, DISTINCT, GROUP BY) — usually read-only.
    • Materialized view (or indexed view): stores computed rows for faster reads and requires refresh strategies; supported differently across RDBMS.
  • When to use: security (limit columns/rows users see), abstraction (hide complexity), convenience (reusable queries), and sometimes performance (materialized views).
  • Updateability rules (brief): A view is updatable if the DBMS can map modifications to a single base table and the view doesn't use aggregates, GROUP BY, DISTINCT, set operations, or derived columns. Many DBMS support INSTEAD OF triggers to make complex views updatable.
  • WITH CHECK OPTION: Ensures that any row inserted/updated through the view still satisfies the view's WHERE condition.

Indexes

  • Definition: An index is a separate data structure (commonly a B-tree) that maps key values to row locations so the DBMS can find rows without scanning the whole table.
  • Syntax (SQL):
    CREATE INDEX idx_name ON table_name(column1);
    CREATE UNIQUE INDEX ux_name ON table_name(column1);
    CREATE INDEX idx_comp ON table_name(col1, col2); -- composite index
  • Types:
    • Clustered index: determines physical order of rows (one per table).
    • Non-clustered index: separate structure that points to rows (multiple allowed).
    • Unique index: enforces uniqueness of key values.
    • Hash index: good for equality lookups (not range queries).
    • Bitmap index: good for low-cardinality columns in data-warehouse scenarios.
    • Composite index: on multiple columns; order of columns matters.
    • Covering index: contains all columns needed by a query so the DBMS need not read the base table.
  • When to create indexes: On columns used frequently in WHERE, JOIN, ORDER BY, GROUP BY, and as foreign keys — especially if they have high cardinality (many distinct values).
  • Trade-offs: Indexes speed SELECTs but slow INSERT/UPDATE/DELETE (extra maintenance) and consume disk space. Avoid over-indexing. Choose indexes where benefit outweighs cost.
  • Common implementation: B-tree for range and equality queries; hash for equality-only; bitmap for analytics on low-cardinality columns.

Example: combined use
You can create a view to present only required columns and behind the scenes the DBMS can still use indexes on base tables to make the view query fast. For large aggregated reports, a materialized view (or indexed view) can store precomputed results and be refreshed periodically.

Practical tips

  • Create indexes on selective columns used in lookup conditions. If a column returns a large fraction of the table, the index may not help.
  • Use composite indexes carefully: put the most selective column first or match the query's leftmost columns.
  • Monitor and drop unused indexes to save space and reduce write overhead.
  • Use views to restrict sensitive columns (security) and simplify complex joins for application developers.
📌 Examples
  • Create a simple view for student marks: CREATE VIEW StudentMarks AS SELECT student_id, name, marks FROM Students WHERE class = 12;
  • Create a read-only aggregated view (example): CREATE VIEW DeptAverage AS SELECT dept_id, AVG(salary) AS avg_sal FROM Employee GROUP BY dept_id;
  • Make a materialized/indexed view (vendor-specific, general idea): -- In some DBMS CREATE MATERIALIZED VIEW SalesSummary AS SELECT product_id, SUM(quantity) AS total_qty FROM Sales GROUP BY product_id REFRESH FAST ON DEMAND;
  • Create indexes to speed queries: CREATE INDEX idx_students_marks ON Students(class, marks); CREATE UNIQUE INDEX ux_student_id ON Students(student_id); -- Composite index: useful for WHERE class = ? AND marks > ?
  • Use WITH CHECK OPTION to protect view integrity: CREATE VIEW ActiveEmployees AS SELECT * FROM Employee WHERE status = 'ACTIVE' WITH CHECK OPTION; -- prevents inserting a row with status != 'ACTIVE' through this view.
🧮 Formulas
  1. \[Selectivity = (matching_rows) / (total_rows) -- lower selectivity (smaller fraction) means index more useful\]
  2. \[Cardinality = number_of_distinct_values(column)\]
  3. \[Estimated cost (conceptual): Cost_full_table_scan ≈ N_pages_to_read Cost_index_seek ≈ log_fanout(N_index_nodes) + pages_for_matching_rows -- B-tree seeks are logarithmic in number of index pages\]
    \[fetching matching rows may require extra I/O\]
  4. \[Rough rule: If selectivity < 0.05 (5–10%) an index is often beneficial\]
    \[if selectivity is high (many rows match)\]
    \[a full scan may be cheaper\]
  5. \[Approximate index storage: index_size ≈ N_rows * (key_size + pointer_size) * overhead_factor\]
💻14

Advantages of the Relational Model and RDBMS

💻 COMPUTER SCIENCE / IT

Advantages of the Relational Model and RDBMS

Key Point: |R × S| = |R| * |S| (size of Cartesian product of relations R and S)

The relational model organises data in tables (relations) made of rows (tuples) and columns (attributes). A Relational Database Management System (RDBMS) implements this model and provides tools to store, retrieve and manage data reliably. The main advantages are:

  • Simplicity and tabular structure — Data is represented as tables with named columns; this makes design, understanding and querying straightforward. Tables map easily to real-world entities (students, products, accounts).
  • Data independence — Logical schema (tables and relations) is separate from physical storage. Changes to storage or access methods do not require changes to application queries.
  • Reduced redundancy and consistency — Normalization and relational design minimise duplicated data, reducing anomalies (insert, update, delete) and keeping data consistent.
  • Data integrity and constraints — RDBMS enforces rules such as primary keys (uniqueness), foreign keys (referential integrity), NOT NULL, UNIQUE and CHECK constraints to ensure valid data.
  • Powerful, declarative querying — SQL lets users request what they want (SELECT, JOIN, GROUP BY) without specifying how to get it. Complex queries and aggregations are easy to express.
  • Transactions and ACID properties — Atomicity, Consistency, Isolation and Durability ensure reliable multi-step operations (e.g., bank transfers) even under failures or concurrent access.
  • Concurrent access control and security — Built-in mechanisms (locks, MVCC) allow many users to work simultaneously while preserving correctness; role-based access and privileges protect data.
  • Indexes and performance optimisation — Indexes speed up searches and joins; query optimisers choose efficient execution plans.
  • Backup, recovery and durability — RDBMS tools support scheduled backups, point-in-time recovery and logging to restore data after crashes.
  • Interoperability and standards — Standard SQL and wide tool support make integration with applications, reporting tools and BI systems straightforward.

These features make RDBMS suitable for many real-life information systems where correctness, multi-user access and complex queries are required.

📌 Examples
  • Banking system: Transactions use ACID properties so a fund transfer either completes fully or not at all; foreign keys ensure accounts referenced exist.
  • School database: Student, Class and Enrollment tables use primary and foreign keys to model relationships and avoid repeating student details in many places.
  • E-commerce site: Product, Customer and Order tables allow complex queries (orders by customer, top-selling products) and indexes speed up search.
  • Hospital management: Patient records, Appointments and Prescriptions tables maintain data integrity and enable concurrent access by doctors and staff.
  • Airline reservation: Seats and bookings use transactions to prevent double-booking and ensure consistent seat inventory during high concurrency.
🧮 Formulas
  1. \[|R × S| = |R| * |S| (size of Cartesian product of relations R and S)\]
  2. \[|σ_condition(R)| ≤ |R| (selection returns at most as many tuples as R)\]
  3. \[|π_attrs(R)| ≤ |R| (projection returns at most as many tuples as R\]
    \[duplicates removed)\]
  4. \[|R ⋈ S| ≤ |R| * |S| (join result bounded by Cartesian product\]
    \[usually much smaller when join keys match)\]
  5. \[If A → B (functional dependency)\]
    \[then for any two tuples t1,t2 in R\]
    \[t1[A] = t2[A] ⇒ t1[B] = t2[B]\]
  6. \[Index improves search complexity: full table scan O(n) vs indexed search O(log n) (typical B-tree index)\]

Key Concepts

Relation
A relation is a table with rows and columns representing data; each row is a tuple and each column is an attribute.
Tuple (Row)
A tuple is a single row in a relation representing one record or fact.
Attribute (Column)
An attribute is a named column of a relation that describes a property of tuples.
Domain
Domain is the set of permissible values for an attribute.
Degree (Arity)
Degree is the number of attributes (columns) in a relation.
Cardinality
Cardinality is the number of tuples (rows) in a relation.
Relation Schema
Relation schema defines the name of a relation and its attributes with domains.
Primary Key
A primary key is an attribute or set of attributes that uniquely identifies each tuple in a relation.
Candidate Key
A candidate key is a minimal set of attributes that can uniquely identify tuples; one candidate key is chosen as primary key.
Super Key
A super key is any set of attributes that uniquely identifies tuples; it may include extra attributes beyond a candidate key.
Foreign Key
A foreign key is an attribute in one relation that refers to the primary key of another relation, establishing a link.
Referential Integrity
A rule that ensures foreign key values must either be null or match existing primary key values in the referenced relation.
Selection (σ)
Selection is a relational algebra operation that retrieves rows satisfying a given condition.
Projection (π)
Projection is a relational algebra operation that selects specific columns (attributes) from a relation.
Cartesian Product (×)
Cartesian product combines every tuple of one relation with every tuple of another, producing paired tuples.
Join (Natural Join ⨝)
Join combines tuples from two relations based on matching attribute values, typically equating common attributes.
Union (∪)
Union is a set operation that returns all distinct tuples present in either of two relations with the same schema.
Normalization
Normalization is the process of organizing relations to reduce redundancy and avoid anomalies by applying normal forms.
First Normal Form (1NF)
1NF requires that each attribute value is atomic (no repeating groups or arrays) and each tuple is unique.
Third Normal Form (3NF)
3NF requires a relation to be in 2NF and that no non-prime attribute is transitively dependent on the primary key.

Practice Questions

  1. Define degree and cardinality of a relation. / किसी रिलेशन के डिग्री और कार्डिनैलिटी को परिभाषित कीजिए।
    Show answer

    Degree is the number of attributes (columns) of a relation; cardinality is the number of tuples (rows) in its instance. / डिग्री किसी रिलेशन की एट्रिब्यूट्स (कॉलम) की संख्या है; कार्डिनैलिटी उसके इंस्टेंस में ट्यूपल्स (पंक्तियों) की संख्या है।

  2. Differentiate between a candidate key and a primary key. / कैंडिडेट की और प्राइमरी की में अंतर बताइए।
    Show answer

    A candidate key is a minimal superkey that uniquely identifies tuples; the primary key is the one candidate key chosen by the designer, which must be unique and NOT NULL. / कैंडिडेट की एक न्यूनतम सुपरकी है जो ट्यूपल्स की विशिष्ट पहचान करती है; प्राइमरी की डिज़ाइनर द्वारा चुनी गई एक कैंडिडेट की है जो यूनिक और NOT NULL होनी चाहिए।

  3. State the rule of referential integrity for a foreign key. / फॉरेन की के लिए रेफरेंशियल इंटीग्रिटी का नियम बताइए।
    Show answer

    A foreign key value in the child relation must either be NULL or match an existing primary key value in the referenced parent relation. / चाइल्ड रिलेशन में फॉरेन की का मान या तो NULL होना चाहिए या रेफरेंस की गई पैरेंट रिलेशन की किसी मौजूदा प्राइमरी की मान से मेल खाना चाहिए।

  4. Given Student(SID, RollNo, Name) where SID is unique and RollNo unique only within a branch, identify a candidate key and explain. / Student(SID, RollNo, Name) में जहाँ SID यूनिक है, एक कैंडिडेट की पहचानिए और समझाइए।
    Show answer

    SID is a candidate key because SID -> all attributes and no proper subset determines all attributes; hence its closure SID+ = R and it is minimal. / SID एक कैंडिडेट की है क्योंकि SID -> सभी एट्रिब्यूट्स और कोई उपसमुच्चय सभी का निर्धारण नहीं करता; अतः SID+ = R तथा यह न्यूनतम है।

  5. Explain the difference between a relation schema and a relation instance with an example. / रिलेशन स्कीमा और रिलेशन इंस्टेंस के बीच अंतर उदाहरण सहित समझाइए।
    Show answer

    Schema is the fixed structure R(A1,...,An), e.g. Student(AdmNo, Name, Class, DOB); the instance is the current set of tuples that changes with insert/update/delete. / स्कीमा निश्चित संरचना R(A1,...,An) है, जैसे Student(AdmNo, Name, Class, DOB); इंस्टेंस ट्यूपल्स का वर्तमान समुच्चय है जो insert/update/delete से बदलता है।

  6. Name the three update anomalies that poor design causes and give a one-line cause. / खराब डिज़ाइन से उत्पन्न तीन एनॉमलीज़ के नाम तथा एक-पंक्ति कारण दीजिए।
    Show answer

    Insertion (cannot add data without other unrelated data), Deletion (deleting a row loses other useful info), and Update anomaly (redundant copies require multiple consistent updates). / इंसर्शन (अन्य असंबंधित डेटा बिना जोड़ नहीं सकते), डिलीशन (पंक्ति हटाने से अन्य उपयोगी जानकारी खो जाती है), और अपडेट एनॉमली (अनावश्यक प्रतियों को कई बार सुसंगत रूप से बदलना पड़ता है)।

  7. State the condition for a relation to be in 2NF. / किसी रिलेशन के 2NF में होने की शर्त बताइए।
    Show answer

    The relation must be in 1NF and every non-prime attribute must be fully functionally dependent on the whole of every candidate key (no partial dependency on part of a composite key). / रिलेशन 1NF में हो तथा प्रत्येक नॉन-प्राइम एट्रिब्यूट प्रत्येक कैंडिडेट की के संपूर्ण भाग पर पूर्ण रूप से फंक्शनली निर्भर हो (कंपोजिट की के भाग पर आंशिक निर्भरता न हो)।

  8. What is a natural join and how does it differ from a Cartesian product? / नैचुरल जॉइन क्या है और यह कार्टीज़ियन प्रोडक्ट से कैसे भिन्न है?
    Show answer

    Natural join (R ⋈ S) combines tuples having equal values on all common attributes, keeping the common column once; Cartesian product (R × S) pairs every tuple of R with every tuple of S with no condition, giving |R|×|S| rows. / नैचुरल जॉइन (R ⋈ S) उन ट्यूपल्स को जोड़ता है जिनके सामान्य एट्रिब्यूट्स के मान समान हों, सामान्य कॉलम एक बार रखता है; कार्टीज़ियन प्रोडक्ट (R × S) बिना शर्त R के प्रत्येक ट्यूपल को S के प्रत्येक ट्यूपल से जोड़ता है, जिससे |R|×|S| पंक्तियाँ बनती हैं।

Related Laws & Principles

Explore all

Foundational laws & principles connected to this chapter — tap to open in the Laws Explorer.

Loading related laws…
Sourced from 189 content files · LLOS Learn · browse all chapters