CS5203 DATABASE MANAGEMENT SYSTEMS LAB RECORD

CHENNAI INSTITUTE OF TECHNOLOGY, CHENNAI

Section Content
Experiment No 1
Date
Aim To write MySQL statements to create a table and manipulate data using basic SQL commands.
Theory SQL (Structured Query Language) is used to create, modify, and manage relational databases. The CREATE TABLE command defines the schema structure, while INSERT adds new records. Commands like SELECT, UPDATE, and DELETE allow users to retrieve, modify, and remove specific records efficiently.
Query / Program
CREATE TABLE employee (
    empno INT,
    empname VARCHAR(255),
    DOB DATE,
    salary INT,
    designation VARCHAR(20)
);

INSERT INTO employee(empno, empname, DOB, salary, designation) 
VALUES (100, 'John', '1999-07-02', 50000, 'Manager');

INSERT INTO employee(empno, empname, DOB, salary, designation) 
VALUES (101, 'Greg', '1994-06-10', 15000, 'Clerk');

SELECT * FROM employee;

UPDATE employee SET salary = salary + 1000;

DELETE FROM employee WHERE empno = 100;
Output
EMPNO EMPNAME DOB SALARY DESIGNATION
100 John 1999-07-02 50000 Manager
101 Greg 1994-06-10 15000 Clerk
Table Updated.
1 row deleted.
Result Thus all the above basic SQL commands have been executed successfully and the output was verified.
Section Content
Experiment No 2.a
Date
Aim To create and manipulate a table using Data Definition Language (DDL) statements without using constraints.
Theory DDL statements define and alter the database schema. CREATE TABLE sets up the initial structure. ALTER TABLE modifies it by adding, modifying, or dropping columns. RENAME changes the table name, and DROP TABLE deletes the table and its structure from the database.
Query / Program
CREATE TABLE employee (
    empno INT,
    empname VARCHAR(25),
    dob DATE,
    salary INT,
    designation VARCHAR(20)
);

ALTER TABLE employee ADD department VARCHAR(50);

ALTER TABLE employee MODIFY COLUMN department VARCHAR(20);

ALTER TABLE employee DROP COLUMN department;

RENAME TABLE employee TO emp1;

DROP TABLE emp1;
Output
Table created.
Table altered (Column Added).
Table altered (Column Modified).
Table altered (Column Dropped).
Table renamed.
Table dropped.
Result Thus all the above DDL SQL commands without constraints have been executed successfully and the output was verified.
Section Content
Experiment No 2.b
Date
Aim To create a table using Data Definition Language (DDL) statements with constraints to enforce data integrity.
Theory Constraints are rules applied to columns to prevent invalid data entry. PRIMARY KEY ensures row uniqueness. NOT NULL prevents missing values. UNIQUE avoids duplicate entries in a column. CHECK enforces a specific condition, and DEFAULT provides a fallback value.
Query / Program
CREATE TABLE student (
    studentID INT PRIMARY KEY,
    sname VARCHAR(30) NOT NULL,
    department CHAR(5),
    sem INT,
    dob DATE,
    email_id VARCHAR(20) UNIQUE,
    college VARCHAR(20) DEFAULT 'MEC'
);

CREATE TABLE exam (
    examID INT,
    studentID INT REFERENCES student(studentID),
    department CHAR(5) NOT NULL,
    mark1 INT CHECK (mark1<=100 AND mark1>=0)
);

ALTER TABLE student ADD address VARCHAR(100);

ALTER TABLE student DROP address;

DROP TABLE exam;
Output
Table 'student' created with constraints.
Table 'exam' created with constraints.
Table 'student' altered.
Table 'exam' dropped.
Result Thus all the above DDL SQL commands with constraints have been executed successfully and the output was verified.
Section Content
Experiment No 3
Date
Aim To perform various manipulation operations using Data Manipulation Language (DML) statements.
Theory DML statements manage the actual data inside tables. INSERT adds new records. UPDATE changes existing data based on a WHERE condition to prevent overwriting all rows. DELETE removes specific rows based on a condition, keeping the table structure intact.
Query / Program
INSERT INTO student VALUES (101,'RUPESH','IT', 5,'1996-04-18','rupesh@gmail.com','MEC');
INSERT INTO student VALUES (102,'BALA','CSE',7,'1995-10-17','bala@gmail.com','IIT');

