0% found this document useful (0 votes)
22 views26 pages

DBMS Lab Manual

The document outlines a series of experiments involving SQL and NoSQL database operations, including creating tables, inserting records, and performing CRUD operations. It details the creation of triggers, stored procedures, and the use of aggregate functions, as well as the installation and basic usage of MongoDB. Each experiment includes specific SQL commands and expected outcomes, demonstrating various database functionalities.

Uploaded by

Manish Dey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views26 pages

DBMS Lab Manual

The document outlines a series of experiments involving SQL and NoSQL database operations, including creating tables, inserting records, and performing CRUD operations. It details the creation of triggers, stored procedures, and the use of aggregate functions, as well as the installation and basic usage of MongoDB. Each experiment includes specific SQL commands and expected outcomes, demonstrating various database functionalities.

Uploaded by

Manish Dey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

EXPERIMENT-1

Create a table called Employee & execute the following. Employee(EMPNO,ENAME,JOB,

MANAGER_NO, SAL, COMMISSION)

Write SQL Quires:

1. Create a user and grant all permissions to the user.

2. Insert the any three records in the employee table contains attributes

EMPNO,ENAME JOB, MANAGER_NO, SAL, COMMISSION and use rollback.

Check the result.

3. Add primary key constraint and not null constraint to the employee table.

4. Insert null values to the employee table and verify the result.

CREATE EMPLOYEE TABLE :

create table employee1(empno int primary key,ename varchar(50),job varchar(50),manager_no int,sal


int,commision int);

STEP-1 :

==Create a new user==

CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'password';

==Grant all privileges to the user (basic privileges like create, alter, delete, etc.)==
GRANT ALL PRIVILEGES ON DB_name.* TO 'new_user'@'localhost';

==Optionally, you may also grant the user the ability to create tables, views, and other objects==

GRANT CREATE, ALTER, DROP, INDEX, CREATE VIEW ON DB_name.* TO 'new_user'@'localhost';

STEP-2 :

BEFORE INSERT GIVE QUERY AS :

START TRANSACTION;

INSERT 3 ROWS IN EMPLOYEE TABLE :

INSERT INTO employee1 VALUES (1001, 'John Doe', 'Manager', NULL, 50000, 1000);

INSERT INTO employee1 VALUES (1002, 'Jane Smith', 'Clerk', 1001, 30000, 500);

INSERT INTO employee1 VALUES (1003, 'Sam Brown', 'Analyst', 1001, 45000, 700);

NOW ROLLBACK :

ROLLBACK;
YOU WILL OBSERVE THAT EMPLOYEE TABLE HAS EMPTY SET.

STEP-3 :

ADDING NOT NULL CONSTRAINT :

ALTER TABLE employee1 MODIFY COLUMN empno INT NOT NULL;

ALTER TABLE employee1 MODIFY COLUMN ename varchar(50) NOT NULL;

ALTER TABLE employee1 MODIFY COLUMN job VARCHAR(50) NOT NULL;

STEP-4 :

TRYING TO INSERT NULL VALUES:

INSERT INTO employee1 VALUES (1004, NULL, 'Manager', NULL, 55000, 1000);

IT WILL SHOW AN ERROR.

----------------------------------------------------------------------------

EXPERIMENT-2

Create a table called Employee that contain attributes EMPNO, ENAME, JOB, MGR, SAL
& execute the following.

1. Add a column commission with domain to the Employeetable.

2. Insert any five records into the table.

3. Update the column details of job

4. Rename the column of Employ table using alter command.

5. Delete the employee whose Empno is 105.

1.ALTER TABLE Employee

ADD COMMISSION DECIMAL(10, 2);

2. INSERT INTO employee1 VALUES

-> (101, 'John Doe', 'Manager', NULL, 5000.00, 1000.00),

-> (102, 'Jane Smith', 'Clerk', 101, 3000.00, 500.00),

-> (103, 'Robert Brown', 'Analyst', 101, 4000.00, 800.00),

