0% found this document useful (0 votes)
3 views21 pages

Dbms Lab Manual

The document outlines a series of SQL operations involving the creation and manipulation of an Employee table, including user creation, data insertion, constraint application, and data retrieval using aggregate functions. It also describes the creation of triggers and cursors for managing customer data and merging records between two tables. The document includes specific SQL commands and their expected outputs for various operations.

Uploaded by

tanushree9663
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)
3 views21 pages

Dbms Lab Manual

The document outlines a series of SQL operations involving the creation and manipulation of an Employee table, including user creation, data insertion, constraint application, and data retrieval using aggregate functions. It also describes the creation of triggers and cursors for managing customer data and merging records between two tables. The document includes specific SQL commands and their expected outputs for various operations.

Uploaded by

tanushree9663
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/ 21

1) Create a table called Employee & execute the following.

Employee(EMPNO,ENAME,JOB, MANAGER_NO, SAL, COMMISSION)


1. Create a user and grant all permissions to theuser.
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 table Employee(Empno integer,ename varchar(20),job varchar(10),manager_no integer,sal


Decimal(10,2),commission decimal(10,2));

desc Employee;

Data Leng Precisi Scal Prima Nullab Defau Comme


Table Column Type th on e ry Key le lt nt
EMPLOY
EMPNO NUMBER 22 - 0 - - -
EE
VARCHA
ENAME 20 - - - - -
R2
VARCHA
JOB 10 - - - - -
R2
MANAGER_
NUMBER 22 - 0 - - -
NO
SAL NUMBER - 10 2 - - -
COMMISSIO
NUMBER - 10 2 - - -
N

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

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

CREATE USER books_admin IDENTIFIED BY MyPassword;

Grant all permissions to the user

GRANT ALL PRIVILEGES ON *.* TO 'new_user'@'localhost' WITH GRANT OPTION;

GRANT CONNECT TO books_admin;

GRANT CONNECT, RESOURCE, DBA TO books_admin;

GRANT CREATE SESSION GRANT ANY PRIVILEGE TO books_admin;

GRANT UNLIMITED TABLESPACE TO books_admin;

GRANT SELECT, INSERT, UPDATE, DELETE ON schema.books TO books_admin;

Flush privileges to apply changes


FLUSH PRIVILEGES;

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.

START TRANSACTION;

INSERT INTO Employee VALUES (1, 'John Doe', 'Manager', 0, 5000, 1000);

INSERT INTO Employee VALUES (2, 'Jane Smith', 'Developer', 1, 4000, NULL);

INSERT INTO Employee VALUES (3, 'Alice Johnson', 'Analyst', 1, 3500, 500);

Select * from Employee;

EMPNO ENAME JOB MANAGER_NO SAL COMMISSION


John
1 Manager 0 5000 1000
Doe
Jane
2 Developer 1 4000 -
Smith
Alice
3 Analyst 1 3500 500
Johnson

ROLLBACK;

Select * from Employee;

EMPNO ENAME JOB MANAGER_NO SAL COMMISSION

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

ALTER TABLE Employee ADD CONSTRAINT pk_employee_id PRIMARY KEY (empno);

Table altered

ALTER TABLE Employee MODIFY ename VARCHAR(20) NOT NULL;

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

INSERT INTO Employee (EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION) VALUES
(4, ‘shyam sharan’, NULL, 0, 5000, 1000);

Select * from Employee ;

EMPNO ENAME JOB MANAGER_NO SAL COMMISSION


John
1 Manager 0 5000 1000
Doe
Jane
2 Developer 1 4000 -
Smith
Alice
3 Analyst 1 3500 500
Johnson
shyam
4 - 0 5000 1000
sharan
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 Employee table.
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.

create table Employee(Empno integer,ename varchar(20),job varchar(10),manager_no integer,sal


number(10,2),commission number(10,2));

Table created

1.Add a column commission with domain to the Employee table.

ALTER TABLE Employee ADD commission decimal(10, 2) DEFAULT 0.00 NOT NULL;

Prima
Data Leng Precisi Sca ry Nulla Defa Comm
Table Column Type th on le Key ble ult ent
EMPLOYE NUMBE
EMPNO 22 - 0 - - -
E39 R
VARCH
ENAME 20 - - - - -
AR2
VARCH
JOB 10 - - - - -
AR2
MANAGER NUMBE
22 - 0 - - -
_NO R
NUMBE
SAL - 10 2 - - -
R

2.Insert any five records into the table

