0% found this document useful (0 votes)
12 views10 pages

DBMS Practicals

The document outlines a comprehensive guide to implementing a University Management System (UMS) database, detailing various SQL concepts and practical exercises. It covers topics such as database design, data types, SQL commands, constraints, data manipulation, joins, subqueries, triggers, transactions, user management, and optimization techniques. Each section includes practical examples and SQL commands to facilitate understanding and application of the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

DBMS Practicals

The document outlines a comprehensive guide to implementing a University Management System (UMS) database, detailing various SQL concepts and practical exercises. It covers topics such as database design, data types, SQL commands, constraints, data manipulation, joins, subqueries, triggers, transactions, user management, and optimization techniques. Each section includes practical examples and SQL commands to facilitate understanding and application of the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Database Scenario:

All practicals will be implemented on the University Management System (UMS)


database, consisting of tables:
Students(StudentID, Name, Age, Email, CourseID, DepartmentID)
Courses(CourseID, CourseName, Credits, DepartmentID)
Departments(DepartmentID, DepartmentName, HeadOfDepartment)
Professors(ProfessorID, Name, DepartmentID, Salary, Email)
Enrollments(EnrollmentID, StudentID, CourseID, Semester, Grade)

1. Introduction to Database Systems


Concepts: Database, DBMS vs. File System, ACID Properties, Types of
Databases
Practical: Creating an ER Diagram and Converting it to a Relational
Schema
A: Bank Management System
B: College Admission System
C: Online Shopping System
2. Database Models and Relational Database Concepts
Concepts: Hierarchical, Network, Relational, and Object-Oriented Models
Practical: Creating Tables and Defining Relationships
A: Create Students, Courses, and Departments tables
Create Departments Table
CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY AUTO_INCREMENT,
DepartmentName VARCHAR(100) NOT NULL,
HeadOfDepartment VARCHAR(100) NOT NULL
);

Create Courses Table


CREATE TABLE Courses (
CourseID INT PRIMARY KEY AUTO_INCREMENT,
CourseName VARCHAR(100) NOT NULL,
Credits INT NOT NULL CHECK (Credits > 0),
DepartmentID INT
);

Create Students Table


CREATE TABLE Students (
StudentID INT,
Name VARCHAR(100) NOT NULL,
Age INT CHECK (Age >= 18),
Email VARCHAR(100) UNIQUE NOT NULL,
CourseID INT,
DepartmentID INT
);

B: Define Primary and Foreign Key relationships


ALTER TABLE Departments
ADD PRIMARY KEY (dept_id);

ALTER TABLE Courses


ADD PRIMARY KEY (course_id),
ADD FOREIGN KEY (dept_id) REFERENCES Departments(dept_id);
ALTER TABLE Students
ADD PRIMARY KEY (student_id),
ADD FOREIGN KEY (course_id) REFERENCES Courses(course_id);

C: Insert initial data into tables


INSERT INTO Departments (dept_id, dept_name) VALUES
(1, 'Computer Science'),
(2, 'Mathematics'),
(3, 'Physics');

INSERT INTO Courses (course_id, course_name, dept_id) VALUES


(101, 'Data Structures', 1),
(102, 'Algorithms', 1),
(201, 'Linear Algebra', 2),
(202, 'Probability', 2),
(301, 'Quantum Mechanics', 3);

INSERT INTO Students (student_id, student_name, course_id) VALUES


(1001, 'Alice', 101),
(1002, 'Bob', 102),
(1003, 'Charlie', 201),
(1004, 'David', 202),
(1005, 'Eve', 301);

3. Data Types and Constraints in SQL


