Welcome to DBMS
How to use this hub
Tap a unit button at the top, then a day. Or tap any class in the plan below to open its notes.
Read the day's notes before or right after class. Diagrams that look cut off on a phone scroll sideways.
Answer without looking back. Each answer explains why; re-read only the parts you got wrong.
Copy the amber Exam quick points into a revision notebook and answer the homework questions in your own words.
Open the SQL Lab before every lab session: try the examples, then solve that session's exercises.
Tell your teacher. Corrections and new units appear at this same link.
- Your SQL Lab progress and last open tab are saved in this browser only.
- The page follows your phone's light or dark mode.
- To jump straight to a day, add
#day7(or any day number) to the end of the link.
- Learning goals and a recap
- Notes with diagrams and College database examples
- Common mistakes
- Exam quick points
- A quiz and homework questions
The running example: College database
These four tables appear in every unit, in class notes, quizzes and the lab, so the examples build on each other.
| Table | Columns (key underlined in class) | Meaning |
|---|---|---|
| Department | dept_id, dept_name, hod | One row per department |
| Student | roll_no, name, dept_id, semester, email | Each student belongs to one department |
| Course | course_id, title, credits, dept_id | A department offers many courses |
| Enrollment | roll_no, course_id, semester, grade | Links students and courses (many-to-many) |
Theory plan, class by class
Tap a class to open its notes. Classes without a link are coming soon.
Lab plan: 20 sessions (MySQL)
Related experiments are grouped into 20 lab sessions. Students can practise every session at home in the SQL Lab, which has a browser SQL editor and 38 checked exercises.
| Lab | Practical work | Runs alongside |
|---|---|---|
| L1 | MySQL setup; CREATE DATABASE, USE, CREATE TABLE; data types | Unit I · D3 |
| L2 | Constraints: PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE, CHECK, DEFAULT | Unit II |
| L3 | INSERT, UPDATE, DELETE; ALTER and DROP | Unit II |
| L4 | SELECT with WHERE; comparison and logical operators; BETWEEN, IN, LIKE, IS NULL | Unit III · D12 |
| L5 | ORDER BY, DISTINCT, LIMIT; column aliases | Unit III |
| L6 | Aggregate functions: COUNT, SUM, AVG, MIN, MAX | Unit III · D15 |
| L7 | GROUP BY and HAVING | Unit IV · D17 |
| L8 | Set operations: UNION, UNION ALL; INTERSECT and EXCEPT (MySQL 8.0.31+) | Unit IV · D17 |
| L9 | Inner join, natural join, self join | Unit IV |
| L10 | LEFT and RIGHT outer joins; full outer join using UNION (MySQL has no FULL JOIN) | Unit IV |
| L11 | Nested subqueries with IN, ANY, ALL | Unit IV · D18 |
| L12 | Correlated subqueries; EXISTS and NOT EXISTS | Unit IV · D18 |
| L13 | Views: create, query, update through a view, drop | Unit IV · D18 |
| L14 | Stored procedures (DELIMITER, IN/OUT parameters) | Unit IV · D19 |
| L15 | Triggers: BEFORE/AFTER INSERT and UPDATE | Unit IV · D19 |
| L16 | Users and privileges: CREATE USER, GRANT, REVOKE | Unit IV · D20 |
| L17 | Normalization exercise: split an unnormalized table into 3NF tables in MySQL | Unit V |
| L18 | Transactions: START TRANSACTION, COMMIT, ROLLBACK, SAVEPOINT; autocommit | Unit VII |
| L19 | Indexes: CREATE INDEX, EXPLAIN a query before and after | Unit VI / VIII |
| L20 | Integrated College database exercise; lab exam practice | Revision |
Practise SQL in your browser
The SQL Lab has a real database engine running inside this page, already loaded with the College database. Type SQL, press Run, and see the result immediately. You can also create your own databases. You cannot break anything: Reset all brings back the original data. Use it to prepare before each lab session and to revise for the practical exam.
A free practice area with 25 ready-made examples, a list of tables and columns, and error messages explained in plain English.
38 tasks for Labs L1–L18. Write your answer and press Check answer; the page tells you whether your result is right and what to fix.
1How to use the editor
2The College database
Five related tables. Arrows go from a foreign key to the primary key it refers to. This is the same design you studied in Units II and III, with a few extra columns.
| Table | Rows | Special rows to test your queries |
|---|---|---|
| Department | 4 | Physics (PHY) has only one student. |
| Faculty | 7 | Salaries from 68000 to 120000 for GROUP BY and HAVING. |
| Student | 12 | Dev (112) has no department (NULL). Rohan (108) has no email. |
| Course | 8 | Graph Theory (MA301) has no teacher and no students. |
| Enrollment | 18 | Sneha's Data Structures marks are NULL (result pending). Rohan and Dev are not enrolled in anything. |
3Your first five queries
Press Try it to load each query into the editor.
- See what tables exist.
SHOW TABLES; - See a table's columns and types.
DESCRIBE Student; - See all rows.
SELECT * FROM Department; - Choose columns and rows.
SELECT name, semester FROM Student WHERE dept_id = 'CSE'; - Sort the result.
SELECT name, semester FROM Student ORDER BY semester DESC, name;
4Creating your own database
When the Editor opens, the college database is already selected. In Lab 1 you will create your own, exactly as in MySQL:
| Command | What it does | MySQL reply |
|---|---|---|
CREATE DATABASE library; | Makes a new, empty database | Query OK, 1 row affected |
USE library; | Opens it; tables you create now go into it | Database changed |
SHOW DATABASES; | Lists all databases | A table of names |
SELECT DATABASE(); | Shows which database is open | The current name |
DROP DATABASE library; | Deletes the database and all its tables | Query OK |
- Create a library database with one table, then look inside it.
CREATE DATABASE library; USE library; CREATE TABLE Book ( book_id INT PRIMARY KEY, title VARCHAR(100) NOT NULL, author VARCHAR(60), price DECIMAL(8,2) CHECK (price > 0) ); INSERT INTO Book VALUES (1, 'Database System Concepts', 'Silberschatz', 850.00), (2, 'Fundamentals of Database Systems', 'Elmasri', 720.50); SHOW TABLES; SELECT * FROM Book; - Switch back to the college database.
SHOW DATABASES; USE college; SELECT DATABASE();
- Run
CREATE DATABASE library;twice and you get an error: the database exists. WriteCREATE DATABASE IF NOT EXISTS library;to avoid it. - After
DROP DATABASEon the open database, nothing is selected; runUSEagain. - Databases you create live only in this browser tab. They disappear when you reload the page or press Reset all, so keep your SQL in your lab notebook.
5How a SELECT is built
You must write the clauses in this order. Only SELECT and FROM are required; leave out what you do not need.
The database runs them in a different order. This explains two common errors.
- WHERE runs before grouping, so it cannot use COUNT, SUM or AVG. Use HAVING for conditions on groups.
- SELECT runs after WHERE, so a column alias made in SELECT cannot be used in WHERE. It can be used in ORDER BY.
6Beginner rules
| Rule | Right | Wrong |
|---|---|---|
| End each statement with ; | SELECT * FROM Student; | Two statements with no ; between them |
| Text and dates in single quotes | city = 'Kolkata' | city = Kolkata (read as a column name) |
| Numbers without quotes | semester = 3 | semester = '3' works but is a bad habit |
| Keywords: any case | SELECT = select (write keywords in CAPITALS for neatness) | — |
| Check NULL with IS | email IS NULL | email = NULL (always false) |
| Not equal | <> or != | =! |
| Commas between columns only | SELECT name, city FROM … | SELECT name, city, FROM … |
| Comments | -- this line is ignored | — |
| Always use WHERE with UPDATE and DELETE | DELETE FROM Enrollment WHERE roll_no = 107; | DELETE FROM Enrollment; deletes every row |
7Reading error messages
| Message contains | What it means | Usual fix |
|---|---|---|
| No database selected | No database is open | USE college; (or the one you created) |
| database exists | CREATE DATABASE with a name already used | Use a new name, or IF NOT EXISTS |
| no such table | The table name is wrong or not created | Check spelling with SHOW TABLES |
| no such column | Column name is wrong, or text is missing quotes | DESCRIBE the table; quote text values |
| syntax error near "…" | SQL could not read the words around "…" | Look just before it: missing comma, bracket or keyword |
| UNIQUE / PRIMARY KEY failed | That value already exists | Use a new key value |
| NOT NULL failed | A required column was left empty | Give that column a value |
| CHECK failed | A rule rejected the value | Use a value inside the allowed range |
| FOREIGN KEY failed | The referenced value does not exist | Insert the parent row first, or use an existing value |
| ambiguous column name | Two joined tables have that column | Write it as s.dept_id |
| misuse of aggregate | COUNT/SUM/AVG used in WHERE | Move the condition to HAVING |
8Browser editor vs MySQL in the lab
The editor runs SQLite, a small database engine, with a layer that accepts MySQL-style commands. Almost everything in this course works the same. The differences:
| Works the same | Translated for you | Practise in MySQL only |
|---|---|---|
| SELECT, WHERE, LIKE, BETWEEN, IN, IS NULL, ORDER BY, LIMIT, DISTINCT, aggregates, GROUP BY, HAVING, joins (inner, left, right), UNION, INTERSECT, EXCEPT, subqueries, EXISTS, views, constraints, INSERT, UPDATE, DELETE, ALTER TABLE ADD, SAVEPOINT, ROLLBACK, COMMIT | SHOW TABLES, DESCRIBE, START TRANSACTION, TRUNCATE, AUTO_INCREMENT, CONCAT, NOW(), CURDATE(), YEAR(), MONTH(), DATEDIFF(). CREATE DATABASE, USE, DROP DATABASE and SHOW DATABASES work in the Editor (inside Exercises they are skipped, because each exercise uses a fresh College database) | Stored procedures (CREATE PROCEDURE, CALL, DELIMITER), GRANT, REVOKE, CREATE USER, > ANY / > ALL. Trigger syntax is slightly different: no DELIMITER is needed here. |
The editor shows a note whenever it translates or skips something, so you always know.
9Writing your lab record
10Keyboard shortcuts
| Keys | Action |
|---|---|
| Ctrl + Enter / ⌘ + Enter | Run (in the editor) or Check answer (in an exercise) |
| Tab | Insert two spaces |
| Select text, then Run | Run only the selected part |
SQL editor
SELECT * FROM Student;Tables and columns
Tap a table to insert SELECT * FROM …; tap a column to insert its name.
History
Queries you run appear here.
Lab exercises
Each task runs on a fresh copy of the College database, so earlier tasks never affect later ones. Write your SQL, press Check answer, and read the feedback. Use Hint before Show solution. Your progress is saved in this browser.
File System vs DBMS, and Client–Server Architecture
- List the problems of a file-processing system.
- Explain how a DBMS solves them.
- State 5 advantages and 4 disadvantages of a DBMS.
- Draw 2-tier and 3-tier architecture.
file-processing system · redundancy · inconsistency · atomicity · concurrency · client · server · tier
1.1The file-processing system
Before databases, every office in the college kept its own files and wrote its own program to handle them. The Accounts office had a fees file, the Exam cell had a marks file, and the Library had a members file. Each file stored the student's name and address again.
A file-processing system stores data in separate operating-system files. Each file is created and handled by its own application program, and there is no central control over the data.
1.2Problems with the file-processing system
Learn these seven. They are the most common 5-mark question in Unit I.
| Problem | What it means | College example |
|---|---|---|
| Data redundancy | The same data is stored in many files. | Address is in fees, marks and library files. |
| Data inconsistency | Copies of the same data disagree. | Address changed in fees file but not in library file. |
| Difficulty accessing data | Every new question needs a new program. | "List students from Barasat with fees due" needs new code. |
| Data isolation | Data is scattered in files of different formats. | Fees file is CSV, marks file is a spreadsheet. |
| Integrity problems | Rules are buried inside program code, hard to change. | "Marks must be 0–100" is checked in only one program. |
| Atomicity problems | A failure leaves work half done. | Fee is debited but the receipt is never recorded. |
| Concurrent-access anomalies | Two users updating together corrupt the data. | Two clerks issue the last library copy to two students. |
| Security problems | Hard to give each user access to only some data. | Library staff can open the marks file. |
A file system is like every teacher keeping their own attendance register. A DBMS is like one central register that everyone reads through the office, with rules about who can write in it.
1.3What a DBMS does
A Database Management System (DBMS) is software that stores a collection of related data and provides programs to define, store, retrieve, update and protect that data efficiently. Examples: MySQL, Oracle, PostgreSQL, Microsoft SQL Server.
- Controls redundancy — data is stored once.
- Consistency — one copy means no disagreement.
- Easy data access — ask questions in SQL, no new program.
- Integrity constraints — rules like
CHECK (marks BETWEEN 0 AND 100)are stored centrally. - Security — each user gets only the access they need.
- Concurrency control — many users work safely at once.
- Backup and recovery — data survives crashes.
- Data independence — storage can change without changing programs (Day 4).
- Data sharing and enforced standards.
- High cost — software licences, hardware and trained staff.
- Complexity — design and administration need expertise.
- Large size — needs disk space and memory.
- Performance overhead — slower than a plain file for very small, simple jobs.
- Higher impact of failure — when the central database is down, every office stops.
- Conversion cost — moving old files into a database takes effort.
1.4Client–server architecture
A client is the program the user works with (a browser, a mobile app, MySQL Workbench). A server is the machine and program that stores the database and answers requests. The number of layers between them is called the number of tiers.
| Point | 2-tier | 3-tier |
|---|---|---|
| Layers | Client, database server | Client, application server, database server |
| Business logic | Inside the client | Inside the application server |
| Client reaches DB | Directly | Never directly |
| Security | Lower | Higher |
| Scalability | Few users | Thousands of users |
| Example | Lab PC running MySQL Workbench | College result website |
1-tier means the user, application and database are all on one machine, for example MySQL installed and used on your own laptop.
- Writing "DBMS has no redundancy." It controls redundancy; some controlled redundancy is still allowed.
- Calling a database and a DBMS the same thing. The database is the data; the DBMS is the software.
- Drawing 3-tier with the client connected straight to the database.
- File system problems (remember "R-I-D-I-I-A-C-S"): Redundancy, Inconsistency, Difficult access, Isolation, Integrity, Atomicity, Concurrency, Security.
- Every problem has a matching DBMS advantage — write them as a 2-column table in a 5-mark answer.
- Disadvantages: cost, complexity, size, overhead, failure impact.
- 3-tier adds an application server; the client never talks to the database directly.
- Always draw the diagram in architecture questions; it carries marks.
- Define a file-processing system. [2 marks]
- Explain any four drawbacks of a file-processing system with examples. [5 marks]
- Differentiate between 2-tier and 3-tier architecture with a neat diagram. [5 marks]
- Think of a shop near your home that keeps paper registers. List two problems a DBMS would fix for it. [activity]
Database Fundamentals: Users, DBA and Data Models
- Tell data from information.
- Define database, DBMS and database system.
- Name four types of database users and the DBA's duties.
- Compare the main data models.
Name three problems of the file system. What does the middle layer do in 3-tier architecture?
2.1Data vs information
Raw facts with no context: 78, Ananya, CSE.
Processed data that has meaning and helps a decision: "Ananya topped CSE with 78."
2.2Database, DBMS and database system
| Term | Meaning | College example |
|---|---|---|
| Database | An organised collection of related data. | All tables about students, courses and departments. |
| DBMS | Software that manages the database. | MySQL |
| Database system | Database + DBMS + application programs (+ users). | The full college ERP |
2.3Database users
Different people use the same database in different ways. Classify them by how they interact with it.
| User type | How they use the database | College example |
|---|---|---|
| Naive (end) users | Use ready-made screens; know no SQL. | A student checking results on the portal; a fees clerk. |
| Application programmers | Write programs that use the database (Java, Python, PHP with SQL). | Developer who builds the result portal. |
| Sophisticated users | Write their own SQL queries or use analysis tools. | An analyst finding the pass percentage by department. |
| Specialized users | Write special database applications (expert systems, CAD, multimedia). | Research team storing satellite or medical images. |
| Database Administrator | Has central control over data and the DBMS. | College IT in-charge. |
Elmasri–Navathe divide end users a little differently: casual, naive (parametric), sophisticated and standalone users. Either classification earns marks if you explain each type.
Duties of the DBA
- Schema definition — creates the table design using DDL.
- Storage structure and access methods — decides files and indexes.
- Schema and physical changes — adapts the design as needs change.
- Granting authorization — decides who can read or change what (
GRANT,REVOKE). - Routine maintenance — backups, free disk space, monitoring, performance tuning.
- Recovery — restores data after a crash.
The DBA is like the college librarian: decides how books are arranged, who gets a library card, keeps a register of every book and repairs damage. Students only borrow; they never rearrange the shelves.
2.4Data models
A data model is a collection of concepts used to describe the structure of a database: the data, the relationships between data, what the data means, and the constraints on it.
| Model | Data is stored as | Notes |
|---|---|---|
| Relational | Tables (relations) of rows and columns | Most used today. MySQL, Oracle. Units III–V. |
| Entity–Relationship | Entities, attributes, relationships (diagram) | Used for design. Unit II. |
| Object-based | Objects with attributes and methods | Extends ER with OOP ideas. |
| Semi-structured | Tagged data where items can differ (XML, JSON) | Used in web APIs and NoSQL stores. |
| Hierarchical | A tree: one parent, many children | Historical (IBM IMS). |
| Network | A graph: a child can have many parents | Historical (CODASYL). |
Some textbooks (Navathe) group models by level instead: high-level/conceptual (ER), representational/implementation (relational, network, hierarchical) and low-level/physical (how data sits on disk). Both groupings are standard: learn the four Korth categories and mention the Navathe levels for full marks.
-- The same student in the relational model (a table row)
roll_no | name | dept_id | semester
101 | Ananya | CSE | 3
-- …and in the semi-structured model (JSON)
{ "roll_no": 101, "name": "Ananya", "dept": "CSE",
"phones": ["98xxxxxx01", "98xxxxxx02"] }- Calling the DBA a "naive user". The DBA has the most control of anyone.
- Saying "ER model stores data". ER is a design model; tables are built from it later.
- Writing "data and information are the same".
- Data = raw facts; information = processed, meaningful data.
- Database system = database + DBMS + applications.
- Users: naive, application programmers, sophisticated, specialized, plus the DBA.
- DBA duties: schema definition, storage structure, authorization, maintenance, backup and recovery.
- Data model = structure + relationships + semantics + constraints.
- Relational model = data in tables; ER = design diagram; JSON/XML = semi-structured.
- Differentiate between data and information with an example. [2 marks]
- What is a DBA? Explain the functions of a DBA. [5 marks]
- Explain different types of database users. [5 marks]
- What is a data model? Briefly describe any three data models. [5 marks]
Database Languages and Schema vs Instance
- Name the SQL language groups (DDL, DML, DCL, TCL) and their commands.
- Write a simple
CREATE,INSERTandSELECTin MySQL. - Explain schema vs instance with an example.
Who grants permissions in a database? What is a relational model?
3.1Database languages
A DBMS gives us languages to talk to it. Standard textbooks name two main parts, the Data Definition Language (DDL) and the Data Manipulation Language (DML). In SQL (Structured Query Language) these sit beside commands for access control and transactions, giving four groups.
Silberschatz–Korth–Sudarshan and Elmasri–Navathe both define DML as the language to retrieve, insert, delete and modify data, so SELECT is part of DML. Some lab manuals and websites list SELECT separately as DQL (Data Query Language). In the exam, write SELECT under DML; you may add "sometimes called DQL".
DDL — Data Definition Language
Creates and changes the structure (schema). In MySQL, DDL commands commit automatically and cannot be rolled back.
CREATE DATABASE college;
USE college;
CREATE TABLE Department (
dept_id VARCHAR(5) PRIMARY KEY,
dept_name VARCHAR(50) NOT NULL,
hod VARCHAR(50)
);
CREATE TABLE Student (
roll_no INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
dept_id VARCHAR(5),
semester TINYINT,
FOREIGN KEY (dept_id) REFERENCES Department(dept_id)
);
ALTER TABLE Student ADD email VARCHAR(80); -- add a column
TRUNCATE TABLE Student; -- delete all rows, keep the table
DROP TABLE Student; -- delete rows AND the tableDML — Data Manipulation Language
DML lets users retrieve and change data. Its retrieval part is called the query language (SELECT). Textbooks also classify DMLs as procedural (the user says what data is needed and how to get it) or declarative / non-procedural (the user says only what is needed). SQL's DML is declarative.
INSERT INTO Department VALUES ('CSE', 'Computer Science', 'Dr. Sen');
INSERT INTO Student (roll_no, name, dept_id, semester)
VALUES (101, 'Ananya', 'CSE', 3), (102, 'Rahul', 'CSE', 3);
UPDATE Student SET semester = 4 WHERE roll_no = 101;
DELETE FROM Student WHERE roll_no = 102;DML query — SELECT
SELECT name, semester
FROM Student
WHERE dept_id = 'CSE';DCL — Data Control Language
GRANT SELECT ON college.Student TO 'clerk'@'localhost';
REVOKE SELECT ON college.Student FROM 'clerk'@'localhost';TCL — Transaction Control Language
START TRANSACTION;
UPDATE Student SET semester = 5 WHERE roll_no = 101;
SAVEPOINT s1;
DELETE FROM Student WHERE roll_no = 101;
ROLLBACK TO s1; -- the DELETE is undone, the UPDATE stays
COMMIT; -- the UPDATE is now permanent| Point | DELETE | TRUNCATE | DROP |
|---|---|---|---|
| Group | DML | DDL | DDL |
| Removes | Chosen rows (WHERE) | All rows | Rows + table structure |
| Table remains? | Yes | Yes | No |
| Rollback in MySQL | Yes, inside a transaction | No | No |
3.2Schema vs instance
The overall design of the database: table names, columns, types and constraints. It changes rarely.
The data stored in the database at one moment in time. It changes every time data is inserted, updated or deleted.
| roll_no | name | dept_id | semester |
|---|---|---|---|
| 101 | Ananya | CSE | 3 |
| 102 | Rahul | CSE | 3 |
| 103 | Priya | ECE | 3 |
The schema is the blank admission form printed by the college. The instance is the stack of filled forms in the office today. In programming: int marks; is the schema, marks = 78 is the instance.
A database has schemas at three levels — physical, logical and view (subschema). These lead straight into Day 4.
- DDL: CREATE, ALTER, DROP, TRUNCATE, RENAME — works on structure.
- DML: SELECT, INSERT, UPDATE, DELETE — retrieves and changes data. SELECT is the query part of DML (sometimes called DQL).
- DCL: GRANT, REVOKE. TCL: COMMIT, ROLLBACK, SAVEPOINT.
- DELETE is DML; TRUNCATE and DROP are DDL.
- Schema = design, changes rarely. Instance = snapshot of data, changes often.
- Schema is also called the intension; instance the extension or state.
- Differentiate between schema and instance. [2 marks]
- Explain DDL, DML and DCL with two commands each. [5 marks]
- Write MySQL statements to create the
Coursetable (course_id, title, credits, dept_id) with a primary key and a foreign key to Department. [lab prep] - Differentiate between DELETE, TRUNCATE and DROP. [5 marks]
Three-Schema Architecture and Data Independence
- Draw the three-schema (ANSI/SPARC) architecture.
- Explain each level and the two mappings.
- Define and compare logical and physical data independence.
What is a schema? Is ALTER TABLE a change to the schema or the instance?
4.1Why three levels?
A student, the accounts clerk and the DBA all use the same college database, but each needs to see something different. The student sees only their own marks. The clerk sees fees. The DBA cares about disk files and indexes. The three-schema architecture separates what users see from what the data is from how it is stored.
The three-schema architecture (proposed by the ANSI/SPARC committee) describes a database at three levels — external, conceptual and internal — so that user applications are kept apart from the physical database.
Silberschatz–Korth calls the same three levels the view level, logical level and physical level.
4.2The three levels
| Level | Describes | Who uses it | How many | College example |
|---|---|---|---|---|
| External (view) | The part of the database one user group needs; hides the rest | End users, application programs | Many | Student sees only their marks |
| Conceptual (logical) | The whole database: entities, data types, relationships, constraints; no storage detail | DBA, designers | One | The four College tables and their keys |
| Internal (physical) | How data is stored: files, record layout, indexes, access paths | DBA, DBMS | One | Index on roll_no; data file on disk |
In MySQL, an external schema is usually written as a view:
-- External level: the accounts office never sees grades
CREATE VIEW accounts_view AS
SELECT roll_no, name, dept_id
FROM Student;4.3Mappings
A mapping is the rule the DBMS uses to convert a request and its result from one level to another.
- External/conceptual mapping — converts a query on a view into a query on the full tables.
- Conceptual/internal mapping — converts a query on tables into reads of files and indexes on disk.
4.4Data independence
Data independence is the ability to change the schema at one level without having to change the schema at the next higher level.
Change the conceptual schema without changing external schemas or application programs.
Example: add an email column to Student. accounts_view and the result portal keep working.
Harder to achieve, because programs depend on table structure.
Change the internal schema without changing the conceptual schema.
Example: CREATE INDEX idx_name ON Student(name); or move the data to a faster SSD. Tables and queries stay the same.
Easier to achieve; most DBMSs support it well.
| Point | Logical | Physical |
|---|---|---|
| Change happens at | Conceptual level | Internal level |
| Protected level | External level / applications | Conceptual level |
| Mapping involved | External/conceptual | Conceptual/internal |
| Example change | Add/remove a column or table | Add index, change file organization, change disk |
| Difficulty | Harder | Easier |
Think of a restaurant. Customers read the menu (external). The kitchen works from the recipe book (conceptual). The storeroom layout is internal. Rearranging the storeroom does not change recipes (physical independence). Adding a new recipe does not reprint every customer's favourite dish on the menu (logical independence).
- Swapping the two: remember Logical ↔ Level of tables; Physical ↔ Physical storage.
- Drawing many conceptual schemas. There is only one conceptual and one internal schema, but many external schemas.
- Leaving the mappings out of the diagram.
- Three levels: External (view) → Conceptual (logical) → Internal (physical). Proposed by ANSI/SPARC.
- Many external schemas; exactly one conceptual and one internal schema.
- Two mappings: external/conceptual and conceptual/internal.
- Logical independence: change conceptual, external unaffected — harder.
- Physical independence: change internal, conceptual unaffected — easier.
- 10-mark answer = diagram + three levels + two mappings + both independences with examples.
- What is data independence? [2 marks]
- Differentiate between logical and physical data independence. [5 marks]
- Explain the three-schema architecture of a DBMS with a neat diagram. [10 marks]
- For each change, write L (logical) or P (physical): (a) add an index on
course_id; (b) split Student into two tables; (c) move the database to a new disk; (d) add aphonecolumn. [practice]
Unit I Revision and Test
This class pulls Unit I together. Use the one-page summary to revise, practise the three diagrams, then take the 10-question test. The written questions below match the pattern of university papers.
5.1Unit I on one page
| Topic | Remember this | Day |
|---|---|---|
| File system problems | Redundancy, inconsistency, difficult access, isolation, integrity, atomicity, concurrency, security | 1 |
| DBMS advantages | Controlled redundancy, consistency, sharing, integrity, security, concurrency, backup and recovery, data independence | 1 |
| DBMS disadvantages | Cost, complexity, size, performance overhead, high impact of failure | 1 |
| Client–server | 2-tier: client ↔ DB. 3-tier: client ↔ app server ↔ DB | 1 |
| Data vs information | Raw facts vs processed, meaningful data | 2 |
| Users | Naive, application programmer, sophisticated, specialized, DBA | 2 |
| DBA duties | Schema definition, storage, authorization, maintenance, backup and recovery | 2 |
| Data models | Relational, ER, object-based, semi-structured (hierarchical, network = historical) | 2 |
| Languages | DDL, DML (including SELECT), DCL, TCL; procedural vs declarative DML | 3 |
| Schema vs instance | Design (rarely changes) vs data snapshot (often changes) | 3 |
| Three-schema | External (many) → conceptual (one) → internal (one), two mappings | 4 |
| Data independence | Logical (harder) and physical (easier) | 4 |
5.2Diagrams you must be able to draw
- File system vs database approach (Figure 1.1)
- 2-tier and 3-tier architecture (Figure 1.2)
- SQL language groups tree (Figure 3.1)
- Three-schema architecture with mappings (Figure 4.1) — most important
Practise each one from memory in under three minutes, then compare with the figure.
5.3Unit I test
5.4Written questions with answer outlines
- Define DBMS. Give two examples. [2 marks]
Software to define, store, retrieve, update and protect related data; MySQL, Oracle. - What is a schema? [2 marks]
The overall design of a database (tables, columns, types, constraints); changes rarely. - Explain the disadvantages of a file-processing system. [5 marks]
Any five problems, each with one line of meaning and one college example. - Write the roles of a DBA. [5 marks]
Schema definition; storage and access methods; schema changes; authorization; routine maintenance; recovery. - Classify SQL commands with examples. [5 marks]
Figure 3.1 + one example statement per group. - Explain the three-schema architecture and data independence. [10 marks]
Figure 4.1; three levels with who/what; two mappings; logical vs physical table with examples.
- 2 marks: definition + one example. Stop there.
- 5 marks: definition, 4–5 points or a difference table, one example.
- 10 marks: diagram first, then explain each part of the diagram, then a comparison table, then a short conclusion.
- Use the College database in examples; examiners notice applied answers.
Unit I revision
Everything to revise for Unit I in one place: the exam quick points from every class, the diagrams to practise drawing, and one quiz that mixes all the day quizzes. Tap Open notes whenever a point needs more explanation.
Exam quick points, class by class
- File system problems (remember "R-I-D-I-I-A-C-S"): Redundancy, Inconsistency, Difficult access, Isolation, Integrity, Atomicity, Concurrency, Security.
- Every problem has a matching DBMS advantage — write them as a 2-column table in a 5-mark answer.
- Disadvantages: cost, complexity, size, overhead, failure impact.
- 3-tier adds an application server; the client never talks to the database directly.
- Always draw the diagram in architecture questions; it carries marks.
- Data = raw facts; information = processed, meaningful data.
- Database system = database + DBMS + applications.
- Users: naive, application programmers, sophisticated, specialized, plus the DBA.
- DBA duties: schema definition, storage structure, authorization, maintenance, backup and recovery.
- Data model = structure + relationships + semantics + constraints.
- Relational model = data in tables; ER = design diagram; JSON/XML = semi-structured.
- DDL: CREATE, ALTER, DROP, TRUNCATE, RENAME — works on structure.
- DML: SELECT, INSERT, UPDATE, DELETE — retrieves and changes data. SELECT is the query part of DML (sometimes called DQL).
- DCL: GRANT, REVOKE. TCL: COMMIT, ROLLBACK, SAVEPOINT.
- DELETE is DML; TRUNCATE and DROP are DDL.
- Schema = design, changes rarely. Instance = snapshot of data, changes often.
- Schema is also called the intension; instance the extension or state.
- Three levels: External (view) → Conceptual (logical) → Internal (physical). Proposed by ANSI/SPARC.
- Many external schemas; exactly one conceptual and one internal schema.
- Two mappings: external/conceptual and conceptual/internal.
- Logical independence: change conceptual, external unaffected — harder.
- Physical independence: change internal, conceptual unaffected — easier.
- 10-mark answer = diagram + three levels + two mappings + both independences with examples.
Diagrams to practise
Draw each one from memory in under three minutes, then open the class to compare.
- Figure 1.1 — The same three offices, before and after a database.
- Figure 1.2 — 2-tier and 3-tier client–server architecture.
- Figure 2.1 — A query turns data into information.
- Figure 3.1 — The four groups of SQL commands. SELECT belongs to DML, as in standard textbooks.
- Figure 4.1 — Three-schema architecture for the College database. Draw this in every answer on the topic.
Mixed quiz
Designing a database on paper
In Unit I we learnt what a DBMS is. Before we create any table, we must design the database: what things we store, what we know about them, and how they are connected. The Entity–Relationship (ER) model, proposed by Peter Chen in 1976, is the drawing language for this design. In Unit III the ER diagram becomes tables, and in the lab those tables become MySQL code.
CREATE TABLE with keys and constraints in MySQL.Unit map
| Day | Topics | Syllabus item |
|---|---|---|
| D6 | Entities, entity sets, attributes and their types, domain, NULL | Entity sets; attributes |
| D7 | Super, candidate, primary, alternate, composite and foreign keys | Keys |
| D8 | Relationship sets, degree, mapping cardinality, participation | Relationship sets; constraints on relationships |
| D9 | ER notation, drawing the College ER diagram, weak entity sets | ER diagrams; weak entity sets |
| D10 | Specialization, generalization, inheritance, aggregation; Unit II test | Extended ER features |
ER symbol cheat sheet (Chen notation)
These are the symbols used in most Indian university papers (Korth/Navathe style). Draw them neatly with a scale; marks are lost for wrong shapes.
| Symbol | Name | Meaning |
|---|---|---|
| Entity set | A rectangle. A group of similar things. | |
| Weak entity set | Double rectangle. Cannot be identified without its owner (Day 9). | |
| Attribute | Ellipse joined to its entity by a line. | |
| Key attribute | Name underlined. Uniquely identifies an entity. | |
| Partial key (discriminator) | Dashed underline. Key of a weak entity within its owner. | |
| Multivalued attribute | Double ellipse. Can hold several values. | |
| Derived attribute | Dashed ellipse. Calculated from another attribute. | |
| Composite attribute | Ellipse with its parts attached as smaller ellipses. | |
| Relationship set | Diamond. Connects entity sets. | |
| Identifying relationship | Double diamond. Links a weak entity to its owner. | |
| Total participation | Double line. Every entity must take part. | |
| Cardinality | 1, N or M written on the lines: 1:1, 1:N, M:N. | |
| ISA (specialization) | Triangle. Superclass above, subclasses below (Day 10). |
Elmasri–Navathe and most university papers use the Chen notation shown here (ellipses for attributes, diamonds for relationships). Silberschatz–Korth (6th and 7th editions) lists attributes inside the entity rectangle instead, and design tools often use crow's-foot lines. The ideas are identical. Use Chen notation in theory exams.
Entities, Entity Sets and Attributes
- Tell an entity from an entity set.
- Classify any attribute into its type.
- Draw an entity with all its attributes in Chen notation.
Which data model is used for design? (ER.) Which is used to store data in MySQL? (Relational.)
6.1Entity and entity set
A real-world thing or object that can be identified separately from others. It can be physical (a student, a book) or conceptual (a course, a loan).
Example: the student Ananya, roll number 101.
A collection of entities of the same type that share the same properties.
Example: all students of the college form the entity set Student.
An entity set is like a class in programming; an entity is one object of that class. In a table, the entity set becomes the table and each entity becomes one row.
College entity sets we will use: Student, Department, Course, Faculty, Section.
6.2Attributes and domain
An attribute is a property that describes an entity. The domain (value set) of an attribute is the set of values it is allowed to take.
| Attribute of Student | Domain | MySQL type later |
|---|---|---|
| roll_no | Positive whole numbers | INT |
| name | Text up to 50 characters | VARCHAR(50) |
| semester | 1 to 8 | TINYINT CHECK (semester BETWEEN 1 AND 8) |
| dob | Valid calendar dates | DATE |
6.3Types of attributes
| Type | Meaning | Example | Symbol |
|---|---|---|---|
| Simple (atomic) | Cannot be divided further | roll_no, dob | Ellipse |
| Composite | Made of smaller parts | name = first_name + last_name; address = street + city + pin | Ellipse with sub-ellipses |
| Single-valued | One value per entity | dob | Ellipse |
| Multivalued | Several values per entity | phone, email IDs | Double ellipse |
| Stored | Value is saved in the database | dob | Ellipse |
| Derived | Value is calculated from another attribute | age (from dob), CGPA (from grades) | Dashed ellipse |
| Key | Uniquely identifies each entity | roll_no | Underlined |
These pairs are independent: address is composite and single-valued; phone is simple and multivalued.
6.4NULL values
An attribute takes the special value NULL when a value does not exist for that entity. NULL means one of two things:
- Not applicable — a day scholar has no
hostel_room. - Unknown — the value exists but is not known yet (a missing email), or we do not know whether it exists.
NULL is not zero and not an empty string. Key attributes can never be NULL.
- Drawing a derived attribute with a double ellipse. Derived = dashed; multivalued = double.
- Calling Ananya an entity set. She is one entity; Student is the set.
- Storing age. Store dob and derive age, or it goes wrong every birthday.
- Entity = one real-world object; entity set = collection of similar entities.
- Attribute = property; domain = allowed values.
- Types: simple/composite, single/multivalued, stored/derived, key.
- Symbols: double ellipse = multivalued; dashed ellipse = derived; underline = key.
- NULL = not applicable or unknown.
- Define entity and entity set with examples. [2 marks]
- Explain the types of attributes with ER symbols and examples. [5 marks]
- Draw the Faculty entity with: faculty_id (key), name (first, last), phone (many), date_of_joining, experience (derived), salary. [practice]
Keys
- Define super, candidate, primary, alternate, composite and foreign keys.
- Find all candidate keys of a small table.
- Write PRIMARY KEY and FOREIGN KEY in MySQL.
Which attribute type is shown underlined? Can a key attribute be NULL?
7.1Why we need keys
Two students can both be called "Rahul Das". The college still has to tell them apart, find the right marks and send the right result. A key is an attribute, or a set of attributes, whose values are different for every entity.
We use this table all class. Assume roll_no is unique, email is unique, and two students may share a name or a department.
| roll_no | name | dept_id | |
|---|---|---|---|
| 101 | ananya@clg.edu | Ananya Roy | CSE |
| 102 | rahul.d@clg.edu | Rahul Das | CSE |
| 103 | rahul.das2@clg.edu | Rahul Das | ECE |
7.2Types of keys
| Key | Definition | Student example |
|---|---|---|
| Super key | Any set of attributes that uniquely identifies each row. Extra attributes are allowed. | {roll_no}, {roll_no, name}, {email, dept_id} |
| Candidate key | A minimal super key: remove any attribute and it stops being unique. | {roll_no}, {email} |
| Primary key | The candidate key chosen by the designer to identify rows. Unique and never NULL. | {roll_no} |
| Alternate key | A candidate key that was not chosen as primary key. | {email} |
| Composite key | A key made of two or more attributes. | Enrollment: {roll_no, course_id} |
| Foreign key | An attribute in one table that refers to the primary key of another table. | Student.dept_id → Department.dept_id |
Rows 102 and 103 are both "Rahul Das", but in different departments, so the current data looks unique. A key must hold for all possible data, though: two Rahul Das students could join CSE next year. So {name, dept_id} is not a key. Decide keys from the rules of the college, never from today's rows.
7.3Foreign key and referential integrity
| dept_id (PK) | dept_name |
|---|---|
| CSE | Computer Science |
| ECE | Electronics |
| roll_no (PK) | dept_id (FK) |
|---|---|
| 101 | CSE ✓ |
| 104 | MEC ✗ rejected |
Referential integrity: every foreign key value must match an existing primary key value in the parent table, or be NULL. MySQL rejects the student with MEC because no such department exists.
CREATE TABLE Student (
roll_no INT PRIMARY KEY, -- primary key
email VARCHAR(80) UNIQUE NOT NULL, -- alternate key
name VARCHAR(50) NOT NULL,
dept_id VARCHAR(5),
FOREIGN KEY (dept_id) REFERENCES Department(dept_id) -- foreign key
);
CREATE TABLE Enrollment (
roll_no INT,
course_id VARCHAR(8),
grade CHAR(2),
PRIMARY KEY (roll_no, course_id) -- composite key
);- Saying "a table has many primary keys". It has many candidate keys but one primary key (which may be composite).
- Calling {roll_no, name} a candidate key. It is a super key; it is not minimal.
- Thinking a foreign key must be unique. Many students can have
dept_id = 'CSE'.
- Super key: uniquely identifies. Candidate key: minimal super key.
- Primary key: chosen candidate key; unique, NOT NULL (entity integrity).
- Alternate key = candidate keys − primary key.
- Foreign key refers to the PK of another table; enforces referential integrity; may repeat and may be NULL.
- PK ⊆ CK ⊆ SK. Draw Figure 7.1 in a 5-mark answer.
- Differentiate between super key and candidate key. [2 marks]
- Explain the different types of keys with examples. [5 marks]
- Course(course_id, title, credits, dept_id): course_id and title are each unique. List two super keys, all candidate keys, a sensible primary key and the alternate key. [practice]
- What is referential integrity? Show with Student and Department. [5 marks]
Relationship Sets and Constraints
- Define relationship and relationship set.
- Give the degree of a relationship.
- Identify cardinality (1:1, 1:N, N:1, M:N) and participation (total, partial).
What is a candidate key? Can a foreign key value repeat?
8.1Relationship and relationship set
An association between two or more entities. Example: Ananya enrolls in DBMS.
A set of similar relationships of the same type. Example: enrolls = all (student, course) pairs.
A relationship can have its own descriptive attributes. grade belongs to neither Student nor Course alone; it belongs to the fact that a student enrolled in a course, so it is an attribute of enrolls.
When an entity set takes part twice in the same relationship, we write role names on the lines. In Student — mentors — Student, one side is the mentor and the other is the mentee.
8.2Degree of a relationship
| Degree | Entity sets involved | College example |
|---|---|---|
| Unary (recursive) | 1 (same set twice) | Student mentors Student |
| Binary | 2 | Student enrolls Course — the most common |
| Ternary | 3 | Faculty teaches Course in Classroom |
| n-ary | n | Rare in practice |
8.3Constraint 1: mapping cardinality
Mapping cardinality (cardinality ratio) is the number of entities of one set that can be related to one entity of the other set.
| Cardinality | Rule | College example |
|---|---|---|
| 1 : 1 | An entity in A relates to at most one in B, and vice versa. | A faculty member heads at most one department; a department has one HOD. |
| 1 : N | One A relates to many B; each B relates to at most one A. | One department has many students. |
| N : 1 | Many A relate to one B. | Many students belong to one department (same as above, read the other way). |
| M : N | Many A relate to many B. | Students enroll in many courses; a course has many students. |
Ask both directions. "One student belongs to how many departments?" One. "One department has how many students?" Many. So Department : Student is 1 : N. If both answers are "many", it is M : N.
8.4Constraint 2: participation
Every entity in the set must take part in at least one relationship. Drawn with a double line. Also called existence dependency.
Every Course is offered by some Department.
Some entities may not take part. Drawn with a single line.
Not every Student is a class representative.
Some books also write (min, max) pairs on the lines: (1, N) means at least one, at most many; a minimum of 1 means total participation, 0 means partial.
- Mixing up cardinality and participation. Cardinality = "how many at most?"; participation = "must every entity take part?"
- Putting
gradeon Student. It belongs onenrolls. - Asking only one direction when deciding cardinality.
- Relationship set = set of similar relationships; may have descriptive attributes.
- Degree: unary, binary, ternary, n-ary.
- Cardinality: 1:1, 1:N, N:1, M:N — always check both directions.
- Participation: total (double line, every entity) vs partial (single line).
- Cardinality + participation together are the "constraints on relationships" in the syllabus.
- Define degree of a relationship with examples. [2 marks]
- Explain mapping cardinalities with diagrams. [5 marks]
- Differentiate between total and partial participation. [5 marks]
- Give the cardinality: (a) Student — has — Library card; (b) Faculty — teaches — Course; (c) Course — belongs to — Department; (d) Hostel room — allotted to — Student (2 per room). [practice]
ER Diagrams and Weak Entity Sets
- Draw a complete ER diagram from a problem statement.
- Explain strong vs weak entity sets.
- Identify the owner, identifying relationship and discriminator.
What does a double line mean? What is the cardinality of Student–enrolls–Course?
9.1Drawing an ER diagram: six steps
Problem statement: The college has departments. Each student belongs to exactly one department. Each department offers courses, and every course is offered by one department. Students enroll in many courses and get a grade in each. A course runs in several sections (A, B, C…), and section letters repeat across courses.
- Find entity sets — nouns that have their own data: Department, Student, Course, Section.
- Find attributes and underline the key of each entity set.
- Find relationships — verbs: belongs_to, offers, enrolls, has_section.
- Mark cardinality on every line using the two-question test.
- Mark participation — "exactly one", "every" → double line.
- Check for weak entities — anything without its own key (Section).
| Relationship | Cardinality | Participation | Why |
|---|---|---|---|
| belongs_to | Department 1 : N Student | Student total | "Each student belongs to exactly one department" |
| offers | Department 1 : N Course | Course total | "Every course is offered by one department" |
| enrolls | Student M : N Course | Both partial | A new student may not have enrolled yet |
| has (identifying) | Course 1 : N Section | Section total | A section cannot exist without its course |
9.2Strong and weak entity sets
Section "A" exists in DBMS and also in Data Structures. The letter alone cannot identify a section; we need to know which course it belongs to.
A weak entity set does not have enough attributes to form a primary key of its own. It depends on another entity set, called the owner (identifying) entity set, through an identifying relationship.
| Term | Meaning | In Figure 9.1 |
|---|---|---|
| Owner / identifying entity set | The strong entity set the weak one depends on | Course |
| Identifying relationship | Connects weak to owner; drawn as a double diamond | has |
| Discriminator (partial key) | Attribute that tells weak entities of the same owner apart; dashed underline | sec_id |
| Primary key of weak entity | Owner's primary key + discriminator | (course_id, sec_id) |
| Participation | Weak entity always has total participation | Double line Section–has |
| Point | Strong entity set | Weak entity set |
|---|---|---|
| Primary key | Has its own | Owner's PK + discriminator |
| Symbol | Single rectangle | Double rectangle |
| Relationship | Single diamond | Double diamond (identifying) |
| Existence | Independent | Depends on the owner |
| Participation | Total or partial | Always total in identifying relationship |
| Example | Course, Student | Section, Dependent of Employee |
In MySQL the existence dependency is enforced with a composite primary key and cascade delete. When a course is dropped, its sections disappear too:
CREATE TABLE Section (
course_id VARCHAR(8),
sec_id CHAR(1),
room VARCHAR(10),
PRIMARY KEY (course_id, sec_id),
FOREIGN KEY (course_id) REFERENCES Course(course_id)
ON DELETE CASCADE
);- Drawing the discriminator with a solid underline. It is dashed.
- Forgetting the double line between the weak entity and the identifying relationship.
- Making an entity weak just because it has a foreign key. Student has dept_id but has its own key (roll_no), so it is strong.
- Six steps: entities → attributes and keys → relationships → cardinality → participation → weak entities.
- Weak entity: no PK of its own; double rectangle; double diamond; total participation.
- Discriminator = partial key, dashed underline.
- PK of weak entity = owner PK + discriminator.
- For a "draw the ER diagram for…" question: state your assumptions in two lines before drawing.
- What is a weak entity set? Give an example. [2 marks]
- Differentiate between strong and weak entity sets with ER notation. [5 marks]
- Draw an ER diagram for a library: members borrow books (a member borrows many books; a book copy is borrowed by one member at a time); store issue_date and return_date; each book has several copies identified by copy_no within the book. [10 marks]
Extended ER Features and Unit II Test
- Explain specialization and generalization with the ISA symbol.
- State attribute inheritance and the disjoint/overlapping and total/partial constraints.
- Explain aggregation with a diagram.
What is a discriminator? How is an identifying relationship drawn?
The basic ER model cannot easily show that a Student and a Faculty member are both kinds of Person, or that a relationship itself takes part in another relationship. The Extended ER (EER) model adds three features for this.
10.1Specialization and generalization
Dividing a higher-level entity set into lower-level subclasses based on distinguishing features. Start with Person; split into Student and Faculty.
Combining entity sets that share attributes into a higher-level superclass. Start with Student and Faculty; notice both have id, name and phone; create Person.
Both produce the same diagram. The difference is the direction in which the designer thinks.
Attribute inheritance
A subclass inherits all attributes and relationships of its superclass. A Faculty entity has person_id, name, phone (inherited) plus salary and designation (its own).
Constraints on specialization
| Constraint | Options | Example |
|---|---|---|
| Disjointness | Disjoint: an entity belongs to at most one subclass. Overlapping: it can belong to several. | Disjoint: UG / PG student. Overlapping: a PhD scholar can be both Student and Faculty (teaching assistant). |
| Completeness | Total: every superclass entity must be in some subclass (double line). Partial: some may be in none. | Total: every Student is UG or PG. Partial: an office staff Person is neither Student nor Faculty. |
10.2Aggregation
Students work on projects (works_on). A faculty member guides each student–project pair, not the student alone or the project alone. ER does not allow a line from a relationship to another relationship, so we treat Student works_on Project as a single higher-level entity.
Aggregation is an abstraction in which a relationship set, together with its entity sets, is treated as one higher-level entity set that can take part in other relationships.
- Swapping the directions: Specialization Splits (top-down); Generalization Gathers (bottom-up).
- Drawing a line from one diamond to another diamond. Use aggregation instead.
- Repeating inherited attributes on subclasses. Draw them only on the superclass.
- EER adds specialization, generalization (with inheritance) and aggregation.
- ISA triangle connects superclass (above) and subclasses (below).
- Constraints: disjoint vs overlapping; total vs partial.
- Aggregation = a relationship treated as an entity, drawn as a dashed box.
- 10-mark question "Explain EER features": one diagram each for specialization and aggregation.
10.3Unit II test
10.4Unit II question bank
- Define attribute. What is a derived attribute? [2 marks]
- What is a candidate key? How is it different from a primary key? [2 marks]
- What is a discriminator? [2 marks]
- Explain mapping cardinalities with examples. [5 marks]
- Differentiate between generalization and specialization. [5 marks]
- What is aggregation? Explain with an ER diagram. [5 marks]
- Draw an ER diagram for a hospital: patients, doctors, wards and tests; state your assumptions. [10 marks]
- Explain all symbols used in an ER diagram. [10 marks]
- Write 3–4 assumptions first ("a student belongs to one department").
- Underline every key; mark every line with cardinality.
- Use double lines where the statement says "every" or "must".
- Keep the diagram neat: entities in a row, relationships between them, attributes outside.
Unit II revision
Everything to revise for Unit II in one place: the exam quick points from every class, the diagrams to practise drawing, and one quiz that mixes all the day quizzes. Tap Open notes whenever a point needs more explanation.
Exam quick points, class by class
- Entity = one real-world object; entity set = collection of similar entities.
- Attribute = property; domain = allowed values.
- Types: simple/composite, single/multivalued, stored/derived, key.
- Symbols: double ellipse = multivalued; dashed ellipse = derived; underline = key.
- NULL = not applicable or unknown.
- Super key: uniquely identifies. Candidate key: minimal super key.
- Primary key: chosen candidate key; unique, NOT NULL (entity integrity).
- Alternate key = candidate keys − primary key.
- Foreign key refers to the PK of another table; enforces referential integrity; may repeat and may be NULL.
- PK ⊆ CK ⊆ SK. Draw Figure 7.1 in a 5-mark answer.
- Relationship set = set of similar relationships; may have descriptive attributes.
- Degree: unary, binary, ternary, n-ary.
- Cardinality: 1:1, 1:N, N:1, M:N — always check both directions.
- Participation: total (double line, every entity) vs partial (single line).
- Cardinality + participation together are the "constraints on relationships" in the syllabus.
- Six steps: entities → attributes and keys → relationships → cardinality → participation → weak entities.
- Weak entity: no PK of its own; double rectangle; double diamond; total participation.
- Discriminator = partial key, dashed underline.
- PK of weak entity = owner PK + discriminator.
- For a "draw the ER diagram for…" question: state your assumptions in two lines before drawing.
- EER adds specialization, generalization (with inheritance) and aggregation.
- ISA triangle connects superclass (above) and subclasses (below).
- Constraints: disjoint vs overlapping; total vs partial.
- Aggregation = a relationship treated as an entity, drawn as a dashed box.
- 10-mark question "Explain EER features": one diagram each for specialization and aggregation.
Diagrams to practise
Draw each one from memory in under three minutes, then open the class to compare.
- Figure 6.1 — The Student entity set with every type of attribute.
- Figure 7.1 — How the key types fit inside each other.
- Figure 8.1 — The four mapping cardinalities. Each dot is one entity; each line is one relationship.
- Figure 8.2 — Partial and total participation in the same relationship.
- Figure 9.1 — The College ER diagram. Double lines show total participation; Section is a weak entity set.
- Figure 10.1 — Person is the superclass; Student and Faculty are subclasses that inherit person_id, name and phone.
- Figure 10.2 — Aggregation: Faculty guides a (Student, Project) pair.
Mixed quiz
From diagram to tables to queries
In Unit II we drew the College database. In this unit the drawing becomes relations (tables), and we learn two formal languages for asking questions of them: relational algebra (step-by-step operations) and relational calculus (describe what you want). SQL, which you use in the lab, is built on both.
Unit map
| Day | Topics | Syllabus item |
|---|---|---|
| D11 | Relation, tuple, attribute, domain, degree, cardinality; integrity constraints; ER-to-relational mapping | Structure of relational databases |
| D12 | Select, project, rename, union, set difference, Cartesian product | Relational algebra |
| D13 | Intersection, theta join, equijoin, natural join, division, assignment | Relational algebra |
| D14 | Tuple and domain relational calculus; safety; comparison | Relational calculus |
| D15 | Generalized projection, aggregation, outer joins; Unit III test | Extended relational algebra |
The sample database
Every query in this unit runs on these four relations. Keep this tab open while you solve problems. Note that PHY has no students and that student 101 has taken both CSE courses; both facts matter later.
| dept_id | dept_name | hod |
|---|---|---|
| CSE | Computer Science | Dr. Sen |
| ECE | Electronics | Dr. Paul |
| MTH | Mathematics | Dr. Bose |
| PHY | Physics | Dr. Ghosh |
| course_id | title | credits | dept_id |
|---|---|---|---|
| CS201 | DBMS | 4 | CSE |
| CS202 | Data Structures | 4 | CSE |
| EC201 | Signals | 3 | ECE |
| MA201 | Discrete Maths | 3 | MTH |
| roll_no | name | dept_id | semester |
|---|---|---|---|
| 101 | Ananya | CSE | 3 |
| 102 | Rahul | CSE | 3 |
| 103 | Priya | ECE | 3 |
| 104 | Arjun | ECE | 5 |
| 105 | Meera | MTH | 5 |
| roll_no | course_id | grade |
|---|---|---|
| 101 | CS201 | A |
| 101 | CS202 | B |
| 101 | MA201 | A |
| 102 | CS201 | B |
| 103 | CS201 | C |
| 103 | EC201 | A |
| 104 | EC201 | B |
| 105 | MA201 | A |
Operator cheat sheet
| Symbol | Name | Form | Result | In SQL | Type |
|---|---|---|---|---|---|
| σ | Select | σcondition(R) | Rows that satisfy a condition | WHERE | Basic |
| π | Project | πa, b(R) | Chosen columns, duplicates removed | SELECT DISTINCT a, b | Basic |
| ρ | Rename | ρS(R) | Gives a relation or its attributes a new name | AS | Basic |
| ∪ | Union | R ∪ S | Tuples in R or S or both | UNION | Basic |
| − | Set difference | R − S | Tuples in R but not in S | EXCEPT (MySQL 8.0.31+) | Basic |
| × | Cartesian product | R × S | Every tuple of R paired with every tuple of S | CROSS JOIN | Basic |
| ∩ | Intersection | R ∩ S | Tuples in both R and S | INTERSECT (MySQL 8.0.31+) | Derived |
| ⋈θ | Theta join | R ⋈θ S | σθ(R × S) | JOIN … ON condition | Derived |
| ⋈ | Natural join | R ⋈ S | Join on all common attributes, keep one copy | NATURAL JOIN | Derived |
| ÷ | Division | R ÷ S | Values in R paired with all tuples of S | No direct keyword (double NOT EXISTS) | Derived |
| ← | Assignment | temp ← expression | Stores a result under a name | a view or subquery | Derived |
| π | Generalized projection | πa, b×2(R) | Projection with arithmetic | SELECT a, b*2 | Extended |
| G | Aggregation | aGcount(b)(R) | Groups and aggregate functions | GROUP BY + COUNT/SUM… | Extended |
| ⟕ ⟖ ⟗ | Outer joins | R ⟕ S | Join that keeps unmatched tuples, padded with NULL | LEFT / RIGHT JOIN | Extended |
The six basic operators (σ, π, ρ, ∪, −, ×) can express every relational-algebra query; all the others are shortcuts built from them. Exams often ask "list the fundamental operations" or "express ∩ using basic operators".
Structure of Relational Databases
- Use the terms relation, tuple, attribute, domain, degree and cardinality correctly.
- State the properties of a relation and the three integrity constraints.
- Convert an ER diagram into relation schemas.
What is the primary key of the weak entity Section? What is the cardinality of Student–enrolls–Course?
11.1Relational model terms
The relational model, proposed by E. F. Codd in 1970, stores all data as relations. Informally a relation is a table, but the formal words are what the examiner looks for.
| Formal term | Informal term | Meaning | In Student |
|---|---|---|---|
| Relation | Table | A set of tuples with the same attributes | Student |
| Tuple | Row, record | One entity or fact | (101, Ananya, CSE, 3) |
| Attribute | Column, field | A named property | semester |
| Domain | Data type + allowed values | Set of atomic values an attribute may take | 1–8 for semester |
| Degree (arity) | Number of columns | Number of attributes | 4 |
| Cardinality | Number of rows | Number of tuples at this moment | 5 |
| Relation schema | Table design | Name + attributes: Student(roll_no, name, dept_id, semester) | Changes rarely |
| Relation instance | Table contents | The set of tuples at a given time | The 5 rows above |
If D1, D2, …, Dn are domains, a relation r is a subset of D1 × D2 × … × Dn. That is why a relation is a set of tuples.
11.2Properties of a relation
- No duplicate tuples — a relation is a set.
- Order of tuples does not matter — sorting Student by name gives the same relation.
- Order of attributes does not matter — attributes are identified by name.
- Values are atomic — one value per cell; no lists (that is First Normal Form, Unit V).
- Each attribute has a distinct name within the relation.
11.3Integrity constraints
| Constraint | Rule | Violated by |
|---|---|---|
| Domain constraint | Every value must come from the attribute's domain | semester = 11 |
| Key / entity integrity | Primary key values are unique and never NULL | Two students with roll_no 101; roll_no NULL |
| Referential integrity | A foreign key value must match a PK in the referenced relation, or be NULL | Student with dept_id = 'MEC' |
11.4ER diagram to relations
Apply these rules to the College ER diagram from Day 9. In the schemas below, underlined attributes form the primary key.
| ER construct | Rule | College example |
|---|---|---|
| Strong entity set | A table with the same attributes; key becomes PK | Department(dept_id, dept_name, hod) |
| Composite attribute | Keep only the simple parts as columns | name → first_name, last_name |
| Multivalued attribute | A separate table: owner's PK + the value | StudentPhone(roll_no, phone) |
| Derived attribute | Usually not stored | age is calculated from dob |
| 1 : N relationship | Put the PK of the 1-side as a FK in the N-side table | Student(roll_no, name, semester, dept_id → Department) |
| M : N relationship | A new table: both PKs (together the PK) + relationship attributes | Enrollment(roll_no, course_id, grade) |
| 1 : 1 relationship | FK on either side; prefer the side with total participation | Department(…, hod_id → Faculty) |
| Weak entity set | Table with owner's PK + discriminator as PK; FK to owner | Section(course_id, sec_id, room) |
| Specialization | Superclass table + one table per subclass sharing the PK | Person(pid, name), Faculty(pid, salary) |
Department(dept_id, dept_name, hod)
Student (roll_no, name, semester, dept_id → Department)
Course (course_id, title, credits, dept_id → Department)
Enrollment(roll_no → Student, course_id → Course, grade)
Section (course_id → Course, sec_id, room)Five relations: four from entity sets and one (Enrollment) from the M:N relationship. belongs_to and offers produced no tables; they became foreign keys.
- Making a separate table for every relationship. Only M:N (and multivalued attributes) need their own table.
- Putting the FK on the 1-side of a 1:N relationship. It always goes on the N-side.
- Calling cardinality of a relation the same as cardinality ratio of a relationship. One counts tuples; the other is 1:1, 1:N, M:N.
- Relation = table; tuple = row; attribute = column; domain = allowed atomic values.
- Degree = number of attributes; cardinality = number of tuples.
- Properties: no duplicate tuples, no ordering of tuples or attributes, atomic values.
- Constraints: domain, entity (PK not NULL, unique), referential (FK matches PK).
- Mapping: 1:N → FK on N-side; M:N → new table; weak → owner PK + discriminator; multivalued → new table.
- Define degree and cardinality of a relation with an example. [2 marks]
- State the properties of a relation. [5 marks]
- Explain domain, entity and referential integrity constraints. [5 marks]
- Convert your library ER diagram (Day 9 homework) into relation schemas. Underline primary keys and mark foreign keys. [10 marks]
Relational Algebra: Fundamental Operations
- Explain what relational algebra is.
- Use σ, π, ρ, ∪, −, × and write their results.
- Combine operations into one expression and translate it to SQL.
What is the degree of Enrollment? Why can a relation not contain two identical tuples?
12.1What is relational algebra?
Relational algebra is a procedural query language: it takes one or two relations as input and produces a new relation as output, using a set of operations. Because the output is again a relation, operations can be nested (this is called closure).
Think of it like arithmetic: (3 + 4) × 2 applies operations to numbers; πname(σsemester=3(Student)) applies operations to relations.
12.2Select (σ)
Returns the tuples that satisfy a condition. Conditions use =, ≠, <, ≤, >, ≥ joined by ∧ (and), ∨ (or), ¬ (not).
SELECT * FROM Student WHERE semester = 3;| roll_no | name | dept_id | semester |
|---|---|---|---|
| 101 | Ananya | CSE | 3 |
| 102 | Rahul | CSE | 3 |
| 103 | Priya | ECE | 3 |
SELECT * FROM Student WHERE dept_id = 'ECE' AND semester = 5;| roll_no | name | dept_id | semester |
|---|---|---|---|
| 104 | Arjun | ECE | 5 |
12.3Project (π)
Returns only the listed attributes. Because the result is a relation (a set), duplicate tuples are removed.
SELECT DISTINCT dept_id FROM Student;| dept_id |
|---|
| CSE |
| ECE |
| MTH |
SELECT DISTINCT name FROM Student WHERE dept_id = 'CSE';| name |
|---|
| Ananya |
| Rahul |
Read inside-out: first σ selects the CSE rows, then π keeps only the name column.
12.4Rename (ρ)
Gives a name to a relation (and optionally its attributes). Needed when the same relation is used twice in one query.
SELECT * FROM Student AS S2;12.5Union (∪) and set difference (−)
R ∪ S and R − S are allowed only if R and S are union-compatible (Navathe also says type-compatible): (1) the same number of attributes, and (2) the domains of the i-th attributes match. You cannot union Student with Course directly; project first.
Let A ← πroll_no(σcourse_id='CS201'(Enrollment)) = {101, 102, 103} and B ← πroll_no(σcourse_id='MA201'(Enrollment)) = {101, 105}.
… UNION …| roll_no |
|---|
| 101 |
| 102 |
| 103 |
| 105 |
… EXCEPT …| roll_no |
|---|
| 102 |
| 103 |
Union is commutative (A ∪ B = B ∪ A); difference is not (B − A = {105}).
12.6Cartesian product (×)
Pairs every tuple of R with every tuple of S. If R has n1 tuples and degree d1, and S has n2 tuples and degree d2, then R × S has n1 × n2 tuples and d1 + d2 attributes.
Let P = πdept_id(σdept_id='CSE' ∨ dept_id='ECE'(Department)) = {CSE, ECE} and Q = πcourse_id(σcredits=3(Course)) = {EC201, MA201}.
SELECT * FROM P CROSS JOIN Q;| dept_id | course_id |
|---|---|
| CSE | EC201 |
| CSE | MA201 |
| ECE | EC201 |
| ECE | MA201 |
On its own × produces meaningless pairs (CSE with EC201). It becomes useful when followed by σ to keep only matching pairs; that is a join, the topic of Day 13.
12.7Practice: write the expression
1. Titles of all 4-credit courses.
Result: DBMS, Data Structures.
2. Roll numbers of students who got grade A in any course.
Result: 101, 103, 105.
3. Roll numbers of students who have not enrolled in any course.
Result: empty — every student in the sample has enrolled.
- Mixing σ and π. σ = rows (the s in select is for slices of rows); π = columns.
- Forgetting that π removes duplicates.
- Taking union of relations with different attributes.
- Relational algebra = procedural; input relations, output a relation (closure).
- Six fundamental operations: σ, π, ρ, ∪, −, ×.
- σ and π and ρ are unary; ∪, −, × are binary.
- ∪ and − need union-compatible relations.
- |R × S| = |R| × |S| tuples; degree adds.
- What is relational algebra? List its fundamental operations. [2 marks]
- Explain select and project with examples. How are they different? [5 marks]
- R has 6 tuples and 3 attributes; S has 4 tuples and 2 attributes. Find the degree and cardinality of R × S. [2 marks]
- Write relational algebra for: (a) names of semester-5 students; (b) course IDs with no enrollment. [5 marks]
Relational Algebra: Joins and Division
- Express intersection using difference.
- Use theta join, equijoin and natural join.
- Use division for "all" queries.
- Write multi-step queries with assignment.
Which operation removes duplicate tuples? How many tuples does a 3-row × 4-row product have?
13.1Intersection (∩)
R ∩ S returns tuples present in both relations (union-compatible). It is not fundamental, because:
SELECT … INTERSECT SELECT …;With A and B from Day 12: A ∩ B = {101}, the only student who took both DBMS and Discrete Maths.
13.2Joins
| Join | Notation | Definition |
|---|---|---|
| Theta join | R ⋈θ S | σθ(R × S), where θ is any condition (<, ≥, ≠, …) |
| Equijoin | R ⋈R.a = S.a S | Theta join where θ uses only =; both copies of the column remain |
| Natural join | R ⋈ S | Equijoin on all attributes with the same name, then one copy of each is kept |
SELECT * FROM Student NATURAL JOIN Department;| roll_no | name | dept_id | semester | dept_name | hod |
|---|---|---|---|---|---|
| 101 | Ananya | CSE | 3 | Computer Science | Dr. Sen |
| 102 | Rahul | CSE | 3 | Computer Science | Dr. Sen |
| 103 | Priya | ECE | 3 | Electronics | Dr. Paul |
| 104 | Arjun | ECE | 5 | Electronics | Dr. Paul |
| 105 | Meera | MTH | 5 | Mathematics | Dr. Bose |
SELECT DISTINCT name FROM Enrollment NATURAL JOIN Student WHERE grade = 'A';| name |
|---|
| Ananya |
| Priya |
| Meera |
Ananya has two A grades but appears once, because π removes duplicates.
Three relations: Student gives Priya's roll number, Enrollment gives her courses, Course gives the titles.
Result: DBMS, Signals. The inner πroll_no matters: Student and Course both have dept_id, so without it the natural join would also demand student.dept_id = course.dept_id and lose DBMS (a CSE course taken by an ECE student).
13.3Division (÷)
Use division when the question contains "all" or "every": "students who took all CSE courses".
If R has attributes (X, Y) and S has attributes (Y), then R ÷ S returns the values of X that are paired in R with every Y-value in S.
| roll_no | course_id |
|---|---|
| 101 | CS201 |
| 101 | CS202 |
| 101 | MA201 |
| 102 | CS201 |
| 103 | CS201 |
| 103 | EC201 |
| 104 | EC201 |
| 105 | MA201 |
| course_id |
|---|
| CS201 |
| CS202 |
| roll_no |
|---|
| 101 |
In words: take every candidate X; pair each with all of S; whatever pairs are missing from R mark that X as "failed"; remove the failed ones.
13.4Assignment (←)
Long queries are easier to write in steps. The assignment operator stores an intermediate result under a temporary name.
ALL_CSE ← πroll_no, course_id(Enrollment) ÷ CSE_C
result ← πname(ALL_CSE ⋈ Student)
Result: Ananya.
13.5Practice
1. Names of students enrolled in DBMS.
Careful: Course and Student both have dept_id, so a natural join of all three would also force course.dept_id = student.dept_id and drop Priya (ECE). Project Course first: πcourse_id(σtitle='DBMS'(Course)) ⋈ Enrollment ⋈ Student. Result: Ananya, Rahul, Priya.
2. Departments that have at least one semester-5 student (department names).
Result: Electronics, Mathematics.
3. Roll numbers of students who took every course offered by any department (all 4 courses).
Result: empty. 101 has three of the four (no EC201).
- Natural join on relations with an unintended common attribute (like dept_id in Course and Student) — project it away first.
- Using ∩ or join where the question says "all"; that needs ÷.
- Writing division with the wrong attribute sets: S's attributes must be a subset of R's.
- R ∩ S = R − (R − S).
- Theta join = σθ(R × S); equijoin uses only =; natural join matches all same-named attributes and keeps one copy.
- Degree of R ⋈ S = deg R + deg S − common attributes.
- "All / every" → division.
- R ÷ S = πX(R) − πX((πX(R) × S) − R).
- Differentiate between theta join, equijoin and natural join. [5 marks]
- Explain the division operation with an example. [5 marks]
- Express R ∩ S using fundamental operations. [2 marks]
- Using the sample database write RA for: (a) names of students in the Electronics department; (b) roll numbers of students who took all 3-credit courses. [5 marks]
Relational Calculus
- Explain procedural vs non-procedural languages.
- Read and write simple TRC and DRC expressions with ∃ and ∀.
- Explain safe expressions and relational completeness.
Which operator answers "all" questions? Write R ∩ S using −.
14.1Algebra vs calculus
Says how: "first select ECE rows, then project names".
πname(σdept_id='ECE'(Student))
Says what: "the names of students whose department is ECE". The DBMS decides how.
{ t.name | t ∈ Student ∧ t.dept_id = 'ECE' }
Algebra is giving a driver turn-by-turn directions. Calculus is telling the driver the address. SQL is closer to calculus: you describe the result in SELECT … WHERE and MySQL plans the steps.
14.2Symbols you need
| Symbol | Read as | Meaning |
|---|---|---|
| ∈ | belongs to | t ∈ Student: t is a tuple of Student |
| ∧ | and | both conditions true |
| ∨ | or | at least one true |
| ¬ | not | negation |
| ⇒ | implies | if … then … |
| ∃ | there exists | at least one tuple satisfies |
| ∀ | for all | every tuple satisfies |
14.3Tuple relational calculus (TRC)
{ t | P(t) }
"The set of all tuples t such that predicate P is true for t." Variables range over tuples. Notation: t[name] or t.name.
- All semester-3 students.
{ t | t ∈ Student ∧ t[semester] = 3 }
Result: tuples 101, 102, 103. - Only their names (need a new tuple with one attribute):
{ t | ∃ s ∈ Student ( s[semester] = 3 ∧ t[name] = s[name] ) }
Result: Ananya, Rahul, Priya. - Names of students enrolled in CS201 (∃ plays the role of a join):
{ t | ∃ s ∈ Student ( t[name] = s[name] ∧ ∃ e ∈ Enrollment ( e[roll_no] = s[roll_no] ∧ e[course_id] = 'CS201' ) ) }
Result: Ananya, Rahul, Priya. - Students who took all CSE courses (∀ plays the role of division):
{ t | ∃ s ∈ Student ( t[roll_no] = s[roll_no] ∧ ∀ c ∈ Course ( c[dept_id] = 'CSE' ⇒ ∃ e ∈ Enrollment ( e[roll_no] = s[roll_no] ∧ e[course_id] = c[course_id] ) ) ) }
Result: 101.
A variable bound by ∃ or ∀ is a bound variable; t, which appears to the left of the bar, is the free variable.
14.4Domain relational calculus (DRC)
{ <x1, x2, …, xn> | P(x1, …, xn) }
Variables range over attribute values (domains), not whole tuples. A relation is written with one variable per attribute in order: <r, n, d, m> ∈ Student means roll_no r, name n, dept_id d, semester m.
- Roll number and name of semester-3 students.
{ <r, n> | ∃ d, m ( <r, n, d, m> ∈ Student ∧ m = 3 ) }
- Names of students enrolled in CS201.
{ <n> | ∃ r, d, m ( <r, n, d, m> ∈ Student ∧ ∃ g ( <r, 'CS201', g> ∈ Enrollment ) ) }
The shared variable r does the join.
14.5Safety of expressions
The expression { t | ¬ ( t ∈ Student ) } asks for every tuple in the universe that is not a student — an infinite answer. Such an expression is unsafe.
A calculus expression is safe if every value in its result comes from the domain of the expression: values that appear in the relations it mentions or as constants in it. Only safe expressions are allowed.
14.6Expressive power
Codd showed that relational algebra, safe TRC and safe DRC are equally powerful: any query in one can be written in the others. A language that can express everything relational algebra can is called relationally complete. SQL is relationally complete (and adds more, such as aggregation).
| Point | Relational algebra | TRC | DRC |
|---|---|---|---|
| Type | Procedural | Non-procedural | Non-procedural |
| Variables range over | — (operators on relations) | Tuples | Domain values |
| Form | π…(σ…(R)) | { t | P(t) } | { <x, y> | P(x, y) } |
| Closest real language | Query plans inside the DBMS | SQL | QBE (Query By Example) |
- Forgetting ∃ for a variable used in the condition but not in the result.
- Writing ∀ … ∧ instead of ∀ … ⇒ in "all" queries.
- Mixing TRC tuple variables with DRC domain variables in one expression.
- Algebra = procedural (how); calculus = non-procedural (what).
- TRC: { t | P(t) }, variables are tuples. DRC: { <x₁…xₙ> | P }, variables are values.
- ∃ ≈ join; ∀ with ⇒ ≈ division.
- Unsafe expression = infinite result, e.g. { t | ¬(t ∈ R) }.
- Algebra, safe TRC and safe DRC have equal power (relational completeness).
- Differentiate between relational algebra and relational calculus. [5 marks]
- What is an unsafe expression? Give an example. [2 marks]
- Explain TRC and DRC with one example each. [5 marks]
- Write in TRC: names of students in semester 5 of the ECE department. [practice]
Extended Relational Algebra and Unit III Test
- Use generalized projection.
- Write aggregation and grouping with G.
- Explain left, right and full outer joins and the role of NULL.
Which is procedural: algebra or calculus? What makes an expression unsafe?
The basic operations cannot answer "how many students are in each department?" or "list every department, even those with no students". The extended operations add these abilities. They are the direct ancestors of SQL's GROUP BY and LEFT JOIN.
15.1Generalized projection
Allows arithmetic expressions in the projection list.
SELECT course_id, credits * 15 AS contact_hours FROM Course;| course_id | contact_hours |
|---|---|
| CS201 | 60 |
| CS202 | 60 |
| EC201 | 45 |
| MA201 | 45 |
15.2Aggregate functions and grouping (G)
G1, …, GnGF1(A1), …, Fm(Am)(R)
Attributes on the left of G are the grouping attributes; on the right are aggregate functions: count, sum, avg, min, max. Without grouping attributes, the whole relation is one group.
Symbols differ by textbook: Silberschatz–Korth 7th edition writes γ, earlier editions a calligraphic G, and Elmasri–Navathe ℑ. They mean the same operation.
SELECT COUNT(roll_no) FROM Student;| count |
|---|
| 5 |
SELECT dept_id, COUNT(roll_no) AS total FROM Student GROUP BY dept_id;| dept_id | total |
|---|---|
| CSE | 2 |
| ECE | 2 |
| MTH | 1 |
PHY does not appear: grouping only forms groups for values present in Student.
Try it: average credits of courses in each department.
SELECT dept_id, AVG(credits) FROM Course GROUP BY dept_id;| dept_id | avg |
|---|---|
| CSE | 4 |
| ECE | 3 |
| MTH | 3 |
15.3Outer joins
| Operation | Symbol | Keeps | MySQL |
|---|---|---|---|
| Left outer join | ⟕ | All tuples of the left relation; unmatched ones padded with NULL | LEFT JOIN |
| Right outer join | ⟖ | All tuples of the right relation | RIGHT JOIN |
| Full outer join | ⟗ | All tuples of both relations | No FULL JOIN; use LEFT JOIN UNION RIGHT JOIN |
SELECT dept_name, name FROM Department LEFT JOIN Student USING (dept_id);| dept_name | name |
|---|---|
| Computer Science | Ananya |
| Computer Science | Rahul |
| Electronics | Priya |
| Electronics | Arjun |
| Mathematics | Meera |
| Physics | NULL |
Student ⟖ Department gives the same tuples (the preserved side is now on the right). In this sample every student has a department, so the full outer join equals the left outer join; it would differ if some student had dept_id = NULL.
- Any comparison with NULL is unknown, so σ does not select that tuple.
- Aggregates ignore NULL values (except count(*) in SQL).
- Outer joins are the main operation that creates NULLs.
- Writing the grouping attribute on the right of G.
- Expecting departments with zero students in a GROUP BY result; you need an outer join first.
- Thinking MySQL supports FULL OUTER JOIN.
- Extended RA: generalized projection, aggregation (G), outer joins.
- Grouping attributes left of G; aggregate functions right of G.
- ⟕ keeps left, ⟖ keeps right, ⟗ keeps both; unmatched padded with NULL.
- Inner joins lose unmatched tuples; outer joins keep them.
15.4Unit III test
15.5Unit III question bank
- Define relation, tuple, degree and cardinality. [2 marks]
- What is union compatibility? [2 marks]
- Express the natural join using fundamental operators. [2 marks]
- Explain the fundamental operations of relational algebra with examples. [10 marks]
- Explain different types of joins with examples. [5 marks]
- Explain the division operation. Express it using basic operators. [5 marks]
- Differentiate between TRC and DRC. [5 marks]
- Explain extended relational algebra operations. [5 marks]
- For Employee(eid, name, salary, dno) and Dept(dno, dname, location), write RA for: (a) names of employees in 'Kolkata'; (b) number of employees in each department; (c) departments with no employee. [10 marks]
Unit III revision
Everything to revise for Unit III in one place: the exam quick points from every class, the diagrams to practise drawing, and one quiz that mixes all the day quizzes. Tap Open notes whenever a point needs more explanation.
Exam quick points, class by class
- Relation = table; tuple = row; attribute = column; domain = allowed atomic values.
- Degree = number of attributes; cardinality = number of tuples.
- Properties: no duplicate tuples, no ordering of tuples or attributes, atomic values.
- Constraints: domain, entity (PK not NULL, unique), referential (FK matches PK).
- Mapping: 1:N → FK on N-side; M:N → new table; weak → owner PK + discriminator; multivalued → new table.
- Relational algebra = procedural; input relations, output a relation (closure).
- Six fundamental operations: σ, π, ρ, ∪, −, ×.
- σ and π and ρ are unary; ∪, −, × are binary.
- ∪ and − need union-compatible relations.
- |R × S| = |R| × |S| tuples; degree adds.
- R ∩ S = R − (R − S).
- Theta join = σθ(R × S); equijoin uses only =; natural join matches all same-named attributes and keeps one copy.
- Degree of R ⋈ S = deg R + deg S − common attributes.
- "All / every" → division.
- R ÷ S = πX(R) − πX((πX(R) × S) − R).
- Algebra = procedural (how); calculus = non-procedural (what).
- TRC: { t | P(t) }, variables are tuples. DRC: { <x₁…xₙ> | P }, variables are values.
- ∃ ≈ join; ∀ with ⇒ ≈ division.
- Unsafe expression = infinite result, e.g. { t | ¬(t ∈ R) }.
- Algebra, safe TRC and safe DRC have equal power (relational completeness).
- Extended RA: generalized projection, aggregation (G), outer joins.
- Grouping attributes left of G; aggregate functions right of G.
- ⟕ keeps left, ⟖ keeps right, ⟗ keeps both; unmatched padded with NULL.
- Inner joins lose unmatched tuples; outer joins keep them.
Diagrams to practise
Draw each one from memory in under three minutes, then open the class to compare.
- Figure 11.1 — The parts of a relation. The highlighted row is one tuple.
- Figure 12.1 — Select cuts across rows; project cuts down columns.
- Figure 13.1 — A join is a product followed by a selection.
- Figure 15.1 — Inner join keeps only matched tuples; an outer join also keeps the unmatched ones.
Mixed quiz
SQL and integrity constraints
Units I–III gave us the ideas: schemas, keys, relational algebra. This unit is about SQL, the language every relational DBMS speaks. Every example here runs on the full College database used in the SQL Lab (Department, Faculty, Student, Course, Enrollment), and most have a Try in SQL Lab button so you can run them yourself.
Unit map
| Day | Topics | SQL Lab |
|---|---|---|
| D16 | Data types; CREATE and ALTER TABLE; integrity constraints and referential actions; INSERT, UPDATE, DELETE in depth | L1–L3 |
| D17 | Set operations; aggregate functions; GROUP BY and HAVING; NULL values and three-valued logic | L6–L8 |
| D18 | Nested and correlated subqueries; EXISTS; derived tables; views | L11–L13 |
| D19 | Assertions; stored procedures; triggers | L15 |
| D20 | Database security: privileges, GRANT/REVOKE, roles, views, SQL injection; Unit IV test | L16 |
From relational algebra to SQL
SQL is declarative: you describe the result and the DBMS plans the steps. Each relational-algebra operator from Unit III has a direct SQL form.
| Algebra | SQL | Example on the College database |
|---|---|---|
| σ | WHERE | SELECT * FROM Student WHERE semester = 3; |
| π | SELECT DISTINCT columns | SELECT DISTINCT city FROM Student; |
| ⋈ | JOIN … ON | SELECT s.name, d.dept_name FROM Student s JOIN Department d ON s.dept_id = d.dept_id; |
| ∪ ∩ − | UNION, INTERSECT, EXCEPT | Day 17 |
| G | GROUP BY + aggregates | Day 17 |
| ÷ | double NOT EXISTS | Day 18 |
| ⟕ | LEFT JOIN | SELECT d.dept_name, s.name FROM Department d LEFT JOIN Student s ON s.dept_id = d.dept_id; |
Write: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT. The DBMS runs them as FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT. The SQL Lab guide explains why this matters.
SQL Data Definition and Integrity Constraints
- Choose the right MySQL data type for a column.
- Write CREATE TABLE with all six constraints, at column and table level.
- Explain referential actions (CASCADE, SET NULL, RESTRICT).
- Use ALTER TABLE and the full forms of INSERT, UPDATE and DELETE.
Name the three integrity constraints from Day 11. Which SQL group does CREATE belong to?
16.1Common MySQL data types
| Type | Stores | Example column |
|---|---|---|
INT, SMALLINT, TINYINT | Whole numbers (TINYINT: −128 to 127) | roll_no, semester |
DECIMAL(p, s) | Exact numbers: p digits in total, s after the point | fee DECIMAL(8,2) → 123456.78 |
FLOAT, DOUBLE | Approximate numbers (never for money) | sensor readings |
CHAR(n) | Fixed-length text, padded to n characters | grade CHAR(2) |
VARCHAR(n) | Variable-length text up to n characters | name VARCHAR(50) |
DATE, TIME, DATETIME | 'YYYY-MM-DD', 'HH:MM:SS', both together | dob DATE |
BOOLEAN | TRUE/FALSE (stored as TINYINT(1) in MySQL) | is_active |
CHAR vs VARCHAR: CHAR(10) always uses 10 characters of space; VARCHAR(10) uses only what the value needs. Use CHAR for fixed codes (grade, PIN), VARCHAR for names and emails.
16.2CREATE TABLE with every constraint
Constraints are rules the DBMS enforces on every insert and update, so bad data never gets in. A constraint written next to a column is a column-level constraint; one written after all columns is a table-level constraint (needed when it involves two or more columns). CONSTRAINT name gives it a name, which makes error messages and later changes easier.
-- Student clubs: each club may have a faculty in charge
CREATE TABLE Club (
club_id INT PRIMARY KEY, -- entity integrity
name VARCHAR(40) NOT NULL UNIQUE, -- required, no duplicates
fee DECIMAL(6,2) DEFAULT 0 CHECK (fee >= 0), -- default + domain rule
fac_id INT,
CONSTRAINT fk_club_fac FOREIGN KEY (fac_id)
REFERENCES Faculty(fac_id) ON DELETE SET NULL -- referential integrity
);
CREATE TABLE Membership (
roll_no INT,
club_id INT,
joined DATE NOT NULL,
PRIMARY KEY (roll_no, club_id), -- table-level, composite
FOREIGN KEY (roll_no) REFERENCES Student(roll_no) ON DELETE CASCADE,
FOREIGN KEY (club_id) REFERENCES Club(club_id) ON DELETE CASCADE
);
INSERT INTO Club VALUES (1, 'Coding Club', 200, 5), (2, 'Robotics', 300, 6);
INSERT INTO Club (club_id, name) VALUES (3, 'Quiz Club'); -- fee uses DEFAULT
INSERT INTO Membership VALUES (101, 1, '2026-08-01'), (106, 1, '2026-08-03'),
(103, 2, '2026-08-02'), (104, 2, '2026-08-05');
SELECT * FROM Club;| club_id | name | fee | fac_id |
|---|---|---|---|
| 1 | Coding Club | 200 | 5 |
| 2 | Robotics | 300 | 6 |
| 3 | Quiz Club | 0 | NULL |
| Constraint | Rule it enforces | Integrity type |
|---|---|---|
NOT NULL | Column must have a value | Domain |
CHECK (condition) | Value must satisfy the condition (MySQL 8.0.16+ enforces it) | Domain |
DEFAULT value | Value used when none is given (not strictly a constraint, but declared the same way) | — |
UNIQUE | No two rows share the value (NULLs allowed) | Key |
PRIMARY KEY | UNIQUE + NOT NULL; one per table | Entity |
FOREIGN KEY … REFERENCES | Value must exist in the parent table (or be NULL) | Referential |
16.3Referential actions
What should happen to child rows when a parent row is deleted or its key changes? You choose with ON DELETE and ON UPDATE.
| Action | Effect on child rows | Use it when |
|---|---|---|
| RESTRICT / NO ACTION (default) | The parent delete is rejected while children exist | Children must never be lost silently |
| CASCADE | Children are deleted (or their keys updated) too | Children cannot exist alone (Membership, Section) |
| SET NULL | Children keep their row; the foreign key becomes NULL | The link is optional (club without a faculty in charge) |
| SET DEFAULT | Foreign key becomes its default value | Standard SQL; not supported by MySQL's InnoDB |
The College tables use the default, so deleting a department that still has students is refused:
DELETE FROM Department WHERE dept_id = 'PHY';Membership uses CASCADE, so deleting a club removes its memberships automatically:
CREATE TABLE Club (club_id INT PRIMARY KEY, name VARCHAR(40) NOT NULL);
CREATE TABLE Membership (
roll_no INT REFERENCES Student(roll_no),
club_id INT REFERENCES Club(club_id) ON DELETE CASCADE,
PRIMARY KEY (roll_no, club_id));
INSERT INTO Club VALUES (1, 'Coding Club'), (2, 'Robotics');
INSERT INTO Membership VALUES (101, 1), (106, 1), (103, 2), (104, 2);
DELETE FROM Club WHERE club_id = 2; -- Robotics closes
SELECT * FROM Membership; -- its two members are gone too| roll_no | club_id |
|---|---|
| 101 | 1 |
| 106 | 1 |
16.4Changing a table: ALTER TABLE
ALTER TABLE Student ADD phone VARCHAR(15); -- add a column
ALTER TABLE Student MODIFY phone VARCHAR(20); -- change its type
ALTER TABLE Student RENAME COLUMN phone TO mobile; -- rename it
ALTER TABLE Student ADD CONSTRAINT uq_mobile UNIQUE (mobile);
ALTER TABLE Student DROP COLUMN mobile; -- remove itIn the SQL Lab, ADD, RENAME COLUMN and DROP COLUMN work; MODIFY and adding a constraint to an existing table work only in MySQL.
16.5INSERT, UPDATE and DELETE in depth
-- 1. Name the columns: safer, and the rest get NULL or DEFAULT
INSERT INTO Student (roll_no, name, dept_id, semester)
VALUES (113, 'Nikhil', 'ECE', 1);
-- 2. Insert the result of a query (Data Structures re-exam list)
CREATE TABLE ReExam (roll_no INT, course_id VARCHAR(8));
INSERT INTO ReExam
SELECT roll_no, course_id FROM Enrollment WHERE marks < 70;
-- 3. Update with an expression: 5 grace marks in DBMS, capped at 100
UPDATE Enrollment
SET marks = CASE WHEN marks + 5 > 100 THEN 100 ELSE marks + 5 END
WHERE course_id = 'CS201';
-- 4. Delete using a subquery
DELETE FROM ReExam
WHERE roll_no IN (SELECT roll_no FROM Student WHERE dept_id = 'ECE');
SELECT * FROM ReExam;| roll_no | course_id |
|---|---|
| 102 | CS202 |
| 109 | MA201 |
- UPDATE or DELETE without WHERE changes every row.
- Inserting values in the wrong column order. Always list the columns.
- Expecting
DEFAULTto be used when you insert NULL explicitly. It is used only when the column is left out. - Using FLOAT for money. Use DECIMAL.
- SQL DDL defines schemas, types, constraints, indexes; DML queries and changes data.
- Constraints: NOT NULL, CHECK (domain); UNIQUE, PRIMARY KEY (key/entity); FOREIGN KEY (referential).
- Column-level vs table-level constraints; composite keys need table-level.
- Referential actions: RESTRICT/NO ACTION (default), CASCADE, SET NULL, SET DEFAULT.
- CHAR fixed length, VARCHAR variable; DECIMAL exact, FLOAT approximate.
- Differentiate between CHAR and VARCHAR. [2 marks]
- Explain integrity constraints in SQL with examples. [5 marks]
- What are referential actions? Explain CASCADE and SET NULL with an example. [5 marks]
- Write SQL to create Library(book_id, title, author, price, copies) with: book_id primary key, title required, price positive, copies default 1. [5 marks]
Set Operations, Aggregates and NULL Values
- Use UNION, UNION ALL, INTERSECT and EXCEPT.
- Write aggregate queries with GROUP BY and HAVING.
- Explain how NULL behaves in arithmetic, comparisons and aggregates (three-valued logic).
Which relational-algebra operators need union-compatible relations? What does the G operator do?
17.1Set operations
SQL set operations combine the results of two SELECTs, exactly like ∪, ∩ and − in relational algebra. Both SELECTs must return the same number of columns with compatible types.
SELECT roll_no FROM Enrollment WHERE course_id = 'CS201'
UNION
SELECT roll_no FROM Enrollment WHERE course_id = 'MA201';| roll_no |
|---|
| 101 |
| 102 |
| 103 |
| 105 |
| 106 |
| 109 |
| 111 |
SELECT roll_no FROM Enrollment WHERE course_id = 'CS201'
UNION ALL
SELECT roll_no FROM Enrollment WHERE course_id = 'MA201';| roll_no |
|---|
| 101 |
| 102 |
| 103 |
| 106 |
| 109 |
| 111 |
| 101 |
| 105 |
| 109 |
SELECT roll_no FROM Enrollment WHERE course_id = 'CS201'
INTERSECT
SELECT roll_no FROM Enrollment WHERE course_id = 'MA201';| roll_no |
|---|
| 101 |
| 109 |
SELECT roll_no FROM Enrollment WHERE course_id = 'CS201'
EXCEPT
SELECT roll_no FROM Enrollment WHERE course_id = 'MA201';| roll_no |
|---|
| 102 |
| 103 |
| 106 |
| 111 |
MySQL supports INTERSECT and EXCEPT from version 8.0.31. Oracle calls EXCEPT MINUS. On older MySQL, write INTERSECT with IN and EXCEPT with NOT IN (Day 18).
17.2Aggregate functions
An aggregate function takes a whole column of values and returns one value.
SELECT COUNT(*) AS enrollments,
COUNT(marks) AS with_marks,
COUNT(DISTINCT course_id) AS courses,
SUM(marks) AS total,
ROUND(AVG(marks), 2) AS average,
MIN(marks) AS lowest,
MAX(marks) AS highest
FROM Enrollment;| enrollments | with_marks | courses | total | average | lowest | highest |
|---|---|---|---|---|---|---|
| 18 | 17 | 7 | 1357 | 79.82 | 58 | 95 |
Notice COUNT(*) = 18 but COUNT(marks) = 17: Sneha's Data Structures marks are NULL, and every aggregate except COUNT(*) ignores NULL.
17.3GROUP BY and HAVING
GROUP BY splits the rows into groups with the same value and computes the aggregate for each group. HAVING then filters the groups.
SELECT course_id, COUNT(*) AS students, ROUND(AVG(marks), 1) AS avg_marks
FROM Enrollment
WHERE marks IS NOT NULL -- 1. filter rows
GROUP BY course_id -- 2. form groups
HAVING COUNT(*) >= 2 -- 3. filter groups
ORDER BY avg_marks DESC; -- 4. sort the result| course_id | students | avg_marks |
|---|---|---|
| CS301 | 2 | 89.5 |
| MA201 | 3 | 83.7 |
| EC201 | 2 | 79.5 |
| CS201 | 6 | 78.2 |
| CS202 | 2 | 70.5 |
| Point | WHERE | HAVING |
|---|---|---|
| Filters | Individual rows | Groups |
| Runs | Before GROUP BY | After GROUP BY |
| Can use aggregates? | No | Yes |
| Example | WHERE marks > 50 | HAVING AVG(marks) > 75 |
Every column in SELECT must either appear in GROUP BY or be inside an aggregate. SELECT dept_id, name, COUNT(*) FROM Student GROUP BY dept_id is wrong: which of the five CSE names should it show? MySQL rejects it in its default ONLY_FULL_GROUP_BY mode.
17.4NULL values and three-valued logic
NULL means "unknown" or "not applicable". It is not zero and not an empty string, so SQL treats it specially:
SELECT 5 + NULL AS arithmetic, -- unknown + 5 is unknown
NULL = NULL AS equal, -- is unknown equal to unknown? unknown
NULL IS NULL AS is_null, -- the right way to test
COALESCE(NULL, 'none') AS replaced;| arithmetic | equal | is_null | replaced |
|---|---|---|---|
| NULL | NULL | 1 | none |
Any comparison involving NULL gives a third truth value, UNKNOWN. WHERE and HAVING keep a row only when the condition is TRUE, so UNKNOWN rows are dropped.
| AND | TRUE | FALSE | UNKNOWN |
|---|---|---|---|
| TRUE | TRUE | FALSE | UNKNOWN |
| FALSE | FALSE | FALSE | FALSE |
| UNKNOWN | UNKNOWN | FALSE | UNKNOWN |
| OR | TRUE | FALSE | UNKNOWN |
|---|---|---|---|
| TRUE | TRUE | TRUE | TRUE |
| FALSE | TRUE | FALSE | UNKNOWN |
| UNKNOWN | TRUE | UNKNOWN | UNKNOWN |
NOT UNKNOWN = UNKNOWN. That is why WHERE marks >= 50 OR marks < 50 still misses Sneha's row:
SELECT COUNT(*) FROM Enrollment WHERE marks >= 50 OR marks < 50; -- 17, not 18| COUNT(*) |
|---|
| 17 |
WHERE email = NULLnever matches. UseIS NULL.- Putting COUNT or AVG in WHERE. Use HAVING.
- Using COUNT(column) when you mean "number of rows"; it skips NULLs.
- Forgetting that UNION removes duplicates. Use UNION ALL to keep them.
- UNION, INTERSECT, EXCEPT remove duplicates; add ALL to keep them. Same number and type of columns required.
- Aggregates: COUNT, SUM, AVG, MIN, MAX. All except COUNT(*) ignore NULL.
- WHERE filters rows before grouping; HAVING filters groups after.
- Non-aggregated SELECT columns must be in GROUP BY.
- NULL in arithmetic → NULL; in comparison → UNKNOWN; test with IS NULL.
- Three-valued logic: TRUE, FALSE, UNKNOWN; WHERE keeps only TRUE.
- Differentiate between WHERE and HAVING. [2 marks]
- Explain aggregate functions in SQL with examples. [5 marks]
- What is a NULL value? Explain three-valued logic with truth tables. [5 marks]
- Write SQL: for each department, the number of faculty and their average salary, only where the average is above 90000. [5 marks]
Nested Queries and Views
- Write subqueries that return one value, a list, or a table.
- Tell a correlated subquery from an ordinary one; use EXISTS and NOT EXISTS.
- Create and use views, and explain why they are useful.
What does WHERE do with UNKNOWN? Write SQL for "courses with more than 2 students".
18.1What is a nested query?
A subquery is a SELECT written inside another statement. The DBMS uses its result as part of the outer query. Subqueries are classified by what they return:
| Kind | Returns | Used with |
|---|---|---|
| Scalar subquery | One value (1 row, 1 column) | =, <, > … |
| Column (multi-row) subquery | A list of values | IN, NOT IN, ANY, ALL |
| Table subquery (derived table) | A whole table | In FROM, with an alias |
18.2Scalar and IN subqueries
-- Faculty who earn more than the average
SELECT name, salary
FROM Faculty
WHERE salary > (SELECT AVG(salary) FROM Faculty);| name | salary |
|---|---|
| Dr. Sen | 120000 |
| Dr. Paul | 115000 |
| Dr. Bose | 110000 |
-- Students enrolled in a 4-credit course
SELECT name
FROM Student
WHERE roll_no IN (
SELECT roll_no FROM Enrollment
WHERE course_id IN (SELECT course_id FROM Course
WHERE credits = 4));| name |
|---|
| Ananya |
| Rahul |
| Priya |
| Arjun |
| Kabir |
| Sneha |
| Isha |
| Tanya |
ANY and ALL
> ANY (subquery) is true if the value is greater than at least one value in the list; > ALL if greater than every value. SOME means the same as ANY. They can always be rewritten with MIN and MAX:
| Using ANY / ALL (MySQL) | Same as |
|---|---|
salary > ANY (SELECT salary FROM Faculty WHERE dept_id='ECE') | salary > (SELECT MIN(salary) …) |
salary > ALL (SELECT salary FROM Faculty WHERE dept_id='ECE') | salary > (SELECT MAX(salary) …) |
x = ANY (…) | x IN (…) |
x <> ALL (…) | x NOT IN (…) |
-- Faculty paid more than everyone in ECE (ALL written with MAX)
SELECT name, dept_id, salary FROM Faculty
WHERE salary > (SELECT MAX(salary) FROM Faculty WHERE dept_id = 'ECE');| name | dept_id | salary |
|---|---|---|
| Dr. Sen | CSE | 120000 |
18.3Correlated subqueries and EXISTS
A correlated subquery refers to a column of the outer query, so it is re-evaluated once for each row of the outer query. An ordinary (non-correlated) subquery runs once.
-- Students who scored above the average of THAT course
SELECT e.roll_no, e.course_id, e.marks
FROM Enrollment e
WHERE e.marks > (SELECT AVG(e2.marks) FROM Enrollment e2
WHERE e2.course_id = e.course_id) -- refers to outer e
ORDER BY e.course_id;| roll_no | course_id | marks |
|---|---|---|
| 101 | CS201 | 88 |
| 106 | CS201 | 79 |
| 109 | CS201 | 82 |
| 111 | CS201 | 90 |
| 101 | CS202 | 76 |
| 111 | CS301 | 95 |
| 103 | EC201 | 85 |
| 101 | MA201 | 91 |
| 105 | MA201 | 93 |
EXISTS (subquery) is true when the subquery returns at least one row; NOT EXISTS when it returns none. It is almost always correlated.
-- Departments with at least one student
SELECT dept_name FROM Department d
WHERE EXISTS (SELECT * FROM Student s
WHERE s.dept_id = d.dept_id);| dept_name |
|---|
| Computer Science |
| Electronics |
| Mathematics |
| Physics |
-- Courses nobody has taken
SELECT title FROM Course c
WHERE NOT EXISTS (SELECT * FROM Enrollment e
WHERE e.course_id = c.course_id);| title |
|---|
| Graph Theory |
Relational algebra used ÷ (Day 13). SQL has no division keyword, so we say it twice negatively: there is no CSE course that the student has not taken.
SELECT s.roll_no, s.name FROM Student s
WHERE NOT EXISTS (
SELECT * FROM Course c
WHERE c.dept_id = 'CSE'
AND NOT EXISTS (SELECT * FROM Enrollment e
WHERE e.roll_no = s.roll_no
AND e.course_id = c.course_id));| roll_no | name |
|---|
The result is empty: CSE offers three courses (CS201, CS202, CS301) and nobody has taken all three. Change the condition to c.dept_id = 'CSE' AND c.credits = 4 (CSE's two 4-credit courses) and Ananya (101) and Rahul (102) appear. Try it.
18.4Subqueries in FROM (derived tables)
-- Students whose average marks are above 80
SELECT t.roll_no, t.avg_marks
FROM (SELECT roll_no, AVG(marks) AS avg_marks
FROM Enrollment
GROUP BY roll_no) AS t -- a derived table needs an alias
WHERE t.avg_marks > 80;| roll_no | avg_marks |
|---|---|
| 101 | 85 |
| 105 | 93 |
| 106 | 81.5 |
| 111 | 92.5 |
18.5Views
A view is a virtual table defined by a query. It stores no data of its own (only its definition); each time you use it, the DBMS runs the query on the base tables.
CREATE VIEW result_sheet AS
SELECT s.roll_no, s.name, c.title, e.marks, e.grade
FROM Enrollment e
JOIN Student s ON s.roll_no = e.roll_no
JOIN Course c ON c.course_id = e.course_id;
SELECT * FROM result_sheet WHERE grade = 'A' ORDER BY marks DESC;| roll_no | name | title | marks | grade |
|---|---|---|---|---|
| 111 | Tanya | Operating Systems | 95 | A |
| 105 | Meera | Discrete Maths | 93 | A |
| 101 | Ananya | Discrete Maths | 91 | A |
| 111 | Tanya | DBMS | 90 | A |
| 101 | Ananya | DBMS | 88 | A |
| 103 | Priya | Signals | 85 | A |
| 106 | Kabir | Operating Systems | 84 | A |
| 109 | Isha | DBMS | 82 | A |
| 104 | Arjun | Digital Electronics | 81 | A |
- Simplicity: hide a long join behind one name.
- Security: give a user the view, not the base table (Day 20).
- Logical data independence: programs use the view even if base tables change (Day 4).
- Consistency: everyone uses the same definition of "result".
CREATE VIEW v AS SELECT …CREATE OR REPLACE VIEW v AS …(MySQL)DROP VIEW v;… WITH CHECK OPTIONrejects updates through the view that would make the row disappear from it (MySQL)
Updatable views
You can INSERT, UPDATE or DELETE through a view only if each view row maps to exactly one base-table row. In MySQL a view is not updatable if it uses aggregates, GROUP BY, HAVING, DISTINCT, UNION, or certain joins and subqueries. result_sheet above is a join of three tables, so most changes through it are refused. A materialized view stores its result physically and is refreshed periodically; Oracle and PostgreSQL support it, MySQL does not.
- Using
=with a subquery that returns several rows. UseIN. NOT INwith a subquery that can return NULL gives no rows at all. Prefer NOT EXISTS.- Forgetting the alias on a derived table.
- Thinking a view stores a copy of the data.
- Subquery = SELECT inside another statement; scalar, column (multi-row) or table.
- Correlated subquery refers to the outer query and runs once per outer row.
- EXISTS is true if the subquery returns any row; NOT EXISTS if none.
- > ALL = greater than MAX; > ANY = greater than MIN; = ANY is IN.
- Division in SQL = double NOT EXISTS.
- View = virtual table (stored query); uses: simplicity, security, logical independence.
- Differentiate between correlated and non-correlated subqueries. [5 marks]
- What is a view? State its advantages. [5 marks]
- Explain IN, EXISTS, ANY and ALL with examples. [5 marks]
- Write SQL to find the names of faculty who teach no course. [2 marks]
Assertions, Stored Procedures and Triggers
- Write an assertion and explain why most DBMSs replace it with triggers.
- Create and call a MySQL stored procedure with IN and OUT parameters.
- Write BEFORE and AFTER triggers using NEW and OLD.
What is a correlated subquery? What does NOT EXISTS return when the subquery is empty?
19.1Assertions
CHECK constraints look at one row. Some rules involve many rows or many tables, such as "no student may take more than 6 courses". Standard SQL expresses these as assertions.
An assertion is a named condition that the database must always satisfy. The DBMS checks it on every change that could violate it and rejects the change if it would.
CREATE ASSERTION max_six_courses CHECK (
NOT EXISTS (SELECT roll_no FROM Enrollment
GROUP BY roll_no
HAVING COUNT(*) > 6)
);Assertions are part of the SQL standard and appear in exams, but they are expensive to check, so MySQL, Oracle, PostgreSQL and SQL Server do not implement them. In practice the same rule is enforced with a trigger (below).
19.2Stored procedures
A stored procedure is a named block of SQL statements stored in the database and run with CALL. It can take parameters: IN (input), OUT (output) and INOUT (both).
DELIMITER //
-- List the students of one department
CREATE PROCEDURE dept_students(IN d VARCHAR(5))
BEGIN
SELECT roll_no, name, semester FROM Student
WHERE dept_id = d ORDER BY roll_no;
END //
-- Count students in a department and return the number
CREATE PROCEDURE count_students(IN d VARCHAR(5), OUT total INT)
BEGIN
SELECT COUNT(*) INTO total FROM Student WHERE dept_id = d;
END //
DELIMITER ;
CALL dept_students('ECE');
CALL count_students('CSE', @n);
SELECT @n AS cse_students; -- 5Why DELIMITER? The procedure body contains semicolons. DELIMITER // tells the MySQL client to treat // as the end of the CREATE statement, so the inner semicolons are not taken as the end. Switch back with DELIMITER ;.
- Written once, reused by every application.
- Fewer network round-trips: many statements in one call.
- Security: users can be allowed to CALL a procedure without direct access to the tables.
- Business rules kept in one place.
- A function returns exactly one value with RETURN and can be used inside SELECT.
- A procedure is run with CALL and returns results through OUT parameters or result sets.
CREATE FUNCTION grade_of(m INT) RETURNS CHAR(1) DETERMINISTIC RETURN …
19.3Triggers
A trigger is a statement the DBMS runs automatically when a specified event happens to a table. Triggers follow the Event–Condition–Action (ECA) model: an event (INSERT, UPDATE or DELETE) is checked against a condition, and if it holds the action runs.
| Part | Choices | Meaning |
|---|---|---|
| Timing | BEFORE / AFTER | BEFORE can check or change the new values; AFTER reacts once the change is done |
| Event | INSERT / UPDATE / DELETE | Which change fires it |
| Granularity | FOR EACH ROW | Runs once per affected row (MySQL supports only this) |
| NEW / OLD | NEW.col, OLD.col | NEW = row after the change (INSERT, UPDATE); OLD = row before (UPDATE, DELETE) |
MySQL: fill the grade automatically and enforce the 6-course rule
DELIMITER //
CREATE TRIGGER set_grade BEFORE INSERT ON Enrollment
FOR EACH ROW
BEGIN
SET NEW.grade = CASE WHEN NEW.marks >= 80 THEN 'A'
WHEN NEW.marks >= 70 THEN 'B'
ELSE 'C' END;
END //
CREATE TRIGGER max_six BEFORE INSERT ON Enrollment
FOR EACH ROW
BEGIN
IF (SELECT COUNT(*) FROM Enrollment WHERE roll_no = NEW.roll_no) >= 6 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'A student may take at most 6 courses';
END IF;
END //
DELIMITER ;Try a trigger in the SQL Lab: an audit log
The browser engine needs no DELIMITER and cannot change NEW, so this AFTER trigger records every change of marks in a log table instead.
CREATE TABLE marks_log (roll_no INT, course_id VARCHAR(8),
old_marks INT, new_marks INT, changed_on DATE);
CREATE TRIGGER log_marks AFTER UPDATE OF marks ON Enrollment
FOR EACH ROW
BEGIN
INSERT INTO marks_log
VALUES (OLD.roll_no, OLD.course_id, OLD.marks, NEW.marks, '2026-10-25');
END;
UPDATE Enrollment SET marks = 70 WHERE roll_no = 102 AND course_id = 'CS202';
UPDATE Enrollment SET marks = 60 WHERE roll_no = 103 AND course_id = 'CS201';
SELECT * FROM marks_log;| roll_no | course_id | old_marks | new_marks | changed_on |
|---|---|---|---|---|
| 102 | CS202 | 65 | 70 | 2026-10-25 |
| 103 | CS201 | 58 | 60 | 2026-10-25 |
- Enforce complex rules (the job assertions were meant to do).
- Keep audit logs of who changed what.
- Fill or correct values automatically (grade from marks).
- Keep summary columns up to date.
- They run invisibly, so errors are hard to trace.
- A trigger can fire another trigger (cascading).
- Too many triggers slow down every insert and update.
- Keep logic simple; document every trigger.
- Forgetting DELIMITER in the MySQL client, so the CREATE stops at the first semicolon.
- Using NEW in a DELETE trigger or OLD in an INSERT trigger: they do not exist there.
- Trying to change NEW in an AFTER trigger. Change values in a BEFORE trigger.
- Writing CREATE ASSERTION in the MySQL lab. It is not supported; use a trigger.
- Assertion: database-wide condition, CREATE ASSERTION … CHECK (…); standard SQL, rarely implemented.
- Stored procedure: named stored SQL block; IN, OUT, INOUT; run with CALL.
- Function returns one value and can be used in SELECT; procedure is CALLed.
- Trigger: automatic action on INSERT/UPDATE/DELETE; ECA model; BEFORE/AFTER; FOR EACH ROW; NEW and OLD.
- DELIMITER changes the statement terminator in the MySQL client.
- What is an assertion? Give an example. [2 marks]
- Differentiate between stored procedures and functions. [5 marks]
- What is a trigger? Explain the ECA model with an example. [5 marks]
- Write a MySQL procedure top_students(IN c VARCHAR(8)) that lists the three highest marks in course c. [5 marks]
Database Security and Unit IV Test
- State the goals of database security and common threats.
- Grant and revoke privileges, and use roles and views for access control.
- Explain SQL injection and how to prevent it.
What is a view? Name one reason views help security.
20.1Goals and threats
| Goal | Meaning | Threat example |
|---|---|---|
| Confidentiality (secrecy) | Only authorised users can read data | A student reading other students' marks |
| Integrity | Only authorised, valid changes are made | Someone changing their own grade |
| Availability | Authorised users can use the data when needed | A server crash during result publication |
Two different questions protect these goals: authentication asks "who are you?" (user name and password), and authorization asks "what are you allowed to do?" (privileges).
20.2Privileges: GRANT and REVOKE
SQL uses discretionary access control: the owner of an object decides who else may use it, by granting privileges.
| Privilege | Allows |
|---|---|
| SELECT | Read rows |
| INSERT | Add rows |
| UPDATE (columns) | Change rows, optionally only listed columns |
| DELETE | Remove rows |
| REFERENCES | Create foreign keys pointing to the table |
| ALL PRIVILEGES | Everything |
-- 1. Create accounts (authentication)
CREATE USER 'clerk'@'localhost' IDENTIFIED BY 'Clerk@2026';
CREATE USER 'teacher'@'localhost' IDENTIFIED BY 'Teach@2026';
-- 2. Grant privileges (authorization)
GRANT SELECT ON college.Student TO 'clerk'@'localhost';
GRANT SELECT, UPDATE (marks, grade) ON college.Enrollment TO 'teacher'@'localhost';
GRANT SELECT ON college.Course TO 'teacher'@'localhost' WITH GRANT OPTION;
SHOW GRANTS FOR 'teacher'@'localhost';
-- 3. Take a privilege back
REVOKE UPDATE ON college.Enrollment FROM 'teacher'@'localhost';WITH GRANT OPTION lets the receiver pass the privilege on to others. In standard SQL, REVOKE … CASCADE also removes privileges that were passed on, while RESTRICT refuses if any were; MySQL does not cascade revokes.
20.3Roles
Granting the same ten privileges to 60 teachers one by one is error-prone. A role is a named set of privileges granted to users as a group (MySQL 8.0+).
CREATE ROLE 'exam_cell';
GRANT SELECT, UPDATE ON college.Enrollment TO 'exam_cell';
GRANT 'exam_cell' TO 'teacher'@'localhost';
SET DEFAULT ROLE 'exam_cell' TO 'teacher'@'localhost';20.4Views for security
Give a user a view instead of the table, and they see only the rows and columns the view shows. The accounts clerk needs names and departments, not dates of birth or email addresses:
CREATE VIEW clerk_view AS
SELECT roll_no, name, dept_id FROM Student;
SELECT * FROM clerk_view;
-- In MySQL: GRANT SELECT ON college.clerk_view TO 'clerk'@'localhost';| roll_no | name | dept_id |
|---|---|---|
| 101 | Ananya | CSE |
| 102 | Rahul | CSE |
| 103 | Priya | ECE |
| 104 | Arjun | ECE |
| 105 | Meera | MTH |
| 106 | Kabir | CSE |
| 107 | Sneha | CSE |
| 108 | Rohan | ECE |
| 109 | Isha | MTH |
| 110 | Aman | PHY |
| 111 | Tanya | CSE |
| 112 | Dev | NULL |
20.5SQL injection
A program that glues user input straight into SQL text can be tricked into running a different query. Suppose a portal builds this query from a search box:
-- Program code (unsafe): "SELECT * FROM Student WHERE name = '" + input + "'"
-- A normal user types: Priya
SELECT roll_no, name, email FROM Student WHERE name = 'Priya';| roll_no | name | |
|---|---|---|
| 103 | Priya | priya@clg.edu |
An attacker types x' OR '1'='1. The program glues it in and the condition becomes always true, so every student's email leaks:
SELECT roll_no, name, email FROM Student WHERE name = 'x' OR '1'='1';| roll_no | name | |
|---|---|---|
| 101 | Ananya | ananya@clg.edu |
| 102 | Rahul | rahul.d@clg.edu |
| 103 | Priya | priya@clg.edu |
| 104 | Arjun | arjun@clg.edu |
| 105 | Meera | meera@clg.edu |
| 106 | Kabir | kabir@clg.edu |
| 107 | Sneha | sneha@clg.edu |
| 108 | Rohan | NULL |
| 109 | Isha | isha@clg.edu |
| 110 | Aman | aman@clg.edu |
| 111 | Tanya | tanya@clg.edu |
| 112 | Dev | dev@clg.edu |
- Prepared statements / parameterised queries: the SQL text is fixed (
WHERE name = ?) and the input is sent separately as data, never as SQL. - Validate input: allow only expected characters and lengths.
- Least privilege: the web application's database user gets only the privileges it needs (no DROP, no access to other tables).
- Show generic error messages so attackers learn nothing about the schema.
20.6Other security measures
- Mandatory access control (MAC): data and users get security levels (top secret, secret, …); used in military systems. SQL's GRANT system is discretionary (DAC).
- Encryption of stored data and network connections (SSL/TLS).
- Audit trail: a log of who accessed or changed what (triggers can build one, Day 19).
- Backups for availability (recovery is Unit VII).
- Mixing up authentication (who) and authorization (what).
- Granting ALL PRIVILEGES to an application user.
- Thinking a strong password stops SQL injection. It does not; prepared statements do.
- Security goals: confidentiality, integrity, availability.
- Authentication = identity; authorization = privileges.
- GRANT privileges ON object TO user [WITH GRANT OPTION]; REVOKE privileges ON object FROM user.
- Role = named group of privileges.
- Views restrict rows and columns a user can see.
- SQL injection: input changes the query; prevent with prepared statements, validation, least privilege.
- DAC (owner grants) vs MAC (security levels).
20.7Unit IV test
20.8Unit IV question bank
- Differentiate between DDL and DML with examples. [2 marks]
- What is the difference between DELETE and TRUNCATE? [2 marks]
- What is a NULL value? [2 marks]
- Define trigger. [2 marks]
- Explain integrity constraints in SQL with examples. [5 marks]
- Explain GROUP BY and HAVING with an example. [5 marks]
- Explain set operations in SQL. [5 marks]
- What is a view? Can every view be updated? Explain. [5 marks]
- Explain GRANT and REVOKE with examples. [5 marks]
- Explain nested and correlated queries with examples. [10 marks]
- Explain stored procedures and triggers with examples. [10 marks]
- For Employee(eid, name, salary, dno) and Dept(dno, dname): write SQL for (a) number of employees per department; (b) departments with average salary above 50000; (c) employees earning more than everyone in department 5; (d) a view of names and department names; (e) departments with no employees. [10 marks]
Unit IV revision
Everything to revise for Unit IV in one place: the exam quick points from every class, the diagrams to practise drawing, and one quiz that mixes all the day quizzes. Tap Open notes whenever a point needs more explanation.
Exam quick points, class by class
- SQL DDL defines schemas, types, constraints, indexes; DML queries and changes data.
- Constraints: NOT NULL, CHECK (domain); UNIQUE, PRIMARY KEY (key/entity); FOREIGN KEY (referential).
- Column-level vs table-level constraints; composite keys need table-level.
- Referential actions: RESTRICT/NO ACTION (default), CASCADE, SET NULL, SET DEFAULT.
- CHAR fixed length, VARCHAR variable; DECIMAL exact, FLOAT approximate.
- UNION, INTERSECT, EXCEPT remove duplicates; add ALL to keep them. Same number and type of columns required.
- Aggregates: COUNT, SUM, AVG, MIN, MAX. All except COUNT(*) ignore NULL.
- WHERE filters rows before grouping; HAVING filters groups after.
- Non-aggregated SELECT columns must be in GROUP BY.
- NULL in arithmetic → NULL; in comparison → UNKNOWN; test with IS NULL.
- Three-valued logic: TRUE, FALSE, UNKNOWN; WHERE keeps only TRUE.
- Subquery = SELECT inside another statement; scalar, column (multi-row) or table.
- Correlated subquery refers to the outer query and runs once per outer row.
- EXISTS is true if the subquery returns any row; NOT EXISTS if none.
- > ALL = greater than MAX; > ANY = greater than MIN; = ANY is IN.
- Division in SQL = double NOT EXISTS.
- View = virtual table (stored query); uses: simplicity, security, logical independence.
- Assertion: database-wide condition, CREATE ASSERTION … CHECK (…); standard SQL, rarely implemented.
- Stored procedure: named stored SQL block; IN, OUT, INOUT; run with CALL.
- Function returns one value and can be used in SELECT; procedure is CALLed.
- Trigger: automatic action on INSERT/UPDATE/DELETE; ECA model; BEFORE/AFTER; FOR EACH ROW; NEW and OLD.
- DELIMITER changes the statement terminator in the MySQL client.
- Security goals: confidentiality, integrity, availability.
- Authentication = identity; authorization = privileges.
- GRANT privileges ON object TO user [WITH GRANT OPTION]; REVOKE privileges ON object FROM user.
- Role = named group of privileges.
- Views restrict rows and columns a user can see.
- SQL injection: input changes the query; prevent with prepared statements, validation, least privilege.
- DAC (owner grants) vs MAC (security levels).
Diagrams to practise
Draw each one from memory in under three minutes, then open the class to compare.