INSERT INTO exam(examid, studentid, department, mark1, mark2) 
VALUES (2222, 101, 'IT', 98, 87);

UPDATE student SET college='MEC' WHERE studentid=102;

UPDATE exam SET total=(mark1+mark2);

DELETE FROM exam WHERE examid=2222;
Output
1 row inserted.
1 row inserted.
1 row inserted.
1 row(s) updated.
1 row(s) updated.
1 row deleted.
Result Thus, all the above DML SQL commands have been executed successfully and the output was verified.
Section Content
Experiment No 4.a
Date
Aim To retrieve or fetch data using Data Query Projection (DQL) statements.
Theory Projection in SQL involves selecting specific columns from a table using the SELECT statement. You can retrieve all columns using *, pick specific columns by name, rename output columns using aliases (AS), perform basic arithmetic, and eliminate duplicate results using DISTINCT.
Query / Program
-- SELECT ALL COLUMNS
SELECT * FROM student;

-- SELECT MULTICOLUMN
SELECT sname, department, sem FROM student;

-- SELECTION WITH ALIAS COLUMN NAME
SELECT sname AS StudentName, department, sem FROM student;

-- SELECTION WITH ARITHMETIC OPERATION
SELECT sname, department, sem+1 "Next_Sem" FROM student;

-- DISTINCT RECORD SELECTION
SELECT DISTINCT college FROM student;
Output
SNAME DEPARTMENT SEM
RUPESH IT 5
BALA CSE 7
COLLEGE
MEC
IIT
Result Thus all the above Data Query Projection SQL commands have been executed successfully and the output was verified.
Section Content
Experiment No 4.b
Date
Aim To retrieve or fetch data using DQL Selection statements.
Theory Selection involves filtering rows using the WHERE clause. It restricts the data returned based on specific conditions. Operators used include relational operators (>, <), BETWEEN for ranges, IN for a set of values, and LIKE for pattern matching with wildcards (% or _).
Query / Program
-- SELECTION WITH WHERE CLAUSE
SELECT * FROM student WHERE college='MEC';

-- BETWEEN COMMAND
SELECT studentid, sname, department FROM student WHERE sem BETWEEN 5 AND 6;

-- IN COMMAND
SELECT studentid, sname FROM student WHERE department IN ('CSE','IT');

-- LIKE COMMAND
SELECT studentid, sname FROM student WHERE sname LIKE 'R%';
SELECT studentid, sname FROM student WHERE sname LIKE '%SH%';

-- RELATIONAL OPERATORS
SELECT studentid, sname FROM student WHERE studentid > 100 AND department='CSE';
Output
STUDENTID SNAME
101 RUPESH
108 RISHA
Result Thus all the above Data Query Selection SQL commands have been executed successfully and the output was verified.
Section Content
Experiment No 5
Date
Aim To perform various database operations using aggregate functions.
Theory Aggregate functions perform calculations on multiple rows to return a single summary value. Examples include COUNT, SUM, AVG, MAX, and MIN. The GROUP BY clause groups rows with the same values, while ORDER BY sorts the final result set in ascending or descending order.
Query / Program
-- ORDER BY
SELECT department, sem, sname FROM student ORDER BY department;
SELECT department, sem, sname FROM student ORDER BY department DESC, sem DESC;

-- AGGREGATE FUNCTIONS
SELECT COUNT(examid) AS STUDENTS_REGISTERED FROM exam;
SELECT MAX(total) AS HIGHEST_MARK FROM exam;
SELECT MIN(total) AS LOWEST_MARK FROM exam;

-- GROUP BY
SELECT department, SUM(total) AS SUM_DEPARTMENT FROM exam GROUP BY department;
SELECT department, AVG(total) AS AVERAGE FROM exam GROUP BY department;
Output
DEPARTMENT SUM_DEPARTMENT
IT 850
CSE 920

