Overview
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.
Relations
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)
| RollNo | Name | Age | Class |
|---|---|---|---|
| 101 | Rita | 17 | XII |
| 102 | Arun | 18 | XII |
| 103 | Maya | 17 | XII |
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).
- 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.
- \[Relation schema: R(A1\]\[A2, ...\]\[An)\]
- \[Relation instance: r(R) ⊆ Dom(A1) × Dom(A2) × ... × Dom(An)\]
- \[Degree = n (number of attributes)\]\[Cardinality = |r| (number of tuples)\]
- \[Primary key constraint: ∀ t1\]\[t2 ∈ r\]\[t1[PK] = t2[PK] ⇒ t1 = t2\]
- \[Functional dependency: A → B (if two tuples agree on A they must agree on B)\]
- \[Selection: σ_condition(R)\]\[Projection: π_A1,A2(R)\]\[Join: R ⋈ S\]\[Cartesian product: R × S\]
Components of a Relation
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):
| StudentID (PK) | Name | DOB | Major |
|---|---|---|---|
| 1001 | Asha | 2004-05-12 | Physics |
| 1002 | Rahul | 2003-11-04 | Math |
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.
- 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.
- \[Relation schema notation: R(A1:D1\]\[A2:D2, ...\]\[An:Dn) where Ai are attributes and Di are domains.\]
- \[Degree (arity): n = number of attributes in the heading.\]
- \[Cardinality: |R| = number of tuples (rows) currently in the relation.\]
- \[Tuple constraint: For any tuple t ∈ R\]\[t = <v1\]\[v2, ...\]\[vn> where vi ∈ Di for i = 1..n.\]
- \[Key uniqueness: For primary key PK, ∀t1\]\[t2 ∈ R\]\[t1.PK = t2.PK ⇒ t1 = t2 (i.e.\]\[PK values uniquely identify tuples).\]
Relation Schema and Relation Instance
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).
- 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.)
- \[Relation schema notation: R(A1\]\[A2, ...\]\[An)\]
- \[Instance as subset: r(R) ⊆ D1 × D2 × ... × Dn\]
- \[Degree (arity): degree(R) = n (number of attributes)\]
- \[Cardinality: card(r) = |r| (number of tuples in instance r)\]
- \[Uniqueness (primary key K): ∀ t1\]\[t2 ∈ r\]\[if t1[K] = t2[K] then t1 = t2\]
- \[Entity integrity: ∀ t ∈ r\]\[t[PK] ≠ NULL\]
Keys
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)
- Identify functional dependencies between attributes.
- Compute the attribute closure X+ for candidate sets X (attributes determined by X using dependencies).
- 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.
- 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.
- \[Functional dependency: X → Y (X determines Y)\]
- \[Attribute closure: X+ = set of attributes functionally determined by X\]\[If X+ contains all attributes of relation R\]\[then X is a superkey.\]
- \[Minimality condition for candidate key: X is a candidate key if X+ = R and for all proper subsets S of X\]\[S+ ≠ R.\]
- \[Upper bound on subsets: For a relation with n attributes\]\[number of non-empty attribute subsets = 2^n - 1 (upper bound on possible superkeys).\]
- \[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.\]
Integrity Constraints
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 );
- 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.
- \[Functional dependency: A -> B (A functionally determines B).\]
- \[Primary key rule: PK is UNIQUE and NOT NULL (no two rows share same PK value\]\[no NULL PKs).\]
- \[Referential integrity rule: For a foreign key FK referencing parent PK: FK is NULL OR FK ∈ {values of PK in parent table}.\]
- \[Superkey ⊇ Candidate key\]\[Candidate key is minimal superkey.\]
- \[SQL constraint examples: CONSTRAINT pk_student PRIMARY KEY (roll_no)\]\[FOREIGN KEY (dept_id) REFERENCES Department(dept_id) ON DELETE CASCADE\]\[CHECK (salary >= 0).\]
Relational Algebra — Basic Operations
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.
- 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.
- \[Selection: σ_condition(R)\]
- \[Projection: π_attr1,attr2,...(R)\]
- \[Union: R ∪ S (requires same schema)\]
- \[Difference: R - S (requires same schema)\]
- \[Intersection: R ∩ S = R - (R - S)\]
- \[Cartesian product: R × S\]
Relational Algebra — Additional Operations
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.
- 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.
- \[Intersection: R ∩ S = { t | t ∈ R AND t ∈ S } = R − (R − S)\]
- \[Natural Join: R ⋈ S = { r ∪ s | r ∈ R\]\[s ∈ S\]\[and r[commonAttrs] = s[commonAttrs] }\]
- \[Theta Join: R ⋈_{θ} S = σ_{θ}(R × S) where θ is any predicate comparing attributes of R and S\]
- \[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)\]
- \[Left Outer Join: R ⟕ S = (R ⋈ S) ∪ (R − π_R(R ⋈ S)) padded with NULLs for S's attributes (similarly for right ⟖ and full ⟗)\]
- \[Rename: ρ_{NewName} (R) or ρ_{NewName(attr1,attr2,...)}(R) — changes the relation/attribute names\]
Joins and Set Operations
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 isA ⋈_{condition} B. - Cross Join (Cartesian Product): Every row of A paired with every row of B. SQL:
SELECT ... FROM A CROSS JOIN B;orFROM 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.
- Left Outer Join: All rows from left table + matching rows from right table; non-matches have NULL for right-side columns. SQL:
- 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 usesMINUS. 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
ALLsuffix to keep duplicates (where supported).
Connection to relational algebra
- Join in relational algebra is often written as
A ⋈_{condition} B. Natural join isA ⋈ 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.
- 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.
- \[Relational algebra join: A ⋈_{A.key = B.key} B\]
- \[Natural join: A ⋈ B (matching common attribute names)\]
- \[Cartesian product: A × B\]
- \[Set union: R ∪ S (SQL: Q1 UNION Q2)\]
- \[Set intersection: R ∩ S (SQL: Q1 INTERSECT Q2)\]
- \[Set difference: R − S (SQL: Q1 EXCEPT Q2 or Q1 MINUS Q2)\]
Relational Database Design and Anomalies
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)
- List attributes and identify candidate keys using attribute closures (X+).
- List functional dependencies by analyzing semantics of data.
- Apply normalization rules: remove partial dependencies (to reach 2NF), remove transitive dependencies (to reach 3NF), and consider BCNF when necessary.
- 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).
- 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.
- \[Functional dependency: X → Y (X determines Y).\]
- \[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.\]
- \[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).\]
- \[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).\]
- \[BCNF condition: For every non-trivial FD X → Y\]\[X must be a superkey.\]
- \[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).\]
Functional Dependency
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.
- 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.
- \[FD notation: X -> Y (X and Y are sets of attributes)\]
- \[Trivial: If Y ⊆ X then X -> Y\]
- \[Reflexivity (Armstrong): If Y ⊆ X then X -> Y\]
- \[Augmentation (Armstrong): If X -> Y then XZ -> YZ\]
- \[Transitivity (Armstrong): If X -> Y and Y -> Z then X -> Z\]
- \[Closure computation: X+ = X ∪ {B | there exists Y -> B and Y ⊆ X+} (repeat until fixed point)\]
Normalization — Normal Forms
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)
- List attributes and determine all functional dependencies.
- Find candidate keys (use attribute closure X+ to test).
- Check 1NF, then 2NF (remove partial dependencies by decomposing), then 3NF (remove transitive dependencies), and if necessary BCNF.
- 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.
- 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).
- \[Functional dependency: X → Y (X and Y are attribute sets).\]
- \[Attribute closure: X+ = all attributes functionally determined by X (used to test keys).\]
- \[Key test: X is a superkey if X+ contains all attributes of the relation.\]
- \[1NF condition: all attribute values are atomic (no repeating groups).\]
- \[2NF condition: relation in 1NF and no non-prime attribute is partially dependent on a candidate key.\]
- \[3NF condition: for every FD X → A\]\[X is a superkey OR A is a prime attribute (part of some candidate key).\]
SQL Basics (often paired with relational concepts)
SQL Basics (often paired with relational concepts)
Key Point: Basic SELECT template:
SELECT What is SQL and the relational model? Core relational concepts SQL command categories Basic SELECT/query structure Notes: WHERE filters rows before grouping; HAVING filters groups after GROUP BY. Common clauses and concepts Data modification Schema definition example Transactions and integrity Normalization (brief) Practical tips Key Point: Selectivity = (matching_rows) / (total_rows) -- lower selectivity (smaller fraction) means index more useful Overview Views Indexes Example: combined use Practical tips 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: These features make RDBMS suitable for many real-life information systems where correctness, multi-user access and complex queries are required. Degree is the number of attributes (columns) of a relation; cardinality is the number of tuples (rows) in its instance. / डिग्री किसी रिलेशन की एट्रिब्यूट्स (कॉलम) की संख्या है; कार्डिनैलिटी उसके इंस्टेंस में ट्यूपल्स (पंक्तियों) की संख्या है। 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 होनी चाहिए। 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 होना चाहिए या रेफरेंस की गई पैरेंट रिलेशन की किसी मौजूदा प्राइमरी की मान से मेल खाना चाहिए। 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 तथा यह न्यूनतम है। 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 से बदलता है। 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). / इंसर्शन (अन्य असंबंधित डेटा बिना जोड़ नहीं सकते), डिलीशन (पंक्ति हटाने से अन्य उपयोगी जानकारी खो जाती है), और अपडेट एनॉमली (अनावश्यक प्रतियों को कई बार सुसंगत रूप से बदलना पड़ता है)। 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 में हो तथा प्रत्येक नॉन-प्राइम एट्रिब्यूट प्रत्येक कैंडिडेट की के संपूर्ण भाग पर पूर्ण रूप से फंक्शनली निर्भर हो (कंपोजिट की के भाग पर आंशिक निर्भरता न हो)। 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| पंक्तियाँ बनती हैं। Foundational laws & principles connected to this chapter — tap to open in the Laws Explorer. WHERE
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.
SELECT column_list
FROM table_name
WHERE conditions
GROUP BY column_list
HAVING group_conditions
ORDER BY column_list;
INSERT INTO table_name (col1, col2) VALUES (val1, val2);
UPDATE table_name SET col = new_val WHERE condition;
DELETE FROM table_name WHERE condition;
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)
);
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 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.
Views and Indexes
Views and Indexes
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.
CREATE VIEW view_name AS
SELECT column1, column2
FROM table_name
WHERE condition;
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
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.
Advantages of the Relational Model and RDBMS
Advantages of the Relational Model and RDBMS
Key Concepts
Practice Questions
Show answer
Show answer
Show answer
Show answer
Show answer
Show answer
Show answer
Show answer
Related Laws & Principles
Explore all