-> (104, 'Michael Green', 'Clerk', 101, 3200.00, 400.00),

-> (105, 'Emily White', 'Analyst', 103, 4500.00, 900.00);

3. UPDATE Employee1

-> SET job = 'Senior Analyst'

-> WHERE job = 'Analyst';

4.ALTER TABLE Employee1

-> RENAME COLUMN ename TO emp_name;


5.delete from employee1 where empno=105;

AFTER ALL OPERATIONS THE TABLE WILL BE LIKE :

mysql> select * from employee1;

+-------+---------------+----------------+------------+------+------------+

| empno | emp_name | job | manager_no | sal | COMMISSION |

+-------+---------------+----------------+------------+------+------------+

| 101 | John Doe | Manager | NULL | 5000 | 1000.00 |

| 102 | Jane Smith | Clerk | 101 | 3000 | 500.00 |

| 103 | Robert Brown | Senior Analyst | 101 | 4000 | 800.00 |

| 104 | Michael Green | Clerk | 101 | 3200 | 400.00 |

+-------+---------------+----------------+------------+------+------------+

------------------------------------------------------------------------------------

EXPERIMENT-3

Queries using aggregate functions(COUNT,AVG,MIN,MAX,SUM), Groupby,

Orderby. Employee(E_id, E_name, Age, Salary)

1. Create Employee table containing all Records E_id, E_name, Age, Salary.

2. Count number of employee names from employeetable

3. Find the Maximum age from employee table.

4. Find the Minimum age from employeetable.


5. Find salaries of employee in Ascending Order.

6. Find grouped salaries of employees.

1.CREATE TABLE Employee (

empno INT PRIMARY KEY,

emp_name VARCHAR(100),

Age INT,

Salary DECIMAL(10, 2)

);

INSERT INTO Employee (empno, emp_name, Age, Salary) VALUES

(101, 'John Doe', 25, 5000.00),

(102, 'Jane Smith', 30, 6000.00),

(103, 'Robert Brown', 35, 7000.00),

(104, 'Michael Green', 28, 5500.00),

(105, 'Emily White', 40, 7500.00);

2.SELECT COUNT(emp_name) AS Employee_Count

-> FROM Employee;

3.SELECT MAX(Age) AS Max_Age

FROM Employee;
4.SELECT MIN(Age) AS Min_Age

FROM Employee;

5.SELECT emp_name, Salary

FROM Employee

ORDER BY Salary ASC;

6.SELECT Salary, COUNT(empno) AS Number_of_Employees

FROM Employee

GROUP BY Salary

ORDER BY Salary;

EXAMPLE FOR HAVING CLAUSE :

SELECT Salary, SUM(Salary) AS Total_Salary, COUNT(empno) AS Number_of_Employees

FROM Employee

GROUP BY Salary

HAVING SUM(Salary) > 5000;

----------------------------------------------------------------------------------------------------

EXPERIMENT-4

Create a row level trigger for the customers table that would fire for INSERT or UPDATE or DELETE
operations performed on the CUSTOMERS table. This

trigger will display the salary difference between the old & new Salary.
CUSTOMERS(ID,NAME,AGE,ADDRESS,SALARY).

1.CREATE CUSTOMERS TABLE :

create table customers(ID int,name varchar(20),age int,address varchar(50),salary int);

2.INSERT ATLEAST 5 ROWS

3.CREATE SALARY_CHNAGE_LOG TABLE :