STUDENTS_REGISTERED
5
Result Thus all the above Aggregate function SQL commands have been executed successfully and the output was verified.
Section Content
Experiment No 6
Date
Aim To write MySQL statements to perform different join operations on a relation.
Theory Joins are used to combine rows from two or more tables based on a related column. INNER JOIN returns matching rows in both tables. LEFT JOIN returns all rows from the left table and matched rows from the right. RIGHT JOIN does the reverse. A Self Join joins a table to itself.
Query / Program
-- INNER JOIN
SELECT c.studentID, c.sname, p.company, p.salary 
FROM cseitstudent c INNER JOIN placement p ON c.studentID = p.studentID;

-- LEFT OUTER JOIN
SELECT c.sname, p.company 
FROM cseitstudent c LEFT OUTER JOIN placement p ON c.studentID = p.studentID;

-- RIGHT OUTER JOIN
SELECT c.sname, p.company 
FROM cseitstudent c RIGHT OUTER JOIN placement p ON c.studentID = p.studentID;

-- EQUI JOIN
SELECT * FROM cseitstudent, placement WHERE cseitstudent.studentID = placement.studentID;

-- SELF JOIN
SELECT e1.empname AS Employee, e2.empname AS Manager 
FROM employee1 e1, employee1 e2 WHERE e1.reportingid = e2.empid;
Output
STUDENTID SNAME COMPANY SALARY
104 nirmal infosys 25000
105 eshwar Wipro 22000
Result Thus all the above Joins SQL commands have been executed successfully and the output was verified.
Section Content
Experiment No 7
Date
Aim To write SQL statements to perform various set operations.
Theory Set operations combine the results of two or more queries into a single result set. UNION combines rows and removes duplicates. UNION ALL keeps all duplicates. INTERSECT returns only the rows present in both result sets. EXCEPT (or MINUS) returns rows from the first query that are not in the second.
Query / Program
-- UNION
SELECT studentid FROM student 
UNION 
SELECT studentid FROM exam;

-- UNION ALL
SELECT studentid FROM student 
UNION ALL 
SELECT studentid FROM exam;

-- INTERSECT
SELECT studentid FROM student 
INTERSECT 
SELECT studentid FROM exam;

-- EXCEPT (MINUS)
SELECT studentid FROM student 
EXCEPT 
SELECT studentid FROM exam;
Output
STUDENTID
101
102
104
106
108
Result Thus all the above SQL Set Operation queries have been executed successfully and the output was verified.
Section Content
Experiment No 8
Date
Aim To write nested queries using MySQL commands.
Theory A nested query (subquery) is a query placed inside another query. The inner query executes first, and its output is used by the outer query to filter data. Subqueries are commonly used with operators like =, IN, NOT IN, ALL, and EXISTS to handle complex conditional logic.
Query / Program
-- BASIC NESTED QUERY
SELECT * FROM employee WHERE designation = (SELECT designation FROM employee WHERE empname='RUPESH');

-- IN OPERATOR
SELECT studentID, sname FROM student WHERE studentID IN (SELECT studentID FROM placement);

-- NOT IN OPERATOR
SELECT studentID, sname FROM student WHERE studentID NOT IN (SELECT studentID FROM placement);

-- ALL OPERATOR
SELECT studentID, company, salary FROM placement WHERE salary > ALL(SELECT salary FROM placement WHERE company='infosys');

-- EXISTS OPERATOR
SELECT * FROM placement WHERE EXISTS (SELECT * FROM placement WHERE salary>20000);
Output
STUDENTID SNAME
104 nirmal
105 eshwar
Result Thus all the above SQL nested queries have been executed successfully and the output was verified.
Section Content
Experiment No 9
Date
Aim To write MySQL commands to perform view operations.
Theory A view is a virtual table that is based on the result set of an SQL query. It does not store data physically but retrieves it dynamically from base tables. Views help in hiding database complexity, securing sensitive data, and simplifying repetitive queries.
Query / Program
-- VIEW CREATION
CREATE VIEW studview AS (SELECT studentid, department, company FROM placement WHERE salary > 25000);

