Dbms Draft3
Dbms Draft3
Dbms Draft3
1) Consider the relation employee (emp_id,e_name,salary ,Date of Joining,Dapt_no,Designation) perform basic operations.
Answer:
e_name VARCHAR(50),
Date_of_Joining DATE,
Dept_no INT,
Designation VARCHAR(50)
);
VALUES
3. Create a view "emp_vl" of the "employee" table with only "emp_id," "e_name," and "Dept_no" attributes:
FROM employee;
UPDATE emp_vl
WHERE emp_id = 2;
8. Create a user-defined index on any column. Let's create an index on the "e_name" column:
Answer:
1. Display employees whose name contains the letter 'e':
SELECT * FROM employee WHERE e_name LIKE '%e%';
2. Display different types of designations:
SELECT DISTINCT Designation FROM employee;
3. Display the name and salary of employees whose location is Mumbai:
SELECT e_name, salary FROM employee WHERE Dept_no = 'Mumbai';
4. Display the name and department of employees working in the Manager or Marketing department:
SELECT e_name, Dept_no FROM employee WHERE Designation = ‘manager’ OR Designation=’marketing’;
5. Display the department name whose employees are more than one:
SELECT Dept_no
FROM employee
GROUP BY Dept_no
HAVING COUNT(*) > 1;
6. Rename the employee table as emp1:
ALTER TABLE employee RENAME TO emp1;
7. Add a new column "city" to the employee table:
ALTER TABLE employee ADD city VARCHAR(255);
3)Consider the relation employee(emp_id,e_name,salary ,Date of Joining,Dept_no,Designation) perform basic operations.
Answer:
CREATE TABLE employee (
e_name VARCHAR(50),
Date_of_Joining DATE,
Dept_no INT,
Designation VARCHAR(50)
);
FROM employee
GROUP BY Dept_no
LIMIT 1;
2. Display the name, designation, and department number of employees whose names start with either 'A' or 'P':
FROM employee
3. Display the maximum salary from department 2 and the minimum salary from department 4:
FROM employee
4. Display employee data where the salary is less than the average salary from department 3:
SELECT *
FROM employee
WHERE salary < (SELECT AVG(salary) FROM employee WHERE Dept_no = 3);
SELECT *
FROM employee
ORDERS BY Date_of_Joining
LIMIT 1;
SELECT *
FROM employee
LIMIT 1;
6. Display the name and department number of employees who are managers or market analysts using predicates:
FROM employee
SELECT *
FROM employee
WHERE MONTH(Date_of_Joining) = 8;
SELECT *
FROM employee
FROM employee
GROUP BY Dept_no;
4)Consider two tables Customer(c_id, c_name , email , city , pincode) and Orders(Order_id , date , amount , cust_id).
1. Create both the tables with primary key and foreign key constraints.
2. insert 10 records each.
3. Find all Orderss placed by customers with cust_id2
4. Find list of customers who placed their Orders and details of Orders
5. List of customers who haven’t placed Orders
6. List all Orderss and append to customer table
7. Display all records
8. Display customer that are from same city
Answer:
1. Create the tables with primary key and foreign key constraints:
-- Create the Customer table:
CREATE TABLE Customer (
c_id INT PRIMARY KEY,
c_name VARCHAR(50),
email VARCHAR(50),
city VARCHAR(50),
pincode INT
);
Answer:
1. Create both tables with primary keys:
-- Create the Borrower table
CREATE TABLE Borrower (
RollNo INT PRIMARY KEY,
Name VARCHAR(50),
DateofIssue DATE,
NameofBook VARCHAR(50),
Status VARCHAR(10)
);
Answer:
Data Definition Language (DDL) Operations:
1. Create Table:
CREATE TABLE student (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
marks INT,
class VARCHAR(10)
);
2. Alter Table:
ALTER TABLE student
ADD dob DATE;
3. Drop Table:
DROP TABLE student;
Answer:
CREATE TABLE jobs (
job_id VARCHAR(10) PRIMARY KEY,
job_title VARCHAR(50),
min_sal DECIMAL(10, 2),
max_sal DECIMAL(10, 2)
);
1.Insert some sample data into the "jobs" table
INSERT INTO jobs (job_id, job_title, min_sal, max_sal)
VALUES
('J001', 'Manager', 50000.00, 80000.00),
('J002', 'Engineer', 40000.00, 70000.00),
('J003', 'Analyst', 35000.00, 60000.00),
('J004', 'Designer', 38000.00, 65000.00),
-- Add more job records here
('J005', 'Supervisor', 45000.00, 75000.00);
-- This unique constraint ensures that employee_id does not contain duplicate values
CREATE UNIQUE INDEX idx_employee_id ON job_history (employee_id);
8) For the given relation schema: employee (employee-name, street, city)
works (employee-name, company-name, salary)
company (company-name, city)
manages (employee-name, manager-name)
Give an expression in for each of the following queries:
a) Find the names, street address, and cities of residence for all employees who work for same company and earn
more than $10,000.
b) Find the names of all employees in the database who live in the same cities as the companies for which they work.
c) Find the names of all employees who earn more than the average salary of all employees of their company. Assume
that all people work for at most one company.
Answer:
a) To find the names, street address, and cities of residence for all employees who work for the same company and
earn more than $10,000, you can use a query like this:
SELECT e.employee-name, e.street, e.city
FROM employee e
JOIN works w ON e.employee-name = w.employee-name
WHERE w.salary > 10000
AND w.company-name IN (
SELECT company-name
FROM works
GROUP BY company-name
HAVING COUNT(DISTINCT employee-name) > 1
);
b) To find the names of all employees in the database who live in the same cities as the companies for which they
work, you can use the following query:
SELECT DISTINCT e.employee-name
FROM employee e
JOIN works w ON e.employee-name = w.employee-name
JOIN company c ON w.company-name = c.company-name
WHERE e.city = c.city;
c) To find the names of all employees who earn more than the average salary of all employees of their company, you
can use this query:
SELECT e.employee-name
FROM employee e
JOIN works w ON e.employee-name = w.employee-name
WHERE w.salary > (
SELECT AVG(salary)
FROM works
WHERE company-name = w.company-name
);
9) For the given relation schema: employee (employee-name, street, city)
works (employee-name, company-name, salary)
company (company-name, city)
manages (employee-name, manager-name)
Give an expression in for each of the following queries:
a) Find the name of the company that has the smallest payroll.
b) Find the names of all employees in the database who live in the same cities and on the same streets as do their
managers.
Answers:
a) To find the name of the company with the smallest payroll, you can use the following query:
SELECT company_name
FROM works
GROUP BY company_name
HAVING SUM(salary) = (SELECT MIN(total_salary)
FROM (SELECT company_name, SUM(salary) AS total_salary
FROM works
GROUP BY company_name) AS payroll);
b) To find the names of employees who live in the same cities and on the same streets as their managers, you can use
the following query:
SELECT e.employee_name
FROM employee e
INNER JOIN manages m ON e.employee_name = m.employee_name
WHERE e.street = (SELECT street FROM employee WHERE employee_name = m.manager_name)
AND e.city = (SELECT city FROM employee WHERE employee_name = m.manager_name);
10) Implement CRUD operations. SAVE method. Use following Collection. Perform Map Reduce to count quantity of each
item.
Answer
Step 1: Create a MongoDB Database and Collection
use my_store
db.createCollection("items")
Step 2: Insert Sample Data
db.items.insertMany([
{ "Item ID": 1, "Item quantity": 10, "price": 50, "brand": "Brand A", "discount": 5 },
{ "Item ID": 2, "Item quantity": 5, "price": 30, "brand": "Brand B", "discount": 10 },
{ "Item ID": 3, "Item quantity": 8, "price": 40, "brand": "Brand A", "discount": 3 },
{ "Item ID": 4, "Item quantity": 12, "price": 60, "brand": "Brand C", "discount": 8 },
{ "Item ID": 5, "Item quantity": 6, "price": 45, "brand": "Brand B", "discount": 5 }
])
Step 3: Perform the Requested Operations:
a) Display the count of items brand-wise:
db.items.mapReduce(mapFunction, reduceFunction, {
out: "brandItemCount",
});
// To retrieve the result
db.brandItemCount.find();
//Aggregate Equivalent
db.items.aggregate([
{
$group: {
_id: "$brand",
count: { $sum: 1 }
}
}
])
Answer:
Step 1: Create a MongoDB Database and Collection
use my_store
db.createCollection("items")
Step 2: Insert Sample Data
db.items.insertMany([
{ "Item ID": 1, "Item quantity": 10, "price": 50, "brand": "Brand A", "discount": 5 },
{ "Item ID": 2, "Item quantity": 5, "price": 30, "brand": "Brand B", "discount": 10 },
{ "Item ID": 3, "Item quantity": 8, "price": 40, "brand": "Brand A", "discount": 3 },
{ "Item ID": 4, "Item quantity": 12, "price": 60, "brand": "Brand C", "discount": 8 },
{ "Item ID": 5, "Item quantity": 6, "price": 45, "brand": "Brand B", "discount": 5 }
])
Step 3: Perform the Requested Operations
a) Display the count of items brand-wise:
db.items.aggregate([
{
$group: {
_id: "$brand",
count: { $sum: 1 }
}
}
])
Question 12
1. *Install and Set Up MongoDB*: If you haven't already, install and set up MongoDB on your system.
2. *Use MongoDB Shell or a MongoDB Driver for Your Preferred Programming Language*: You can use
MongoDB Shell directly or a MongoDB driver for your preferred programming language (e.g., PyMongo
for Python).
Here's a step-by-step guide using MongoDB Shell to create and interact with the collection and perform the
requested operations:
*Step 1: Create a Database and a Collection*
Start the MongoDB shell by running mongo in your terminal. Then, create a new database and a collection
for your items:
use mystore
db.createCollection("items")
db.items.insertMany([
{
"Item ID": 1,
"Item quantity": 10,
"price": 50,
"brand": "Brand A",
"discount": 5
},
{
"Item ID": 2,
"Item quantity": 5,
"price": 30,
"brand": "Brand B",
"discount": 10
},
{
"Item ID": 3,
"Item quantity": 8,
"price": 40,
"brand": "Brand A",
"discount": 3
},
{
"Item ID": 4,
"Item quantity": 12,
"price": 60,
"brand": "Brand C",
"discount": 8
},
{
"Item ID": 5,
"Item quantity": 6,
"price": 45,
"brand": "Brand B",
"discount": 5
}
])
db.items.aggregate([
{ $group: { _id: "$brand", count: { $sum: 1 } } }
])
Answer:
*Step 1: Create a MongoDB Database and Collection*
use school
db.createCollection("students")
db.students.insertMany([
{ roll_no: 1, name: "Alice", marks: 95, class: "10A" },
{ roll_no: 2, name: "Bob", marks: 85, class: "10A" },
{ roll_no: 3, name: "Charlie", marks: 92, class: "10B" },
{ roll_no: 4, name: "David", marks: 78, class: "10B" },
{ roll_no: 5, name: "Eve", marks: 88, class: "10A" }
])
db.students.mapReduce(
mapFunction,
reduceFunction,
{ out: "total_marks" }
)
This map function emits the roll number as the key and the marks as the value. The reduce function
calculates the total marks for each student.
//Aggregate Equivalent
db.students.aggregate([
{
$group: {
_id: "$roll_no",
total_marks: { $sum: "$marks" }
}
}
]);
You can retrieve the results of the Map-Reduce operation from the "total_marks" collection:
db.total_marks.find()
The output will show the student's roll number and their total marks:
json
{ "_id" : 1, "value" : 95 }
{ "_id" : 2, "value" : 85 }
{ "_id" : 3, "value" : 92 }
{ "_id" : 4, "value" : 78 }
{ "_id" : 5, "value" : 88 }
14) Implement Map reduces operation for displaying persons with same profession.
Answer:
*Step 1: Create a MongoDB Database and Collection*
Start by creating a MongoDB database and a collection for your "person" records if you haven't already.
use mydb
db.createCollection("persons")
Insert some sample data into the "persons" collection. Here's an example with a few person records:
db.persons.insertMany([
{ person_id: 1, name: "Alice", addr: "123 Main St", profession: "Doctor" },
{ person_id: 2, name: "Bob", addr: "456 Elm St", profession: "Engineer" },
{ person_id: 3, name: "Charlie", addr: "789 Oak St", profession: "Doctor" },
{ person_id: 4, name: "David", addr: "101 Pine St", profession: "Lawyer" },
{ person_id: 5, name: "Eve", addr: "202 Birch St", profession: "Engineer" }
])
db.persons.mapReduce(
mapFunction,
reduceFunction,
{ out: "same_profession", finalize: finalizeFunction }
)
//Aggregate version
db.persons.aggregate([
{
$group:{
_id:"$profession",
names:{$addToSet:"$name"}
}
}
])
This map function emits the profession as the key and an array containing person information as the value.
The reduce function combines the information of persons with the same profession into a single array.
json
{ "_id" : "Doctor", "value" : { "persons" : [ { "name" : "Alice", "person_id" : 1 }, { "name" : "Charlie",
"person_id" : 3 } ] } }
{ "_id" : "Engineer", "value" : { "persons" : [ { "name" : "Bob", "person_id" : 2 }, { "name" : "Eve",
"person_id" : 5 } ] } }
{ "_id" : "Lawyer", "value" : { "persons" : [ { "name" : "David", "person_id" : 4 } ] } }
This demonstrates a basic Map-Reduce operation in MongoDB to group persons by their professions and
display individuals with the same profession. You can further customize the map and reduce functions to suit
your specific requirments
15) Perform CRUD operation in mongo db –
1.Create Collection.
Question 15
To perform CRUD (Create, Read, Update, Delete) operations in MongoDB for the "person" collection, you can follow these steps:
Create a MongoDB database (if it doesn't already exist) and a collection for your "person" records.
use mydb
db.createCollection("person")
Insert data into the "person" collection. Here's an example with a few person records:
db.person.insertMany([
])
You can read data from the "person" collection using queries. For example:
db.person.find()
- To find a person by their name (e.g., "Alice"):
To update data in the collection, you can use the updateOne or updateMany methods. For example, to update the profession of a
person with "person_id" 2:
db.person.updateOne(
{ "person_id": 2 },
You can delete data from the collection using the deleteOne or deleteMany methods. For example, to delete a person by their
name (e.g., "David"):
Answer:
use company
db.createCollection("employees")
db.employees.insertMany([
{ emp_id: 1, e_name: "Alice", salary: 60000, Date_of_Joining: ISODate("2016-06-01"), Dept_no: 101,
Designation: "Sales Executive" },
{ emp_id: 2, e_name: "Bob", salary: 75000, Date_of_Joining: ISODate("2017-05-15"), Dept_no: 101,
Designation: "Sales Manager" },
{ emp_id: 3, e_name: "Charlie", salary: 55000, Date_of_Joining: ISODate("2016-06-10"), Dept_no: 102,
Designation: "Production Operator" },
{ emp_id: 4, e_name: "David", salary: 80000, Date_of_Joining: ISODate("2018-04-20"), Dept_no: 103,
Designation: "HR Manager" },
{ emp_id: 5, e_name: "Eve", salary: 70000, Date_of_Joining: ISODate("2016-06-25"), Dept_no: 102,
Designation: "Production Supervisor" }
])
- Delete an employee:
b) Display the average salary of employees in the Sales department (Dept_no 101):
db.employees.aggregate([
{
$match: { Dept_no: 101 }
},
{
$group: {
_id: "$Dept_no",
average_salary: { $avg: "$salary" }
}
}
])
d) Display the maximum salary given to employees in the Production department (Dept_no 102):
db.employees.aggregate([
{
$sort: { Dept_no: 1, Date_of_Joining: 1 }
},
{
$group: {
_id: "$Dept_no",
first_employee: { $first: "$$ROOT" },
last_employee: { $last: "$$ROOT" }
}
}
])
//$$ROOT : references all records within the current context, in this case in each $group
instance
These queries will provide you with the desired results based on the specified criteria. You can run these
queries in the MongoDB shell to obtain the output.
17) Consider student ( roll_no, name ,marks, class) table. Perform add update and delete operation on same table
through java program. Write menu driven program.
Question 17
//needs mongodb-driver-core-4.11.0.jar from maven repo
create a new file named “.classpath” in same folder as the program
add:
<classpath>
<classpathentry kind="lib" path="path_to_jar "/>
</classpath>
And save
Make sure you have already created a database called “store” with a collection “students”
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Scanner;
while (true) {
System.out.println("Student Management System");
System.out.println("1. Add Student");
System.out.println("2. Update Student");
System.out.println("3. Delete Student");
System.out.println("4. Exit");
System.out.print("Select an option: ");
int option = scanner.nextInt();
switch (option) {
case 1:
addStudent(collection, scanner);
break;
case 2:
updateStudent(collection, scanner);
break;
case 3:
deleteStudent(collection, scanner);
break;
case 4:
System.out.println("Exiting the program.");
scanner.close();
return;
default:
System.out.println("Invalid option. Please choose a valid option.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
collection.insertOne(document);
System.out.println("Student added successfully.");
}
collection.updateOne(filter, update);
System.out.println("Student updated successfully.");
}
Question 18
In PL/, you can create a stored procedure named proc_Grade to categorize students based on their marks in
an examination. Here's a PL/ block that defines the procedure and uses it to categorize students from the
Stud_Marks table and insert the results into the Result table:
In this PL/ block, we first create the proc_Grade procedure. Inside the procedure, we use a cursor to iterate
over the records in the Stud_Marks table. For each student, we determine their category based on their total
marks and then insert the result into the Result table. The CASE statement is used to categorize the students
according to the provided criteria.
Finally, we execute the proc_Grade procedure to categorize the students and insert the results into the Result
table.
Please ensure that you have the necessary tables (Stud_Marks and Result) and that you have the appropriate
privileges to create and execute procedures in your Oracle database. Adjust the table and column names as
needed to match your actual database schema.
19) Write a database trigger on customer( cust_id, c_name, addr) table. The System should keep track of the records
that are being updated or deleted. The old value of updated or deleted records should be added in cust_Audit table.
*Question 19*
In this example:
1. We first create a table called "cust_Audit" to store the old values of updated or deleted records.
2. We create a trigger named "customer_audit_trigger" on the "customer" table. This trigger fires after a row
is deleted or updated.
3. In the trigger body, we check whether the trigger action is a DELETE or an UPDATE.
4. For deleted records, we set the action_type to 'DELETE.' For updated records, we set it to 'UPDATE.'
5. We then insert the old values of the record (from the :OLD pseudo-record) along with the action type and
the current timestamp into the "cust_Audit" table.
With this trigger in place, the "cust_Audit" table will keep a record of deleted and updated records from the
"customer" table, including the old values and the type of action (delete or update).
20) Implement a database trigger on client_master( c_id, c_name, acc_no) table. The System should keep
track of the records that are being updated or inserted. The old value of updated or deleted records should be
added in client_Audit table.
1. Create the client_Audit table to store the old values of the records. The structure of the client_Audit table
should match that of the client_master table, and it should include additional columns for tracking changes
such as timestamp and the type of operation.
2. Create a database trigger on the client_master table that captures the old values of records and inserts
them into the client_Audit table. The trigger can fire on both update and delete operations.
Here's an example of a trigger that captures the old values and logs them:
This trigger, named client_master_audit_trigger, fires after an insert, update, or delete operation on the
client_master table. It uses conditional blocks to determine the type of operation and inserts the old values
into the client_Audit table along with a timestamp.
3. With the trigger in place, whenever a record is inserted, updated, or deleted in the client_master table, the
old values of the records are logged in the client_Audit table, along with the type of operation and a
timestamp.
Please make sure to adjust the trigger and table structures as needed to match your specific database
requirements. Additionally, ensure that you have the necessary privileges to create and use triggers in your
Oracle database.
21) Implement a PL/ block of code using explicit 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.
Question 21
You can use PL/ with an explicit cursor to merge data from the N_RollCall table into the O_RollCall table
while skipping data that already exists in the O_RollCall table. Here's a sample PL/ block that accomplishes
this:
DECLARE
-- Declare cursor to fetch data from N_RollCall
CURSOR n_cursor IS
SELECT *
FROM N_RollCall;
-- Display a message
DBMS_OUTPUT.PUT_LINE('Data from N_RollCall merged into O_RollCall.');
END;
/
In this PL/ block:
-- Check if the fine conditions are met (between 15 and 30 days late)
IF v_days_late >= 15 AND v_days_late <= 30 THEN
-- Calculate the fine amount (Rs 5 per day)
v_fine_amt := v_days_late * 5;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Book not found for the given Roll number and Name of Book.');
END;
/
In this PL/ block, we:
3. Create a view emp_vl of table employee which has emp_id , name and dept-attributes.
4. Display name and department of employee working in Manager or Marketing department
6. Display name and department no of employees who are manager, market analysts. Use Predicates
Question 23
To perform the basic queries you've mentioned, you can follow these steps:
1. Create a table named "employee" with the necessary columns (emp_id, name, dept, and other attributes).
name VARCHAR(50),
dept VARCHAR(50),
hire_date DATE
);
You can use INSERT statements to insert 10 records into the "employee" table. Here's an example of how to insert a few records:
VALUES
3. Create a view named "emp_vl" that contains emp_id, name, and dept attributes from the "employee" table.
CREATE VIEW emp_vl AS
FROM employee;
4. Display the name and department of employees working in the Manager or Marketing department.
FROM employee
FROM employee
FROM employee
6. Display the name and department number of employees who are managers or market analysts using predicates.
FROM employee
FROM employee
FROM employee
Please adapt the above queries to your specific data and requirements.
24) ) Indexing and join: Consider the relation
d. truncate table.
e. find list of customers who placed Orders and details of their Orderss.
Question 24
In the scenario provided, it seems like you're working with two tables, "employee" and "Customer," and you
want to perform various actions including indexing, joining, and data manipulation. Let's go through each
step:
a. To create an index on the "employee" table, you can use the following command to create an index on the
"emp_id" column, making it the primary key:
b. To create a user-defined index on a specific column, you can use the CREATE INDEX statement. For
example, to create an index on the "salary" column, you can use:
d. To truncate a table, use the TRUNCATE TABLE statement. For example, to truncate the "employee"
table:
e. To find a list of customers who placed Orderss and details of their Orderss, you can use a query with a
JOIN between the "Customer" and "Orders" tables. This query retrieves customer information and their
Orders details:
f. To find information about customers and append their Orders details to the table, you can use an INSERT
INTO...SELECT statement. This example inserts the results of the previous query into a new table:
g. To list customers who haven't placed Orderss, you can use a LEFT JOIN between the "Customer" and
"Orders" tables and filter for rows where there's no match in the "Orders" table:
SELECT c.c_name
FROM Customer c
LEFT JOIN Orders o ON c.c_id = o.cust_id
WHERE o.cust_id IS NULL;
This query returns a list of customers who exist in the "Customer" table but don't have corresponding
records in the "Orders" table, indicating they haven't placed Orderss.
Make sure to adjust table and column names as needed to match your specific database schema.
25) Implement aggregation and indexing with suitable example in mongodb.
*Question 25*
Aggregation and indexing are important features in MongoDB that can improve query performance and
allow for complex data transformations. Let's explore both concepts with suitable examples.
*Aggregation in MongoDB:*
Aggregation in MongoDB allows you to perform data transformation and analysis on your data. You can use
the aggregation pipeline to process documents in various stages, applying filters, transformations, and
calculations. Here's an example of using aggregation to calculate the average salary of employees by
department:
*Indexing in MongoDB:*
Indexing in MongoDB can significantly improve query performance. By creating indexes on fields
frequently used for filtering and sorting, you can speed up query execution. Here's an example of creating an
index on the "name" field of the "employees" collection:
In this example, we create a single-field index on the "name" field, which will make name-based queries
faster. The 1 specifies that the index is in ascending Orders.
You can also create compound indexes on multiple fields, which can further optimize queries with multiple
filtering criteria.
In this example, we create a compound index on "department" in ascending Orders and "salary" in
descending Orders.
Aggregation and indexing are powerful tools in MongoDB, and using them effectively can greatly enhance
the performance and capabilities of your database queries.