INSERT INTO Employee VALUES(101, 'Jay', 'Developer', 0, 5000, 1000);

INSERT INTO Employee VALUES (102, 'Ram', 'Manager', 1, 4000, NULL);

INSERT INTO Employee VALUES (103, 'Steven', 'Analyst', 1, 3500, 500);

INSERT INTO Employee VALUES (104, 'Rahim', 'Architect', 1, 4000, NULL);

INSERT INTO Employee VALUES (105, 'Robert', 'Leader', 1, 3500, 500);

Select * from Employee;


EMPNO ENAME JOB MANAGER_NO SAL COMMISSION
101 Jay Developer 0 5000 1000
102 Ram Manager 1 4000 -
103 Steven Analyst 1 3500 500
104 Rahim Architect 1 4000 -
105 Robert leader 1 3500 500

3.Update the column details of job

ALTER TABLE Employee MODIFY COLUMN job VARCHAR(100);

Table altered.

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

ALTER TABLE Employee RENAME COLUMN sal TO salary;

Table altered.

Select * from employee;

EMPNO ENAME JOB MANAGER_NO SALARY COMMISSION


101 Jay Developer 0 5000 1000
102 Ram Manager 1 4000 -
103 Steven Analyst 1 3500 500
104 Rahim Architect 1 4000 -
105 Robert leader 1 3500 500

6. Delete the employee whose Empno is 105.

DELETE FROM Employee WHERE Empno = 105;

1 row(s) deleted.

Select * from employee;

EMPNO ENAME JOB MANAGER_NO SALARY COMMISSION


101 Jay Developer 0 5000 1000
102 Ram Manager 1 4000 -
103 Steven Analyst 1 3500 500
104 Rahim Architect 1 4000 -
3) Queries using aggregate functions(COUNT,AVG,MIN,MAX,SUM),Group by,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.
Find grouped salaries of employees.

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

Create Table Employee(E_id int, E_name varchar(20), Age integer, Salary decimal(10,2));

Table created

desc Employee;

Lengt Precisio Scal Prima Nullab Defau Comme


Table Column Data Type h n e ry Key le lt nt
EMPLOY
E_ID NUMBER 22 - 0 - - -
EE
E_NAM VARCHA
20 - - - - -
E R2
AGE NUMBER 22 - 0 - - -
SALAR
NUMBER - 10 2 - - -
Y

Insert into Employee values(4, 'Jay', 28,25000);


Insert into Employee values(5, 'John', 38,35000);
Insert into Employee values(6, 'Jabbar', 24,65000);
Insert into Employee values(7, 'Somu', 48,29000);
Insert into Employee values(8, 'Smith', 25,24000);

Select * from Employee;

E_ID E_NAME AGE SALARY


4 Jay 25 26000
5 Kar 35 29000
6 Sta 36 36000
7 Uday 28 46000
8 x 45 20000
2. Count number of employee names from employeetable

SELECT COUNT(E_id) AS total_employee FROM Employee;


total_employee
5

3.Find the Maximum age from employee table.

SELECT Max(Age) AS max_age FROM Employee;


max_age
48

4.Find the Minimum age from employeetable

SELECT Min(Age) AS min_age FROM Employee;


min_age
24

5.Find salaries of employee in Ascending Order.

SELECT E_name, salary FROM Employee ORDER BY salary ASC;


Output
E_name Salary
Smith 24000
Jay 25000
Somu 29000
John 35000
Jabbar 65000

Find grouped salaries of employees

SELECT salary,count(*) FROM Employee GROUP BY salary;


Salary count(*)
24000 1
25000 1
29000 1
35000 1
65000 1
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 Customer Table:

Create table CUSTOMERS01(ID int primary key,NAME varchar(20) NOT NULL,AGE int,ADDRESS
varchar(30),SALARY decimal(10,2));

Table created.

2.Insert values into the table

Insert into CUSTOMERS01 values(12,'ram',25,'jp nagar bangalore',25000);

Insert into CUSTOMERS01 values(13,'rahim',35,'rr nagar mangalore',40000);

Insert into CUSTOMERS01 values(14,'robert',29,'sm nagar tumkur',35000);

ID NAME AGE ADDRESS SALARY


12 ram 25 jp nagar bangalore 26000
13 rahim 35 rr nagar mangalore 40000
15 john 30 abc street 30000

3. Creating trigger

CREATE OR REPLACE TRIGGER display_salary_changes1


