Dbms Lab
Dbms Lab
Dbms Lab
A) To Write a query to find the total salary paid for each department.
B) To Write a query to find departments with a total salary of more than 150,000.
Descrition :
GROUP BY :
The GROUP BY clause in SQL is used to arrange identical data into groups. This
clause is often used in conjunction with aggregate functions like COUNT(), SUM(),
AVG(), MAX(), and MIN() to perform calculations on each group of data.
Syntax :
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...;
HAVING :
The HAVING clause is used to filter groups created by the GROUP BY clause. It
allows you to specify conditions that filter which groups will appear in the final result
set. It is similar to the WHERE clause but is applied after the GROUP BY operation,
thus working on aggregated data.
Syntax :
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...
HAVING condition;
A) To Write a query to find the total salary paid for each department.
Sql query -> SELECT Department, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Department;
Output :
Department TotalSalary
HR 125000
IT 245000
Sales 142000
B) TO Write a query to find departments with a total salary of more than 150,000.
Sql query-> SELECT Department, SUM(Salary) AS TotalSalary
FROM Employees
GROUP BY Department
HAVING SUM(Salary) > 150000;
Output :
Department TotalSalary
IT 245000
Result :
The above sql queries are executed successfully.
9. Exercise on number functions, character functions , conversion functions and
date functions and group functions.
Aim :
Employees
1. Numeric Function
A) TO Write a query to round the salary of each employee to the nearest
thousand.
B) TO Write a query to find the absolute difference between the maximum and
minimum salaries.
2. Character Function
C) TO Write a query to convert all employee names to uppercase.
D) TO Write a query to concatenate the first 3 characters of the employee’s
name with their department.
3. Conversion Functions
E) TO Write a query to convert the salary to a character string and concatenate
it with the employee's name.
4. Date Functions
F) TO Write a query to find the age of each employee based on their Date of
Birth.
5. Group Functions
G) TO Write a query to find the total number of employees in each department.
Description:
Numeric Functions:
Numeric functions perform operations on numeric data types and return numeric
values.
o Syntax: ABS(number)
o Syntax: FLOOR(number)
o Syntax: CEILING(number)
B) To Write a query to find the absolute difference between the maximum and
minimum salaries.
SQL Query ->
SELECT ABS(MAX(Salary) - MIN(Salary)) AS SalaryDifference
FROM Employees;
Output :
SalaryDifference
30000
Character Functions:
Character functions operate on character strings and return strings or numbers.
Output:
Date Functions:
Date functions operate on date values and return date or numeric values.
E) To Write a query to find the age of each employee based on their Date of
Birth.
SQL -> SELECT Name,
FROM Employees;
Output :
Name Age
Alice 30
Bob 35
Charlie 28
David 43
Eve 30
Frank 37
Grace 40
Conversion Functions:
Conversion functions convert a value from one data type to another.
Output:
Group functions operate on a group of rows and return a single value for the group.
These functions are often used with the GROUP BY clause.
o Syntax: COUNT(column_name)
o Syntax: SUM(column_name)
o Syntax: AVG(column_name)
o Syntax: MAX(column_name)
o Syntax: MIN(column_name)
Result :
The above sql queries are executed successfully.
10. Exercise on set Operators
Employees_2023 Table:
EmployeeI
Name Department
D
1 Alice HR
2 Bob IT
3 Charlie Sales
Employees_2024 Table:
EmployeeI
Name Department
D
2 Bob IT
3 Charlie Sales
4 David Marketing
Description :
Set Operators
Set Operators in SQL are used to combine the results of two or more SELECT
queries.
Syntax:
FROM table1
Set_operator
FROM table2;
UNION:
Combines the result sets of two or more SELECT queries, removing duplicate
rows from the final result.
SQL ->
SELECT Name, Department
FROM Employees_2023
UNION
SELECT Name, Department
FROM Employees_2024;
Output:
Name Department
Alice HR
Bob IT
Charlie Sales
David Marketing
UNION ALL
Combines the result sets of two or more SELECT queries, including all duplicates.
SQL Query->
Output:
Name Department
Alice HR
Bob IT
Charlie Sales
Bob IT
Charlie Sales
David Marketing
INTERSECT
Returns only the rows that are common to both result sets.
SQL Query->
Output:
Name Department
Name Department
Bob IT
Charlie Sales
Returns the rows from the first result set that are not present in the second result set.
Output:
Nam
Department
e
Alice HR
Result :
The above sql queries are executed successfully.
11. Exercise on sub queries
Employees
EmployeeI
Name Department Salary DateOfBirth JoiningDate
D
1 Alice HR 60000 1994-04-23 2020-01-15
2 Bob IT 80000 1989-07-10 2018-05-21
3 Charlie IT 75000 1996-03-11 2021-03-01
4 David HR 65000 1981-08-09 2017-09-25
5 Eve Sales 70000 1993-12-29 2019-12-01
6 Frank Sales 72000 1987-02-14 2020-06-18
7 Grace IT 90000 1983-11-19 2016-08-08
Subqueries
Subqueries are SQL queries nested inside a larger query (such as SELECT, INSERT,
UPDATE, or DELETE statement). The result of the subquery can be used as a
condition in the main query or as an intermediate result.
Types of Subqueries
Syntax
Single-row Subquery
SQL Query:
Output:
Name
Grace
Multiple-row Subquery
B) To List the names of employees who work in the same department as 'Bob'.
SQL Query:
Output:
Name
Bob
Eve
Scalar Subquery
C) To Find the average salary of all employees and then list employees who earn
more than this average.
SQL Query:
Output:
Name Salary
Bob 80000
Charlie 75000
Grace 90000
Frank 72000
Correlated Subquery
D) To Find employees whose salary is above the average salary in their department.
SQL Query:
Output:
Nam
Salary
e
Bob 80000
Grace 90000
Result :
The above sql queries are executed successfully.
12. Exercise on Joins
Employees Table:
Departments Table:
DepartmentID DepartmentName
101 HR
102 IT
103 Sales
105 Marketing
Description:
Joins
Joins are used to combine rows from two or more tables based on a related column.
There are 4 types of joins. They are:
Inner Join
Left Join
Right Join
Outer Join
Syntax :
Inner Join
An Inner Join returns records that have matching values in both tables involved in
the join. If there is no match, the record is not included in the result set.
SQL Query:
SELECT Employees.Name, Departments.DepartmentName FROM Employees
INNER JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;
Output:
Name DepartmentName
Alice HR
Bob IT
Charlie Sales
Eve IT
2. Left Join
A Left Join returns all records from the left table (table1), and the matched records
from the right table (table2). If there is no match, the result is NULL on the right side.
SQL Query:
Expected Output:
Name DepartmentName
Alice HR
Bob IT
Charlie Sales
David NULL
Eve IT
3. Right Join
A Right Join returns all records from the right table (table2), and the matched records
from the left table (table1). If there is no match, the result is NULL on the left side.
SQL Query:
Output:
Name DepartmentName
Alice HR
Bob IT
Charlie Sales
Eve IT
NULL Marketing
A Full Join returns all records when there is a match in either left (table1) or right
(table2) table. If there is no match, the result is NULL from the table with no match.
SQL Query:
Output:
Name DepartmentName
Alice HR
Bob IT
Charlie Sales
David NULL
Eve IT
NULL Marketing
Result :
The above sql queries are executed successfully.
13. Exercise on various date and number Format models
Aim :
Description :
Date Format Models: Used to control the display of date and time values in SQL.
They define how date and time values are converted between their internal
representations and textual output.
· YYYY: 4-digit year.
· MM: 2-digit month.
· DD: 2-digit day.
· YYYY-MM-DD: ISO date format.
· HH:MI AM/PM: 12-hour time format with AM/PM.
Number Format Models: Used to control the display of numeric values in SQL.
They define how numbers are represented in textual output, including the use of
decimal points, commas, currency symbols, etc.
· 9: Represents a digit.
· 0: Represents a digit; displays leading zeros.
· .: Decimal point.
· ,: Group separator (e.g., thousands separator).
SQL Query:
Expected Output:
FormattedDate
30-AUG-2024 14:35:22
SQL Query:
Output:
FormattedEmployeeID
FormattedEmployeeID
00001
00002
00003
Result :
The above sql queries are executed successfully.
14. Exercise on creating tables with integrity constraints.
Aim : To Create an Employees table with a unique constraint on the Email column
and a check constraint ensuring that Salary is greater than 30000.
Description:
Integrity Constraints
Integrity Constraints are rules applied to database tables to ensure the accuracy and
consistency of the data. These constraints enforce certain conditions on data in the
database, preventing invalid data entry and maintaining relationships between tables.
PRIMARY KEY: Ensures that each row in a table is unique and not null.
FOREIGN KEY: Enforces a link between two tables, ensuring that a value in
one table corresponds to a value in another.
UNIQUE: Ensures that all values in a column are unique across the table.
NOT NULL: Ensures that a column cannot have a null value.
CHECK: Ensures that all values in a column satisfy a specific condition.
DEFAULT: Assigns a default value to a column when no value is specified.
Syntax :
...
UNIQUE (column_name),
CHECK (condition)
);
SQL Query:
Output:
The Employees table is created with a unique constraint on Email to prevent duplicate
email addresses, and a check constraint on Salary to ensure it is greater than 30,000.
Result :
The above sql queries are executed successfully.
15. Write programs usnig Pl/SQL control statements
Description:
Executes one block of code if the condition is true, and another block if it is false.
Syntax :
IF condition THEN
ELSE
END IF;
PL/SQL Program:
DECLARE
num NUMBER := 10; -- Initialize the numberBEGIN
IF num > 0 THEN
DBMS_OUTPUT.PUT_LINE('The number is positive.');
ELSIF num < 0 THEN
DBMS_OUTPUT.PUT_LINE('The number is negative.');
ELSE
DBMS_OUTPUT.PUT_LINE('The number is zero.');
END IF;END;
Output:
Result :
The Above programs are executed successfully.
15b)CASE Statement
Aim : To write a PL/SQL program assigns a grade using the CASE statement.
Description: The CASE statement is used when you have multiple possible
conditions and to execute a specific block of code based on the value of an
expression.
Syntax:
grade := CASE
WHEN condition THEN stmts
WHEN condition THEN stmts
ELSE stmts
END;
PL/SQL Program:
DECLARE
score NUMBER := 85;
grade CHAR(1);BEGIN
grade := CASE
WHEN score >= 90 THEN 'A'
WHEN score >= 80 THEN 'B'
WHEN score >= 70 THEN 'C'
WHEN score >= 60 THEN 'D'
ELSE 'F'
END;
Output:
Description: Conditional control can also be applied within loops to control the flow
of iteration. The EXIT WHEN statement is used to exit a loop when a certain
condition is met.
Syntax :
LOOP
Executable statements
EXIT
END LOOP;
PL/SQL Program:
DECLARE
num NUMBER := 5;
factorial NUMBER := 1;
i NUMBER := 1;BEGIN
LOOP
factorial := factorial * i;
i := i + 1;
EXIT WHEN i > num;
END LOOP;
Output:
Aim: To Create a procedure that divides two numbers and handles division-by-zero
exceptions.
PL/SQL Program:
Calling procedure :
BEGIN
DivideNumbers(10, 2);
DivideNumbers(10, 0);END;
Output:
Result: 5
Error: Division by zero is not allowed.
Result :
The Above programs are executed successfully.
17. Exercise on Functions
Aim: To Create a function that calculates the annual salary of an employee based on
their monthly salary.
Syntax :
RETURN return_data_type
IS
-- Declarations
BEGIN
-- Executable statements
RETURN return_value;
EXCEPTION
-- Exception handlers
END function_name;
PL/SQL Program:
Calling Function :
DECLARE
v_annual_salary NUMBER;BEGIN
v_annual_salary := CalculateAnnualSalary(5000);
DBMS_OUTPUT.PUT_LINE('The annual salary is: ' || v_annual_salary);END;/
Output:
Result :
The Above programs are executed successfully.
18. Exercise on Cursors
Aim: To Create a procedure that uses a cursor to count the number of employees in a
specific department.
Description: Cursors in PL/SQL are used to handle multiple rows of data returned
by a query. They allow you to iterate over the result set and process each row
individually. There are two types of cursors in PL/SQL: Implicit Cursors and
Explicit Cursors. Here, we'll focus on Explicit Cursors, which offer more control
over the query execution and result processing.
PL/SQL Program:
emp_record emp_cursor%ROWTYPE;BEGIN
OPEN emp_cursor;
FETCH emp_cursor INTO emp_record;
CLOSE emp_cursor;
Calling procedure :
BEGIN
CountEmployeesByDepartment(4);
END;
Output:
Result :
The Above programs are executed successfully.
19. Exercise on Triggers
Aim: Create a trigger to enforce a constraint that prevents salary from being set below
a certain minimum value (e.g., 30000).
PL/SQL Program:
Sql query :
CREATE OR REPLACE TRIGGER EnforceSalaryConstraint
BEFORE INSERT OR UPDATE ON EmployeesFOR EACH ROWBEGIN
IF :NEW.Salary < 30000 THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary must be at least
30000.');
END IF;
END;
Inserting data:
Output:
Aim: To successfully install MongoDB on your local machine or server and verify
that the installation is working.
Description: MongoDB is a popular NoSQL database that is widely used for its
flexibility, scalability, and ease of use. In this exercise, we will go through the steps to
install MongoDB on a local machine, either on Windows, macOS, or Linux, and then
verify that the installation is successful by running a simple MongoDB command.
Aim: To create a new database, work within it, and then drop (delete) the database.
Sql query:
Sql query:
SHOW DATABASES;
Output :
DiplomaDB
Students
Employees
Dropping a Database
Sql query:
Sql query:
SHOW DATABASES;
Output :
Students
Employees
Result :
The Above programs are executed successfully.
22. Exercise on Creation and Dropping of Collections
In MongoDB, collections are usually created implicitly when you insert the first
document. However, you can also create a collection explicitly.
Javascript code:
}}
Javascript code:
db.createCollection("Students");
Output: [“order”,"Students", “Employees”]
Dropping a Collection
db.collection_name.drop();
Javasrcipt code:
db.Students.drop();
Output: true
Aim: To practice and understand the use of essential MongoDB commands for
creating databases, collections, and documents, as well as performing CRUD (Create,
Read, Update, Delete) operations.
Description: MongoDB commands allow you to interact with the database in various
ways. This exercise covers basic MongoDB commands used for managing databases,
collections, and documents, as well as querying and updating data.
Procedure :
CRUD Operations
Insert Documents:
javascript code
db.Teachers.insertMany([
{ TeacherID: 1, FirstName: "Alice", LastName: "Brown", Subject: "Math" },
{ TeacherID: 2, FirstName: "Bob", LastName: "Smith", Subject: "Science" }
]);
Read Documents:
javascript Copy
db.Teachers.find().pretty();
Output:
{
"_id": ObjectId("..."),
"TeacherID": 1,
"FirstName": "Alice",
"LastName": "Brown",
"Subject": "Math"
},
{
"_id": ObjectId("..."),
"TeacherID": 2,
"FirstName": "Bob",
"LastName": "Smith",
"Subject": "Science"
}
Update Document:
javascript code
db.Teachers.updateOne({ TeacherID: 1 }, { $set: { LastName: "White" } });
Output: { acknowledged: true, matchedCount: 1, modifiedCount: 1 }
Delete Document:
javascript Copy
db.Teachers.deleteOne({ TeacherID: 2 });
Result :
The Above programs are executed successfully.