Concepts: Data Types (INT, VARCHAR, DATE, FLOAT), Constraints (NOT NULL,
UNIQUE)
Practical: Applying Data Types and Constraints
A: Define constraints on Student and Professor tables
CREATE TABLE Student (
StudentID INT PRIMARY KEY, -- Unique identifier for each student
Name VARCHAR(100) NOT NULL, -- Prevents null values
Age INT CHECK (Age > 18), -- Ensures students are older than 18
Email VARCHAR(100) UNIQUE NOT NULL, -- No duplicate emails
CourseID INT,
DepartmentID INT,
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID),
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);

CREATE TABLE Professor (


ProfessorID INT PRIMARY KEY, -- Unique identifier for each professor
Name VARCHAR(100) NOT NULL, -- Prevents null values
DepartmentID INT,
Salary DECIMAL(10,2) CHECK (Salary > 0), -- Ensures salary is positive
Email VARCHAR(100) UNIQUE NOT NULL, -- No duplicate emails
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);

B: Modify Courses table to add a DEFAULT constraint on credits


ALTER TABLE Courses
MODIFY COLUMN Credits INT DEFAULT 3; -- Sets default credit value to 3 if not
specified
C: Implement a CHECK constraint on Age (must be >18)
ALTER TABLE Student
ADD CONSTRAINT chk_age CHECK (Age > 18);

4. SQL Data Definition Language (DDL) Commands


Concepts: CREATE, ALTER, DROP, RENAME, TRUNCATE
Practical: Creating and Modifying Database Schema
A: Alter the Students table to add ‘DateOfBirth’ column
ALTER TABLE Students
ADD COLUMN DateOfBirth DATE;

B: Rename the Courses table to ‘CourseCatalog’


ALTER TABLE Courses
RENAME TO CourseCatalog;

C: Drop an unused table from the database


DROP TABLE UnusedTable;

5. SQL Data Manipulation Language (DML) Commands


Concepts: INSERT, UPDATE, DELETE, SELECT
Practical: Performing Insert, Update, and Delete Operations
A: Insert records into Students and Professors tables
INSERT INTO Students (StudentID, Name, Age, Email, CourseID, DepartmentID)
VALUES
(1001, 'Alice Johnson', 19, '[email protected]', 101, 1),
(1002, 'Bob Smith', 21, '[email protected]', 102, 1),
(1003, 'Charlie Brown', 20, '[email protected]', 201, 2);

INSERT INTO Professors (ProfessorID, Name, DepartmentID, Salary, Email)


VALUES
(2001, 'Dr. John Doe', 1, 75000.00, '[email protected]'),
(2002, 'Dr. Jane Smith', 2, 82000.00, '[email protected]');

B: Update course credits for all courses in a specific department


UPDATE Courses
SET Credits = 4
WHERE DepartmentID = 1;

C: Delete students who have not enrolled in any course


DELETE FROM Students
WHERE CourseID is NULL;

6. SQL Constraints and Integrity Rules


Concepts: PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, UNIQUE
Practical: Implementing Integrity Constraints
A: Enforce FOREIGN KEY constraint between Students and Courses
ALTER TABLE Students
ADD CONSTRAINT fk_course
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID);

B: Implement NOT NULL constraint on Student Names


ALTER TABLE Students
MODIFY COLUMN Name VARCHAR(100) NOT NULL;
C: Add a UNIQUE constraint on Email column in Professors table
ALTER TABLE Professors
ADD CONSTRAINT unique_email
UNIQUE (Email);

7. Sorting and Filtering Data in SQL


Concepts: DISTINCT, ORDER BY, LIKE, GROUP BY, HAVING
Practical: Retrieving and Sorting Data Efficiently
A: Retrieve distinct courses offered in the university
SELECT DISTINCT CourseName FROM Courses;

B: Group students by department and count them


SELECT DepartmentID, COUNT(*) AS StudentCount
FROM Students
GROUP BY DepartmentID;

C: Order professors by salary in descending order


SELECT Name, Salary FROM Professors
ORDER BY Salary DESC;

8. SQL Joins (Combining Multiple Tables)