BEFORE DELETE OR INSERT OR UPDATE ON CUSTOMERS01
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff decimal(10,2);
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
Trigger created.

4. Finding salary difference

INSERT INTO CUSTOMERS01 VALUES (15, 'john', 30, 'abc street', 30000);

Old salary: 25000


New salary: 30000
Salary difference: 5000
UPDATE CUSTOMERS01 SET SALARY = 26000 WHERE ID = 12;

1 row(s) inserted.
Old salary: 25000
New salary: 26000
Salary difference: 1000

1 row(s) updated.

DELETE FROM CUSTOMERS01 WHERE ID = 14;

1 row(s) deleted.
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)

CREATE TABLE Employee01 (


E_id INT PRIMARY KEY,
E_name VARCHAR(255),
Age INT,
Salary DECIMAL(10, 2)
);
Table created

insert into Employee01 values(8,'x',45,20000);


1 row(s) inserted.

-- Declare variables
DECLARE
E_id Employee.E_id%TYPE;
E_name Employee.E_name%TYPE;
Age Employee.Age%TYPE;
Salary Employee.Salary%TYPE;

-- Declare cursor
CURSOR employee_cursor IS
SELECT E_id, E_name, Age, Salary
FROM Employee01;

-- Open the cursor


BEGIN
OPEN employee_cursor;

-- Fetch data from cursor


LOOP
FETCH employee_cursor INTO E_id, E_name, Age, Salary;
EXIT WHEN employee_cursor%NOTFOUND;

-- Output or use the fetched values


DBMS_OUTPUT.PUT_LINE('Employee ID: ' || E_id || ', Name: ' || E_name || ', Age: ' || Age || ', Salary: ' ||
Salary);
END LOOP;

-- Close the cursor


CLOSE employee_cursor;
END;

OUTPUT:
Employee ID: 8, Name: x, Age: 45, Salary: 20000

Statement processed.
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.

CREATE TABLE N_RollCall7( id INT PRIMARY KEY, name VARCHAR(25), roll varchar(20));

Table created.

CREATE TABLE O_RollCall7( id INT PRIMARY KEY, name VARCHAR(25), roll varchar(20));

Table created.

insert into O_RollCall7 values(4,'d','m');


insert into O_RollCall7 values(3,'bcd','n');
insert into O_RollCall7 values(1,'bc','k');
insert into O_RollCall7 values(5,'bch','l');
insert into N_RollCall7 values(2,'b','o');
insert into N_RollCall7 values(5,'bch','u');
insert into N_RollCall7 values(1,'bc','k');
insert into N_RollCall7 values(6,'a','x');
select * from O_RollCall7;

ID NAME ROLL
4 D m
3 bcd n
5 bch l
2 B o
6 A x
Select * from N_RollCall7;

ID NAME ROLL
2 B o
5 Bch u
1 Bc k
6 A x
DECLARE
v_count NUMBER;
CURSOR c_new_rollcall IS
SELECT id, name, roll
FROM N_RollCall7;
BEGIN
FOR new_rec IN c_new_rollcall LOOP
-- Check if the record already exists in O_RollCall7
SELECT COUNT(*)
INTO v_count
FROM O_RollCall7
WHERE id = new_rec.id;

-- If record doesn't exist, insert it


IF v_count = 0 THEN
INSERT INTO O_RollCall7(id, name, roll)
VALUES (new_rec.id, new_rec.name, new_rec.roll);
DBMS_OUTPUT.PUT_LINE('Record inserted: ' || new_rec.id);
ELSE
DBMS_OUTPUT.PUT_LINE('Record skipped: ' || new_rec.id);
END IF;
END LOOP;
COMMIT;
END;
Record inserted: 2
Record skipped: 5
Record skipped: 1
Record inserted: 6

1 row(s) inserted.

select * from N_RollCall7;


ID NAME ROLL
2 b o
5 bch u
1 bc k
6 a x

select * from O_RollCall7;

ID NAME ROLL
4 d m
3 bcd n
1 bc k
5 bch l
2 b o
6 a x

delete from O_Rollcall7 where id=1;


1 row(s) deleted.
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.

How to Install and Configure MongoDB in Ubuntu?

MongoDB is a popular NoSQL database offering flexibility, scalability, and ease of use. Installing
and configuring MongoDB in Ubuntu is a straightforward process, but it requires careful attention to
detail to ensure a smooth setup.
In this guide, we’ll learn how to install and configure MongoDB in Ubuntu. We’ll walk you through
each step, from installation to configuration, enabling you to harness the power of MongoDB on
your Ubuntu system.
Let’s look at the requirements for installing MongoDB in Ubuntu.