-- SELECT FROM VIEW
SELECT * FROM studview;

-- COMPLEX VIEW WITH JOIN
CREATE VIEW studetails AS (
    SELECT c.studentID, c.sname, c.sem, p.company, p.salary 
    FROM cseitstudent c INNER JOIN placement p ON c.studentID = p.studentID
);

-- QUERY THE VIEW
SELECT * FROM studetails;

-- DROP VIEW
DROP VIEW studetails;
Output
View created.
STUDENTID DEPARTMENT COMPANY
104 CSE Infosys
View dropped.
Result Thus all the above SQL View queries have been executed successfully and the output was verified.
Section Content
Experiment No 10.a
Date
Aim To write MySQL commands to perform Transaction Control Language (TCL) operations.
Theory TCL commands manage database transactions to ensure data consistency. START TRANSACTION begins the process. COMMIT permanently saves the changes made. ROLLBACK undoes uncommitted changes. SAVEPOINT creates a specific marker within a transaction to allow partial rollbacks.
Query / Program
SET autocommit=0;
START TRANSACTION;

INSERT INTO emp VALUES(106, 'John', 'manager', 25000);
COMMIT;

START TRANSACTION;
SAVEPOINT s1;
UPDATE emp SET salary=50000 WHERE emp_ID=104;

SAVEPOINT s2;
UPDATE emp SET salary=45000 WHERE emp_ID=103;

ROLLBACK TO s2;
ROLLBACK TO s1;
Output
Commit completed.
Savepoint created.
Rollback completed.
Result Thus all the above TCL commands have been executed successfully and the output was verified.
Section Content
Experiment No 10.b
Date
Aim To write MySQL commands to simulate Data Control Language (DCL) operations.
Theory DCL commands are used to manage database security and access control. GRANT gives a user specific permissions (like SELECT or ALL PRIVILEGES) on database objects. REVOKE removes those permissions from the user, ensuring only authorized personnel can manipulate data.
Query / Program
-- CREATE USER
CREATE USER student IDENTIFIED BY 'password123';

-- GRANT PRIVILEGES
GRANT ALL PRIVILEGES ON emp TO student;

-- REVOKE PRIVILEGES
REVOKE ALL PRIVILEGES FROM student;

-- DROP USER
DROP USER student;
Output
User created.
Grant succeeded.
Revoke succeeded.
User dropped.
Result Thus all the above DCL commands have been executed successfully and the output was verified.
Section Content
Experiment No 10.c
Date
Aim To write MySQL commands to simulate string, date, and math operations.
Theory SQL provides built-in functions for data manipulation. String functions (CONCAT, LENGTH, SUBSTRING) format text. Date functions (CURRENT_DATE, ADDDATE) manage time-based data. Math functions (ABS, POWER, SQRT) perform mathematical calculations directly within queries.
Query / Program
-- STRING FUNCTIONS
SELECT CHAR_LENGTH("SQL Tutorial");
SELECT CONCAT("SQL", "Tutorial");
SELECT SUBSTRING('Welcome to Tutorialspoint', 11);

-- DATE FUNCTIONS
SELECT ADDDATE("2024-03-17 09:00:00", INTERVAL 15 MINUTE);
SELECT CURRENT_DATE();
SELECT DAY("2024-03-17");

-- MATH FUNCTIONS
SELECT ABS(-243.5);
SELECT POWER(4, 2);
SELECT ROUND(345.156, 0);
SELECT SQRT(64);
Output
CHAR_LENGTH: 12
CONCAT: SQLTutorial

CURRENT_DATE: 2024-03-17

