Unit 1: SQL implementation and database design
Relational Database Management System Laboratory notes · PTU syllabus (PGCA1907)
On this page
Unit summary
This lab implements SQL and database design: DDL to create, alter, modify and drop tables, constraints — check, entity integrity, referential integrity, unique and not null — DML and DCL, built-in functions, nested and join queries, cursors, procedures, functions and triggers, embedded SQL, ER-based and normalised designs for payroll, banking and library systems, and a complete data model for a university.
After this unit you can
- Create and modify tables with constraints
- Write DML, DCL, nested and join queries with built-in functions
- Write cursors, procedures, functions and triggers
- Design normalised databases from ER models
PTU syllabus topics
- DDL commands for table creation/alteration/modification/drop
- constraint implementation (check, entity integrity, referential integrity, unique, null value)
- DML and DCL commands
- built-in functions
- nested and join queries
- cursors
- procedures and functions
- triggers
- embedded SQL
- ER-model and normalization-based design for payroll
- banking and library management systems
- a complete conceptual and relational data model design for a university database application
PRIMARY KEY
Unique and not null
FOREIGN KEY
Referential integrity
UNIQUE
No duplicate values
NOT NULL
Value required
CHECK
Custom rule, e.g. salary > 0
Topic 1
DDL: create, alter, modify and drop
sqlCREATE DATABASE university;
USE university;
CREATE TABLE department (
dept_id INT PRIMARY KEY, -- entity integrity
dept_name VARCHAR(40) NOT NULL UNIQUE, -- not null and unique
budget DECIMAL(12,2) CHECK (budget > 0) -- check
);
CREATE TABLE student (
roll INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
dept_id INT,
cgpa DECIMAL(3,2) CHECK (cgpa BETWEEN 0 AND 10),
FOREIGN KEY (dept_id) REFERENCES department(dept_id) -- referential integrity
ON DELETE SET NULL ON UPDATE CASCADE
);
ALTER TABLE student ADD email VARCHAR(60) UNIQUE;
ALTER TABLE student MODIFY name VARCHAR(80) NOT NULL; -- MySQL
ALTER TABLE student DROP COLUMN email;
ALTER TABLE student ADD CONSTRAINT chk_name CHECK (CHAR_LENGTH(name) > 1);
RENAME TABLE student TO pg_student; RENAME TABLE pg_student TO student;
DROP TABLE IF EXISTS temp;Topic 2
DML and DCL
sqlINSERT INTO department VALUES (1, 'Computer Applications', 2500000), (2, 'Management', 1800000);
INSERT INTO student (roll, name, dept_id, cgpa) VALUES (101, 'Aman', 1, 8.4), (102, 'Riya', 1, 9.1), (103, 'Kabir', 2, 7.2);
UPDATE student SET cgpa = cgpa + 0.1 WHERE dept_id = 1 AND cgpa < 9.9;
DELETE FROM student WHERE roll = 103;
CREATE USER 'clerk'@'localhost' IDENTIFIED BY 'Str0ng#Pass';
GRANT SELECT, INSERT ON university.student TO 'clerk'@'localhost';
REVOKE INSERT ON university.student FROM 'clerk'@'localhost';- Test each constraint by inserting a violating row (duplicate key, cgpa 11, dept_id 99) and noting the error.
Topic 3
Built-in functions
sqlSELECT UPPER(name), LENGTH(name), SUBSTRING(name, 1, 3), CONCAT(name, '-', roll) FROM student; -- string
SELECT ROUND(cgpa, 1), CEIL(cgpa), FLOOR(cgpa), MOD(roll, 2), POWER(2, 5) FROM student; -- numeric
SELECT CURDATE(), NOW(), DATEDIFF('2026-12-31', CURDATE()), DATE_FORMAT(NOW(), '%d-%m-%Y'); -- date
SELECT dept_id, COUNT(*), AVG(cgpa), MAX(cgpa), MIN(cgpa) FROM student GROUP BY dept_id; -- aggregate
SELECT name, IFNULL(email, 'not given'), CASE WHEN cgpa >= 9 THEN 'O' WHEN cgpa >= 8 THEN 'A+' ELSE 'A' END FROM student;Topic 4
Nested and join queries
sqlSELECT name FROM student WHERE cgpa > (SELECT AVG(cgpa) FROM student);
SELECT dept_name FROM department d WHERE NOT EXISTS (SELECT 1 FROM student s WHERE s.dept_id = d.dept_id);
SELECT s.name, d.dept_name FROM student s INNER JOIN department d ON s.dept_id = d.dept_id;
SELECT d.dept_name, COUNT(s.roll) AS strength
FROM department d LEFT JOIN student s ON s.dept_id = d.dept_id GROUP BY d.dept_name;
SELECT a.name, b.name FROM student a JOIN student b ON a.dept_id = b.dept_id AND a.roll < b.roll; -- self joinTopic 5
Cursors
sqlDELIMITER //
CREATE PROCEDURE list_toppers()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE v_name VARCHAR(80); DECLARE v_cgpa DECIMAL(3,2);
DECLARE c CURSOR FOR SELECT name, cgpa FROM student WHERE cgpa >= 9;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN c;
read_loop: LOOP
FETCH c INTO v_name, v_cgpa;
IF done THEN LEAVE read_loop; END IF;
SELECT CONCAT(v_name, ' : ', v_cgpa) AS topper;
END LOOP;
CLOSE c;
END //
DELIMITER ;
CALL list_toppers();Topic 6
Procedures, functions and triggers
sqlDELIMITER //
CREATE PROCEDURE transfer(IN from_acc INT, IN to_acc INT, IN amt DECIMAL(10,2))
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
START TRANSACTION;
UPDATE account SET balance = balance - amt WHERE acc_no = from_acc AND balance >= amt;
IF ROW_COUNT() = 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient balance';
END IF;
UPDATE account SET balance = balance + amt WHERE acc_no = to_acc;
COMMIT;
END //
CREATE FUNCTION net_salary(basic DECIMAL(10,2)) RETURNS DECIMAL(10,2) DETERMINISTIC
BEGIN
RETURN basic + basic * 0.42 + basic * 0.10 - basic * 0.12; -- DA 42%, HRA 10%, PF 12% (illustrative)
END //
CREATE TRIGGER before_issue BEFORE INSERT ON issue
FOR EACH ROW
BEGIN
IF (SELECT copies FROM book WHERE book_id = NEW.book_id) = 0 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'No copies available';
END IF;
END //
CREATE TRIGGER after_issue AFTER INSERT ON issue
FOR EACH ROW UPDATE book SET copies = copies - 1 WHERE book_id = NEW.book_id //
DELIMITER ;Topic 7
Embedded SQL
c/* Pro*C style embedded SQL in C */
EXEC SQL BEGIN DECLARE SECTION;
int roll; char name[50]; float cgpa;
EXEC SQL END DECLARE SECTION;
EXEC SQL INCLUDE SQLCA;
EXEC SQL CONNECT :user IDENTIFIED BY :pwd;
roll = 101;
EXEC SQL SELECT name, cgpa INTO :name, :cgpa FROM student WHERE roll = :roll;
if (sqlca.sqlcode == 0) printf("%s %.2f\n", name, cgpa);
EXEC SQL DECLARE c1 CURSOR FOR SELECT name FROM student;
EXEC SQL OPEN c1;
/* EXEC SQL FETCH c1 INTO :name; in a loop until NOT FOUND */
EXEC SQL CLOSE c1;
EXEC SQL COMMIT WORK RELEASE;- A precompiler converts EXEC SQL statements into library calls; in labs without Pro*C, the same exercise is done through JDBC or Python's mysql-connector with parameterised queries.
Topic 8
Designing payroll, banking and library databases
Payroll
EMPLOYEE(emp_id, name, dept_id, grade_id), DEPARTMENT, GRADE(grade_id, basic, da_rate, hra_rate), SALARY(emp_id, month, gross, deductions, net), ATTENDANCE
Employee belongs to one department and grade; one salary row per employee per month
Banking
CUSTOMER, BRANCH, ACCOUNT(acc_no, type, branch_id, balance), DEPOSITOR(cust_id, acc_no), LOAN, BORROWER, TRANSACTION(txn_id, acc_no, date, type, amount)
M:N customers–accounts through DEPOSITOR; account at one branch
Library
BOOK(book_id, isbn, title, publisher_id, copies), AUTHOR, BOOK_AUTHOR, MEMBER, ISSUE(issue_id, book_id, member_id, issue_date, due_date, return_date), FINE
M:N books–authors through BOOK_AUTHOR; issue links member and book
- 1List entities, attributes and relationships
- 2Draw the ER diagram with cardinalities
- 3Reduce to relations; M:N become separate tables
- 4Identify FDs and normalise to 3NF or BCNF
- 5Create tables with constraints and test with sample data and queries
Topic 9
University database: conceptual and relational model
Entities
DEPARTMENT, INSTRUCTOR, STUDENT, COURSE, SECTION (weak, of COURSE), CLASSROOM, TIME_SLOT
Relationships
INST_DEPT (N:1), STUD_DEPT (N:1), TEACHES (M:N), TAKES (M:N with grade), ADVISOR (N:1), PREREQ (course to course), SEC_CLASS
Constraints
Total participation of SECTION in SEC_COURSE; budget > 0; grade in a valid set
| Relation | Primary key | Foreign keys |
|---|---|---|
| department(dept_name, building, budget) | dept_name | — |
| instructor(ID, name, dept_name, salary) | ID | dept_name |
| student(ID, name, dept_name, tot_cred) | ID | dept_name |
| course(course_id, title, dept_name, credits) | course_id | dept_name |
| section(course_id, sec_id, semester, year, building, room_no, time_slot_id) | course_id, sec_id, semester, year | course_id; building and room_no |
| teaches(ID, course_id, sec_id, semester, year) | all attributes | ID; section key |
| takes(ID, course_id, sec_id, semester, year, grade) | ID + section key | ID; section key |
| advisor(s_ID, i_ID) | s_ID | s_ID; i_ID |
| prereq(course_id, prereq_id) | both | both reference course |
Key terms
- Referential integrity
- Foreign keys must match existing primary keys
- Cursor
- Mechanism for processing query results one row at a time
- Stored procedure
- Named SQL routine stored in the database
- Trigger
- Routine fired automatically by a data change
- Embedded SQL
- SQL statements inside a host-language program
Quick revision
- CREATE, ALTER (ADD, MODIFY, DROP), RENAME, DROP; constraints.
- INSERT, UPDATE, DELETE; CREATE USER, GRANT, REVOKE.
- String, numeric, date, aggregate functions; CASE, IFNULL.
- Subqueries, EXISTS, inner, outer and self joins; cursors with handlers; procedures with transactions; functions; BEFORE and AFTER triggers.
- Embedded SQL host variables and SQLCA; payroll, banking, library and university designs.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.How do you add a CHECK constraint to an existing table?
- Q2.What does ON DELETE SET NULL do?
- Q3.Distinguish DELETE and TRUNCATE.
- Q4.What is a NOT FOUND handler used for in a cursor?
- Q5.Distinguish BEFORE and AFTER triggers.
- Q6.Which table resolves the M:N relationship between books and authors?
Long-answer questions
- Q1.Create tables with all types of constraints and test them.
- Q2.Write nested and join queries for a university database.
- Q3.Write a procedure, a function and a trigger for a banking or library system.
- Q4.Design a normalised database for a payroll system from its ER diagram.
Stuck on this unit?
Message SBS on WhatsApp for help with Relational Database Management System Laboratory, or to ask about studying M.Sc IT at Synetic.