Concepts: INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN
Practical: Performing Joins for Data Retrieval
A: INNER JOIN Students and Enrollments to display grades
SELECT Students.StudentID, Students.Name, Enrollments.CourseID,
Enrollments.Grade
FROM Students
INNER JOIN Enrollments ON Students.StudentID = Enrollments.StudentID;

B: LEFT JOIN Professors and Departments to show department names


SELECT Professors.ProfessorID, Professors.Name, Departments.DepartmentName
FROM Professors
LEFT JOIN Departments ON Professors.DepartmentID =
Departments.DepartmentID;

C: RIGHT JOIN Courses and Enrollments to list registered students


SELECT Courses.CourseID, Courses.CourseName, Enrollments.StudentID
FROM Courses
RIGHT JOIN Enrollments ON Courses.CourseID = Enrollments.CourseID; SELECT
Courses.CourseID, Courses.CourseName, Enrollments.StudentID
FROM Courses
RIGHT JOIN Enrollments ON Courses.CourseID = Enrollments.CourseID;

9. SQL Subqueries
Concepts: Simple Subqueries, Correlated Subqueries
Practical: Using Subqueries for Data Extraction
A: Find students who are enrolled in more than 3 courses
SELECT StudentID, Name, COUNT(CourseID) AS TotalCourses
FROM Students
JOIN Enrollments ON Students.StudentID = Enrollments.StudentID
GROUP BY StudentID, Name
HAVING COUNT(CourseID) > 3;

B: Retrieve courses with more than 50 enrollments


SELECT CourseID, CourseName, COUNT(StudentID) AS EnrollmentCount
FROM Courses
JOIN Enrollments ON Courses.CourseID = Enrollments.CourseID
GROUP BY CourseID, CourseName
HAVING COUNT(StudentID) > 50;

C: Display students who scored higher than the course average


SELECT e.StudentID, s.Name, e.CourseID, e.Grade
FROM Enrollments e
JOIN Students s ON e.StudentID = s.StudentID
WHERE e.Grade > (SELECT AVG(Grade) FROM Enrollments WHERE CourseID =
e.CourseID);

10 Aggregate Functions in SQL


.
Concepts: SUM, AVG, MIN, MAX, COUNT, ROUND
Practical: Using Aggregate Functions for Data Analysis
A: Find the average grade of students in each course
SELECT CourseID, AVG(Grade) AS AverageGrade
FROM Enrollments
GROUP BY CourseID;

B: Determine the highest and lowest professor salaries


SELECT MAX(Salary) AS HighestSalary, MIN(Salary) AS LowestSalary
FROM Professors;

C: Count the number of students in each department


SELECT DepartmentID, COUNT(StudentID) AS StudentCount
FROM Students
GROUP BY DepartmentID;

1. Views in SQL
Concepts: Creating, Using, and Dropping Views
Practical: Managing Views for Better Query Performance
A: Create a view of all students enrolled in Computer Science
CREATE VIEW ComputerScienceStudents AS
SELECT s.StudentID, s.Name, s.Email, s.CourseID, d.DepartmentName
FROM Students s
JOIN Departments d ON s.DepartmentID = d.DepartmentID
WHERE d.DepartmentName = 'Computer Science';

B: Drop an existing view of Enrolled Students


DROP VIEW EnrolledStudents;
C: Retrieve data from a View displaying top-performing students
CREATE VIEW TopPerformingStudents AS
SELECT s.StudentID, s.Name, e.CourseID, e.Grade
FROM Students s
JOIN Enrollments e ON s.StudentID = e.StudentID
WHERE e.Grade = 'A';

SELECT * FROM TopPerformingStudents;


2. SQL Triggers
Concepts: BEFORE, AFTER, ROW-Level, Statement-Level Triggers
Practical: Implementing SQL Triggers for Automation
A: Prevent negative salary updates for professors
DELIMITER $$

CREATE TRIGGER prevent_negative_salary