Steps to Install and Configure MongoDB in Ubuntu

MongoDB can be installed on Ubuntu with the use of the following commands. These commands
are easy to run on the terminal and make the installation process handy. Follow the steps given
below to install MongoDB:
Step 1: First you need to update and upgrade your system repository to install MongoDB. Type the
following command in your terminal and then press Enter.

sudo apt update && sudo apt upgrade

Step 2: Now, install the MongoDB package using ‘apt‘. Type the following command and press
Enter.

sudo apt install -y mongodb


Step 3: Check the service status for MongoDB with the help of following command:

sudo systemctl status mongodb

systemctl verifies that MongoDB server is up and running.

Step 4: Now check if the installation process is done correctly and everything is working fine.
Gothrough the following command:

mongo --eval 'db.runCommand({ connectionStatus: 1 })'


the value “1” in ok field indicates that the server is working properly with no errors.

Step 5: MongoDB services can be started and stopped with the use of following commands: To
stoprunning the MongoDB service, use command :

sudo systemctl stop mongodb

MongoDB service has been stopped and can be checked by using the status command:

sudo systemctl status mongodb


As it can be seen that the service has stopped, to start the service we can use :
sudo systemctl start mongodb

Step 6: Accessing the MongoDB Shell

MongoDB provides a command-line interface called the MongoDB shell, which allows you to
interact with the database.
To access the MongoDB shell, simply type the following command in your terminal:

mongo

You are now connected to the MongoDB server, and you can start executing commands to
createdatabases, collections, and documents.

CRUD Operations:
1. Create (Insert)

To create or insert data into a MongoDB collection, you use the insertOne() or insertMany()
methods.

Insert a single document:

db.collection('yourCollection').insertOne({ key: value });

Insert multiple documents:


db.collection('yourCollection').insertMany([{ key1: value1 }, key2:
value2 },

// more documents
]);
Example:
db.users.insertOne({ name: "John Doe", age: 30, email: "[email protected]"});

output:
{
"acknowledged" : true,
"insertedId" : ObjectId("669f39fa348de2397e445c0b")
}
2. Read (Query)

To read or retrieve data from a MongoDB collection, you use the find() method.

Find all documents:

db.collection('yourCollection').find();

Find documents with a specific condition:


db.collection('yourCollection').find({ key: value });

Example:
db.users.find();

output:
{ "_id" : ObjectId("669f39fa348de2397e445c0b"), "name" : "John Doe", "age" : 30, "email" :
"[email protected]" }

3. Update

To update existing documents in a MongoDB collection, you use the updateOne()or updateMany()
methods.

Update a single document:

db.collection('yourCollection').updateOne({ key: value }, // filter{ $set: { newField: newValue } } // update


operation);

Example:
db.users.updateOne({ name: "John Doe" },{ $set: { age: 31 } });

output:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

4. Delete

To delete documents from a MongoDB collection, you use the deleteOne()or deleteMany()methods.

Delete a single document:

db.collection('yourCollection').deleteOne({ key: value });

Delete multiple documents:


db.collection('yourCollection').deleteMany({ key: value });

Example:

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

output:

{ "acknowledged" : true, "deletedCount" : 1 }

Insert multiple documents

Example:
db.users.insertMany([
{ name: "Jane Smith", age: 25, email: "[email protected]" },
{ name: "Michael Brown", age: 35, email: "[email protected]" }
]);

output:
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("669f3aae348de2397e445c0c"),
ObjectId("669f3aae348de2397e445c0d")
]
}

Find with projection (select specific fields):

Example:
db.users.find({}, { name: 1, age: 1 });

output:

{ "_id" : ObjectId("669f3aae348de2397e445c0c"), "name" : "Jane Smith", "age" : 25 }


{ "_id" : ObjectId("669f3aae348de2397e445c0d"), "name" : "Michael Brown", "age" : 35 }

Find with filter (query with conditions):

Example:
db.users.find({ age: { $gte: 30 } });

output:

{ "_id" : ObjectId("669f3aae348de2397e445c0d"), "name" : "Michael Brown", "age" : 35, "email" :


"[email protected]" }

Update multiple documents:

Example:
db.users.updateMany(
{ age: { $gte: 30 } },
{ $set: { status: "senior" } }
);

output:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

Delete multiple documents:

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

output:
{ "acknowledged" : true, "deletedCount" : 1 }

You might also like