CREATE TABLE salary_change_log (

id INT AUTO_INCREMENT PRIMARY KEY,

operation VARCHAR(10),

customer_id INT,

old_salary INT DEFAULT NULL,

new_salary INT DEFAULT NULL,

salary_difference INT,

timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

4.CREATE INSERT TRIGGER :

DELIMITER $$

CREATE TRIGGER salary_insert_trigger


AFTER INSERT ON customers

FOR EACH ROW

BEGIN

INSERT INTO salary_change_log (operation, customer_id, new_salary, salary_difference)

VALUES ('INSERT', NEW.ID, NEW.salary, NEW.salary);

END $$

DELIMITER ;

5.CREATE UPDATE TRIGGER :

DELIMITER $$

CREATE TRIGGER salary_update_trigger

AFTER UPDATE ON customers

FOR EACH ROW

BEGIN

IF OLD.salary != NEW.salary THEN

INSERT INTO salary_change_log (operation, customer_id, old_salary, new_salary, salary_difference)

VALUES ('UPDATE', NEW.ID, OLD.salary, NEW.salary, NEW.salary - OLD.salary);

END IF;

END $$

DELIMITER ;
6.CREATE DELETE TRIGGER :

DELIMITER $$

CREATE TRIGGER salary_delete_trigger

AFTER DELETE ON customers

FOR EACH ROW

BEGIN

INSERT INTO salary_change_log (operation, customer_id, old_salary, salary_difference)

VALUES ('DELETE', OLD.ID, OLD.salary, 0 - OLD.salary);

END $$

DELIMITER ;

7.NOW DO INSERT, UPDATE, DELETE OPERATIONS ON CUSTOMERS TABLE :

-- Insert a new customer (this will log the insert)

INSERT INTO customers (ID, name, age, address, salary) VALUES (6, 'David', 28, 'Kerala', 45000);

-- Update a customer's salary (this will log the update)

UPDATE customers SET salary = 55000 WHERE ID = 2;

-- Delete a customer (this will log the delete)

DELETE FROM customers WHERE ID = 3;


-- Check the log table to see the changes

SELECT * FROM salary_change_log;

------------------------------------------------------------------------------------------------

EXPERIMENT-5

Create cursor for Employee table & extract the values from the table. Declare

the variables ,Open the cursor & extract the values from the cursor. Close the

cursor. Employee(E_id, E_name, Age, Salary) .

1.CREATE EMPLOYEE TABLE :

CREATE TABLE Employee (

E_id INT PRIMARY KEY,

E_name VARCHAR(50),

Age INT,

Salary DECIMAL(10, 2)

);

2.INSERT ATLEAST 5 ROWS

3.CREATE A STORED PROCEDURE USING CURSOR :

DELIMITER $$
CREATE PROCEDURE fetch_employee_details()

BEGIN

-- Declare variables to hold the values fetched from the cursor

DECLARE done INT DEFAULT FALSE;

DECLARE v_e_id INT;

DECLARE v_e_name VARCHAR(50);

DECLARE v_age INT;

DECLARE v_salary DECIMAL(10, 2);

-- Declare the cursor to select data from Employee table

DECLARE employee_cursor CURSOR FOR

SELECT E_id, E_name, Age, Salary FROM Employee;

-- Declare a handler to set 'done' to TRUE when no more rows are found

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

-- Open the cursor

OPEN employee_cursor;

-- Loop through the cursor and fetch values

read_loop: LOOP

FETCH employee_cursor INTO v_e_id, v_e_name, v_age, v_salary;

-- Exit the loop if no more rows are found


IF done THEN

LEAVE read_loop;

END IF;

-- Process the values (e.g., print them using SELECT or insert into another table)

SELECT v_e_id AS E_id, v_e_name AS E_name, v_age AS Age, v_salary AS Salary;

END LOOP;

-- Close the cursor

CLOSE employee_cursor;

END $$

DELIMITER ;

4.CALL THE STORED PROCEDURE :

CALL fetch_employee_details();

--------------------------------------------------------------------------------------------------

EXPERIMENT-6

Write a PL/SQL block of code using parameterized Cursor, that will merge the

data available in the newly created table N_RollCall with the data available in

the table O_RollCall. If the data in the first table already exist in the second
table then that data should be skipped.

STEP-1 :

CREATE N_ROLLCALL TABLE AND INSERT SOME ROWS

CREATE TABLE N_RollCall (

roll_call_id INT NOT NULL,

student_id INT NOT NULL,

attendance_date DATE,

PRIMARY KEY (roll_call_id, student_id)

);

INSERT INTO N_RollCall (roll_call_id, student_id, attendance_date)

VALUES

(1, 1001, '2025-04-01'),

(2, 1002, '2025-04-01'),

(3, 1003, '2025-04-01'),

(4, 1004, '2025-04-01'),

(5, 1005, '2025-04-01');

STEP-2 :

CREATE O_ROLLCALL TABLE AND INSERT SOME VALUES


CREATE TABLE O_RollCall (

roll_call_id INT NOT NULL,

student_id INT NOT NULL,

attendance_date DATE,

PRIMARY KEY (roll_call_id, student_id)

);

INSERT INTO O_RollCall (roll_call_id, student_id, attendance_date)

-> VALUES

-> (1, 1001, '2025-04-01'),

-> (2, 1002, '2025-04-02'),

-> (3, 1003, '2025-04-01'),

-> (6, 1006, '2025-04-01');

STEP-3 :

CREATE STORED PROCEDURE TO MERGE BOTH THE TABLES

DELIMITER $$

CREATE PROCEDURE Merge_RollCall_Data()

BEGIN

-- Declare local variables


DECLARE v_roll_call_id INT;

DECLARE v_student_id INT;

DECLARE v_attendance_date DATE;

DECLARE done INT DEFAULT FALSE;

-- Declare the cursor to select records from N_RollCall

DECLARE cur CURSOR FOR

SELECT id, student_id, attendance_date

FROM N_RollCall;

-- Declare the handler to close the cursor when done

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

-- Open the cursor

OPEN cur;

-- Loop through the records in the cursor

read_loop: LOOP

-- Fetch the data from the cursor into the local variables

FETCH cur INTO v_roll_call_id, v_student_id, v_attendance_date;

-- Exit the loop if all rows have been processed

IF done THEN

LEAVE read_loop;

END IF;
-- Check if the record already exists in O_RollCall

IF NOT EXISTS (

SELECT 1

FROM O_RollCall

WHERE id = v_roll_call_id

AND student_id = v_student_id

) THEN

-- If the record does not exist, insert it into O_RollCall

INSERT INTO O_RollCall (id, student_id, attendance_date)

VALUES (v_roll_call_id, v_student_id, v_attendance_date);

END IF;

END LOOP;

-- Close the cursor

CLOSE cur;

-- Commit the transaction (optional if you're using autocommit)

COMMIT;

END $$

DELIMITER ;

STEP-4 :
CALL THAT PROCEDURE

CALL Merge_RollCall_Data();

FINAL OUTPUT WILL BE LIKE :

SELECT * FROM O_RollCall;

+--------------+------------+-----------------+

| roll_call_id | student_id | attendance_date |

+--------------+------------+-----------------+

| 1| 1001 | 2025-04-01 |

| 2| 1002 | 2025-04-02 |

| 3| 1003 | 2025-04-01 |

| 4| 1004 | 2025-04-01 |

| 5| 1005 | 2025-04-01 |

| 6| 1006 | 2025-04-01 |

+--------------+------------+-----------------+

6 rows in set (0.00 sec)

mysql> SELECT * FROM N_RollCall;

+--------------+------------+-----------------+

| roll_call_id | student_id | attendance_date |

+--------------+------------+-----------------+

| 1| 1001 | 2025-04-01 |

| 2| 1002 | 2025-04-01 |
| 3| 1003 | 2025-04-01 |

| 4| 1004 | 2025-04-01 |

| 5| 1005 | 2025-04-01 |

+--------------+------------+-----------------+

------------------------------------------------------------------------------------------

EXPERIMENT-7

Install an Open Source NoSQL Data base MangoDB & perform basic

CRUD(Create, Read, Update & Delete) operations. Execute MangoDB basic

Queries using CRUD operations.

1.DOWNLOAD MONGODB COMPASS AND INSTALL

https://www.mongodb.com/try/download/community

2.COPY THE MONGODB SERVER PATH AND PASTE IT IN THE ENVIRONMENT VARIABLES

3.MAKE COMMAND PROMPT AS AN ADMINSTRATOR(RIGHT CLICK ON COMMAND PROMPT AND SELECT


ADMINSTRATOR)

GIVE THIS COMMAND : net start MongoDB(IT STARTS THE SERVER FOR MONGODB)
KEEP OPEN THE COMMAND PROMPT WINDOW TILL YOU FINISHED YOUR WORK IN MONGO
COMPASS(DON'T CLOSE)

4.VERIFY WHETHER THE SERVER IS RUNNING OR NOT

COMMAND : netstat -an | findstr "27017"

5.NOW OPEN MONGODB COMPASS AND CONNECT TO THE LOCALHOST:27017

6.AFTER CONNECTED TO THE SERVER CLICK ON CREATE DATABSE AND CREATE YOUR OWN DATABASE
AND ADD THE COLLECTION NAME THEIR ITSELF.

7.NOW OPEN MONGODB SHELL AND START DOING CRUD OPERATIONS

TO DO THE OPERATIONS FIRST WE HAVE TO USE THAT DATABASE WHICH WE HAVE CREATED :

STEP-1 : use database_name

INPUT - >use eastpoint

OUTPUT - <switched to db eastpoint

STEP-2 : If you want to create collections in the database use this query

IN EASTPOINT DATABASE :

INPUT - >db.createCollection("users")
OUTPUT - <{ ok: 1 }

If you are not created any database as per the 6th point and try to do the 2nd step then it will
create "test" database automatically and uses the same.

IN TEST DATABSE :

INPUT - >db.createCollection("EPCET")

OUTPUT - <{ ok: 1 }

You can refresh the databases to see the changes everytime

STEP-3 : NOW START CRUD OPERATIONS

3.1. Create (Insert) Data

Now, let's insert data into the users collection.

db.users.insertOne({

name: "John Doe",

age: 30,

email: "[email protected]"

})

This command inserts a document with name, age, and email fields into the users collection.

If you want to insert multiple documents at once, use insertMany():


db.users.insertMany([

{ name: "Alice", age: 25, email: "[email protected]" },

{ name: "Bob", age: 35, email: "[email protected]" }

])

3.2. Read Data

You can read data from the collection using find().

Find all documents in the users collection:

db.users.find()

Find documents with a specific condition (e.g., age greater than 30):

db.users.find({ age: { $gt: 30 } })

Find one document:

db.users.findOne({ name: "John Doe" })

3.3. Update Data

To update data, use the updateOne() or updateMany() methods.

Update a single document:


db.users.updateOne(

{ name: "John Doe" },

{ $set: { age: 31 } }

This updates John Doe's age to 31.

Update multiple documents:

db.users.updateMany(

{ age: { $gt: 30 } },

{ $set: { status: "senior" } }

This adds a status field with value "senior" to all users with an age greater than 30.

3.4. Delete Data

To delete data, use deleteOne() or deleteMany().

Delete a single document:

db.users.deleteOne({ name: "Alice" })

Delete multiple documents:


db.users.deleteMany({ age: { $lt: 30 } })

3.5. Drop a Collection

If you want to delete an entire collection, use the drop() method:

db.users.drop()

This will drop the entire users collection.

3.6. Show Databases and Collections

To list all databases:

show dbs

To list all collections in the current database:

show collections

STEP-4: Exit MongoDB Shell(If you are using terminal not in compass)

To exit the MongoDB shell, simply type:

exit

Summary of Basic MongoDB CRUD Operations:


Create: insertOne(), insertMany()

Read: find(), findOne()

Update: updateOne(), updateMany()

Delete: deleteOne(), deleteMany()

Show: show dbs, show collections

Drop: drop()

These are some of the key query operators you can use in MongoDB to match documents based on
different conditions:

Comparison operators: $eq, $gt, $lt, $gte, $lte, $ne

Logical operators: $and, $or, $nor, $not

Element operators: $exists, $type

Array operators: $all, $elemMatch, $size


Evaluation operators: $regex, $text, $where

GeoSpatial operators: $geoWithin, $near

You might also like