BEFORE UPDATE ON Professors
FOR EACH ROW
BEGIN
IF NEW.Salary < 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Salary cannot be negative';
END IF;
END $$

DELIMITER ;

B: Automatically update student GPA after a grade is entered


DELIMITER $$

CREATE TRIGGER update_student_gpa


AFTER INSERT ON Enrollments
FOR EACH ROW
BEGIN
UPDATE Students
SET GPA = (SELECT AVG(Grade) FROM Enrollments WHERE StudentID =
NEW.StudentID)
WHERE StudentID = NEW.StudentID;
END $$

DELIMITER ;

C: Log deleted student records in an audit table


CREATE TABLE StudentAudit (
AuditID INT PRIMARY KEY AUTO_INCREMENT,
StudentID INT,
Name VARCHAR(100),
Email VARCHAR(100),
DeletionDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DELIMITER $$

CREATE TRIGGER log_deleted_students


BEFORE DELETE ON Students
FOR EACH ROW
BEGIN
INSERT INTO StudentAudit (StudentID, Name, Email)
VALUES (OLD.StudentID, OLD.Name, OLD.Email);
END $$

DELIMITER ;
3. Transactions and ACID Properties
Concepts: COMMIT, ROLLBACK, SAVEPOINT
Practical: Handling Transactions in SQL
A: Implement a transaction for course enrollments
START TRANSACTION;

INSERT INTO Enrollments (EnrollmentID, StudentID, CourseID, Semester, Grade)


VALUES (1001, 2001, 301, 'Spring 2025', 'A');

-- If everything is correct, commit the transaction


COMMIT;

B: Use SAVEPOINT to partially rollback an enrolment


START TRANSACTION;

INSERT INTO Enrollments (EnrollmentID, StudentID, CourseID, Semester, Grade)


VALUES (1002, 2002, 302, 'Spring 2025', 'B');

SAVEPOINT sp1;

INSERT INTO Enrollments (EnrollmentID, StudentID, CourseID, Semester, Grade)


VALUES (1003, 2003, 303, 'Spring 2025', 'C');

-- If we want to undo only the second insert but keep the first:
ROLLBACK TO sp1;

-- Finalizing the first transaction


COMMIT;

C: Test ACID properties with fee payment


START TRANSACTION;

UPDATE Students SET Balance = Balance - 5000 WHERE StudentID = 2001;

INSERT INTO Payments (PaymentID, StudentID, Amount, PaymentDate)


VALUES (9001, 2001, 5000, NOW());

-- If both operations succeed, confirm the transaction:


COMMIT;

-- If an issue arises (e.g., negative balance), rollback:


ROLLBACK;

4. User Management and Access Control in SQL


Concepts: Creating Users, Granting and Revoking Permissions
Practical: Implementing User Management and Security
A: Create a user and assign privileges
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT SELECT, INSERT, UPDATE ON database_name.* TO 'new_user'@'localhost';

B: Grant read-only access to an external user


CREATE USER 'readonly_user'@'%' IDENTIFIED BY 'secure_password';
GRANT SELECT ON database_name.* TO 'readonly_user'@'%';
C: Revoke access from a specific user
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user_to_remove'@'host';
DROP USER 'user_to_remove'@'host';

5. Date and Time Functions in SQL


Concepts: CURRENT_DATE, CURRENT_TIME, TIMESTAMP, DATE_DIFF
Practical: Working with Date and Time in SQL
A: Retrieve the current system date
SELECT CURDATE();
SELECT NOW();

B: Calculate the duration between two dates


SELECT DATEDIFF('2025-05-19', '2025-04-01') AS duration_in_days;

C: List students who registered within the last 30 days


SELECT * FROM students
WHERE registration_date >= CURDATE() - INTERVAL 30 DAY;

6. String Functions in SQL


Concepts: CONCAT, LENGTH, UPPER, LOWER, SUBSTRING
Practical: Applying String Functions
A: Convert student names to uppercase
SELECT UPPER(student_name) AS uppercase_name FROM students;

B: Extract domain from email addresses


SELECT SUBSTRING_INDEX(email, '@', -1) AS domain FROM students;

C: Find the length of course names


SELECT coursename, LENGTH(coursename) AS name_length FROM courses;

7. Indexing in SQL for Optimization


Concepts: Primary, Secondary, Clustered, Non-Clustered Indexing
Practical: Creating and Managing Indexes
A: Create an index on Student Names for faster search
CREATE INDEX idx_student_name ON students(name);

B: Drop an index on Course table


DROP INDEX idx_course_name ON courses;

C: Use an index to speed up a query for top-performing students


CREATE INDEX idx_grade ON Enrollments(grade);
SELECT name, grade FROM Enrollments WHERE grade > 90 ORDER BY grade
DESC;

8. Query Optimization Techniques


Concepts: Execution Plan, Indexing, Query Rewriting
Practical: Optimizing Queries for Performance
A: Use EXPLAIN to analyze query execution time
EXPLAIN SELECT student_name, grade FROM students WHERE grade > 90 ORDER
BY grade DESC;
B: Optimize a slow-running query using indexing
CREATE INDEX idx_grade ON Enrollments(grade);
SELECT student_ID, grade FROM Enrollments WHERE grade > 90 ORDER BY grade
DESC;
C: Use EXISTS instead of IN for better performance
SELECT student_name FROM students
WHERE student_id IN (SELECT student_id FROM honors);

9. Concurrency Control in Databases


Concepts: Locks, Deadlocks, Isolation Levels
Practical: Implementing Concurrency Control
A: Implement locking in a multi-user database
LOCK TABLE students WRITE;
INSERT INTO students (StudentID, Name, Age, Email, CourseID, DepartmentID)
VALUES (101, 'John Doe', 21, '[email protected]', 5, 2);
UNLOCK TABLES;

B: Demonstrate Deadlock detection and resolution


START TRANSACTION;
UPDATE students SET Age = 22 WHERE StudentID = 101;
UPDATE courses SET Credits = 4 WHERE CourseID = 5;
COMMIT;

START TRANSACTION;
UPDATE courses SET Credits = 3 WHERE CourseID = 5;
UPDATE students SET Age = 23 WHERE StudentID = 101;
COMMIT;

SHOW ENGINE INNODB STATUS;

C: Use Isolation Levels for concurrent transactions


SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; -- Allows dirty reads
SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- Prevents dirty reads
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; -- Prevents non-
repeatable reads
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; -- Full isolation

START TRANSACTION;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT * FROM enrollments WHERE Semester = 'Spring 2025';
COMMIT;

10 Backup and Recovery in Traditional Databases


.
Concepts: Full, Incremental, Differential Backup, Recovery Techniques
Practical: Implementing Database Backup and Recovery Methods
A: Take a full database backup and restore it
mysqldump -u root -p --all-databases > full_backup.sql
mysqldump -u root -p UMS > ums_full_backup.sql

mysql -u root -p UMS < ums_full_backup.sql

B: Perform an incremental backup and apply recovery


SET GLOBAL log_bin = 'mysql-bin';
SHOW VARIABLES LIKE 'log_bin';

mysqlbinlog --read-from-remote-server -u root -p --raw mysql-bin.000001 >


incremental_backup.sql
mysql -u root -p UMS < incremental_backup.sql

C: Simulate a failure and recover using transaction logs


Simulating a Failure (Accidental Data Deletion):
DELETE FROM students WHERE StudentID = 101;

Recover Using Binary Logs (Point-in-Time Recovery):


mysqlbinlog --start-datetime="2025-05-19 13:00:00" --stop-datetime="2025-05-
19 13:50:00" mysql-bin.000001 | mysql -u root -p UMS

You might also like