SQRT(64): 8
Result Thus all the above string, date and math function commands have been executed successfully and the output was verified.
Section Content
Experiment No 11
Date
Aim To write MySQL statements to simulate PL/SQL basic programs using loops.
Theory MySQL allows procedural programming constructs via Stored Procedures. These blocks of code can include variable declarations, conditional statements, and loops (WHILE, REPEAT). The DELIMITER must be changed before creating the procedure so the engine processes the entire block as one unit.
Query / Program
DELIMITER //
CREATE PROCEDURE WhileLoopExample()
BEGIN
    DECLARE n INT;
    DECLARE i INT;
    SET n = 5;
    SET i = 0;
    
    WHILE i <= n DO
        SELECT i AS Iteration;
        SET i = i + 1;
    END WHILE;
END//
DELIMITER ;

CALL WhileLoopExample();
Output
Iteration
0
1
2
3
4
5
Procedure successfully completed.
Result Thus all the above PL/SQL Programs have been executed successfully and the output was verified.
Section Content
Experiment No 12
Date
Aim To write MySQL statements to simulate functions and procedures.
Theory A Stored Function is a named block of code that returns a single value using the RETURN statement. A Stored Procedure is a block of code that executes tasks but does not directly return a value (though it can use OUT variables). Both enhance code reusability.
Query / Program
DELIMITER //
CREATE FUNCTION getSalary(s INT) RETURNS INT READS SQL DATA
BEGIN
    DECLARE Salary INT;
    SELECT sal INTO Salary FROM employee WHERE eid = s;
    RETURN Salary;
END//
DELIMITER ;

DELIMITER //
CREATE PROCEDURE PrintSalary()
BEGIN
    DECLARE sal INT;
    DECLARE eno INT;
    SET eno = 103;
    SET sal = getSalary(eno);
    SELECT CONCAT('Salary: ', sal) AS Result;
END//
DELIMITER ;

CALL PrintSalary();
Output
Result
Salary: 18000
Procedure successfully completed.
Result Thus all the above Functions and Procedures have been executed successfully and the output was verified.
Section Content
Experiment No 13.a
Date
Aim To write MySQL statements to simulate the use of Cursors.
Theory A Cursor allows row-by-row processing of a query result set inside a stored procedure. The steps involve declaring the cursor, opening it, fetching the rows sequentially into variables within a loop, handling the 'Not Found' condition to exit the loop, and finally closing the cursor.
Query / Program
DELIMITER //
CREATE PROCEDURE process_table_data()
BEGIN
    DECLARE done BOOLEAN DEFAULT FALSE;
    DECLARE emp_id INT;
    
    DECLARE cursor_name CURSOR FOR SELECT eid FROM employee;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    
    OPEN cursor_name;
    read_loop: LOOP
        FETCH cursor_name INTO emp_id;
        IF done THEN
            LEAVE read_loop;
        END IF;
    END LOOP;
    CLOSE cursor_name;
END//
DELIMITER ;

CALL process_table_data();
Output
Cursor executed successfully.
Procedure successfully completed.
Result Thus all the above Cursor statements have been executed successfully and the output was verified.
Section Content
Experiment No 13.b
Date
Aim To write MySQL statements to simulate Database Triggers.
Theory A Trigger is a stored program that is automatically invoked by the database engine when a specified event (like INSERT, UPDATE, or DELETE) occurs on a table. It is used to maintain audit logs, enforce business rules, and validate data dynamically using NEW and OLD row values.
Query / Program
CREATE TABLE emplog (
    eid INT,
    ename VARCHAR(10),
    idate DATE,
    nsal DECIMAL(10, 2)
);

DELIMITER //
CREATE TRIGGER logsal AFTER UPDATE ON employ
FOR EACH ROW
BEGIN
    INSERT INTO emplog (eid, ename, idate, nsal) 
    VALUES (NEW.eid, NEW.ename, CURDATE(), NEW.salary);
END//
DELIMITER ;

UPDATE employ SET salary = salary + 2500.0 WHERE expe > 3 AND expe < 7;

SELECT * FROM emplog;
Output
Trigger created.
3 rows updated.
EID ENAME IDATE NSAL
101 Rahul 2024-03-17 35000.00
102 Anita 2024-03-17 42000.00
105 Vikram 2024-03-17 38000.00
Result Thus all the above Trigger statements have been executed successfully and the output was verified.