Adbmslab File
Adbmslab File
UNIVERSITY
LAB FILE
Session 2024-25
(PCS1203)
Group: M.Tech(DS)
1
S.No. Particulars Signature of Faculty Member
with Date
2
EXPERIMENT 01
OBJECTIVE: Write the queries for data definition and data manipulation language.
In SQL, Data Definition Language (DDL) and Data Manipulation Language (DML) are subsets of SQL
used for defining and manipulating database structures and data. Here's a breakdown of both types with
examples:
DDL statements are used to define and modify the structure of the database itself, such as tables, indexes, and
schemas.
1)CREATE TABLE:
first_name VARCHAR(50),
last_name VARCHAR(50),
hire_date DATE,
salary DECIMAL(10, 2) );
2)ALTER TABLE
3)DROP TABLE:
4)TRUNCATE TABLE:
DML statements are used for managing data within the objects (tables) defined by DDL. These operations
include inserting, updating, deleting, and querying data.
3
Common DML Statements:
SELECT: Retrieves data from one or more tables.
INSERT: Adds new data into a table.
UPDATE: Modifies existing data in a table.
DELETE: Removes data from a table.
FROM employees
UPDATE employees
WHERE employee_id = 1;
WHERE employee_id = 1;
4
EXPERIMENT 02
The AND operator filters data where both conditions must be true.
FROM employees
2. Using OR Operator
The OR operator filters data where at least one condition must be true.
FROM employees
The NOT operator negates a condition, filtering records where the condition is false.
FROM employees
FROM employees
WHERE hire_date 5
FROM employees
FROM employees
FROM employees
6
EXPERIMENT 03
SQL operators are used to perform operations on data values and return results based on certain conditions.
Operators can be divided into different types such as Arithmetic Operators, Comparison Operators, Logical
Operators, Bitwise Operators, Unary Operators, and Set Operators. Below, I'll cover common SQL
operators and provide examples of how to use them in queries.
1. Arithmetic Operators
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulo)
1) Addition:
This query adds 5,000 to the salary of each employee and returns the new salary.
2) Subtraction:
3) Multiplication:
4) Division:
2. Comparison Operators
= (Equal to)
<> or != (Not equal to)
< (Less than)
> (Greater than)
<= (Less than or equal to)
>= (Greater than or equal to)
BETWEEN (Within a range)
IN (Matches a list of values)
LIKE (Matches a pattern)
IS NULL (Checks for NULL values)
1) Equal to:
FROM employees
WHERE department_id = 2;
FROM employees
WHERE department_id != 3;
3) Less than:
FROM employees
FROM employees
This query retrieves employees with a salary between 40,000 and 60,000.
5. IN
FROM employees
6. LIKE
FROM employees
This query retrieves employees whose first name starts with the letter "J".
7. IS NULL
FROM employees
This query retrieves employees who do not have a department assigned (i.e., department_id is NULL).
3. Logical Operators
1) AND:
9
SELECT first_name, last_name, salary
FROM employees
This query retrieves employees who have a salary greater than 50,000 and work in department 2.
2) OR:
FROM employees
This query retrieves employees who either have a salary greater than 50,000 or were hired before January 1,
2023.
3) NOT:
FROM employees
This query retrieves employees whose salary is not less than 40,000.
4. Set Operators
Set operators combine the results of multiple SELECT queries. The common set operators are UNION,
INTERSECT, and EXCEPT.
UNION: Combines results from two or more SELECT queries and removes duplicates.
INTERSECT: Returns common records from two SELECT queries.
EXCEPT: Returns records from the first query that does not exist in the second query.
1) UNION:
FROM employees
FROM employees
WHERE department_id = 2;
This query combines the first names and last names of employees from department 1 and department 2,
removing duplicates. 10
2) INTERSECT:
SELECT first_name, last_name
FROM employees
FROM employees
WHERE department_id = 2;
This query retrieves employees who work in both department 1 and department 2.
3) EXCEPT:
FROM employees
FROM employees
WHERE department_id = 2;
This query retrieves employees who work in department 1 but not in department 2.
11
EXPERIMENT 04
OBJECTIVE: Write SQL Query using character, number, date, and group functions.
SQL provides a variety of functions to handle character, numeric, date, and grouping operations. Below are
SQL queries that demonstrate the use of these different types of functions:
1. Character Functions
1) UPPER():
UPPER(first_name) AS upper_first_name
FROM employees;
This query retrieves the employee's first name and converts it to uppercase.
2) CONCAT():
FROM employees;
This query combines the first name and last name of employees into a full name.
3) LENGTH():
FROM employees;
This query retrieves the first name and calculates the length of the first name.
4) SUBSTRING():
This query extracts the first 3 characters of the first name of employees.
12
5) TRIM():
SELECT TRIM(first_name) AS trimmed_first_name
FROM employees;
This query removes any leading or trailing spaces from the first_name.
2. Numeric Functions
1) ABS():
FROM employees;
This query calculates the absolute difference between an employee's salary and 50,000.
2) ROUND():
FROM employees;
3) CEIL():
FROM employees;
This query rounds the salary of each employee up to the nearest thousand.
4) FLOOR():
FROM employees;
This query rounds the salary of each employee down to the nearest thousand.
5) MOD():
13
SELECT first_name, last_name, MOD(salary, 1000) AS salary_modulo
FROM employees;
This query calculates the remainder of the salary divided by 1,000 for each employee.
3. Date Functions
1) CURRENT_DATE:
FROM employees;
This query retrieves the current date along with employee details.
2) NOW:
FROM employees;
This query retrieves the current timestamp along with the employee's information.
FROM employees;
FROM employees;
This query calculates the number of days each employee has worked by subtracting the hire date from the
current date.
4. Group Functions
Group functions (also known as aggregate functions) are used to perform calculations on a set of rows.
1) COUNT():
FROM employees
GROUP BY department_id;
2) SUM():
FROM employees
GROUP BY department_id;
3) AVG():
FROM employees
GROUP BY department_id;
4) MIN():
FROM employees
GROUP BY department_id;
15
This query finds the lowest salary in each department.
5) MAX():
FROM employees
GROUP BY department_id;
16
EXPERIMENT 05
OBJECTIVE: Write SQL Query for extracting data from more than one table.
The INNER JOIN returns records that have matching values in both tables.
FROM orders
The LEFT JOIN returns all records from the left table (orders), and the matched records from the right table
(customers). If there is no match, NULL values are returned for columns from the right table.
FROM orders
The RIGHT JOIN is similar to the LEFT JOIN, but it returns all records from the right table (customers), and
matched records from the left table (orders).
FROM orders
The FULL JOIN returns all records when there is a match in either the left (orders) or the right (customers)
table.
FROM orders
18
EXPERIMENT 06
OBJECTIVE: Write SQL queries for sub queries and nested queries
A subquery can be used in the WHERE clause to filter results based on the results of another query.
WHERE customer_id IN (
A subquery can be used in the SELECT clause to return a single value for each row processed by the main
query.
You want to return the order_id and the customer_name for each order. The customer name is in a different
table (customers).
FROM customers
A subquery can also be used in the FROM clause to create a derived table or inline view. This is useful for
situations where you need to aggregate or filter data before joining it with other tables.
The HAVING clause is used to filter groups of data after aggregation. You can use a subquery in the HAVING
clause to filter results based on an aggregate condition.
5. Correlated Subquery
A correlated subquery refers to a subquery that uses values from the outer query. The subquery is evaluated
once for each row processed by the outer query.
Example 5: Correlated subquery to find orders where the order amount is higher than the average order
amount for that customer:
FROM orders o
You can nest multiple subqueries within each other. A nested query involves one subquery inside another,
which can be useful for complex filtering or data extraction.
Example 6: Nested query to find customers who placed an order exceeding the average order amount for
all customers:
SELECT customer_id
FROM orders
20
EXPERIMENT 07
An AFTER INSERT trigger fires after a new row is inserted into the table. For instance, let's say we want to
automatically insert a record into a logs table every time a new order is added to the orders table.
Use Case: Insert a record into the logs table when a new order is inserted.
CREATE TRIGGER after_order_insert AFTER INSERT ON orders FOR EACH ROW BEGIN INSERT INTO
logs (log_message, created_at) VALUES ('New order added: ' || NEW.order_id, NOW()); END;
A BEFORE INSERT trigger runs before a new row is inserted into a table. You might use this to validate data
before it's inserted into the database.
Use Case: Ensure that the order_amount is not negative before inserting a new order.
CREATE TRIGGER before_order_insert BEFORE INSERT ON orders FOR EACH ROW BEGIN IF
NEW.order_amount < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Order amount cannot
be negative'; END IF; END;
An AFTER UPDATE trigger fires after a row is updated. You may use this to automatically update or log
changes to the database.
CREATE TRIGGER after_order_update AFTER UPDATE ON orders FOR EACH ROW BEGIN IF
OLD.status != NEW.status THEN INSERT INTO logs (log_message, created_at) VALUES ('Order ' ||
OLD.order_id || ' status changed from ' || OLD.status || ' to ' || NEW.status, NOW()); END IF; END;
A BEFORE DELETE trigger runs before a row is deleted. You might use this to perform actions such as
archiving data before deletion or preventing deletion under certain conditions.
Use Case: Prevent deletion of orders if the order has been shipped.
CREATE TRIGGER before_order_delete BEFORE DELETE ON orders FOR EACH ROW BEGIN IF
OLD.status = 'Shipped' THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete a
shipped order'; END IF; END;
An AFTER DELETE trigger runs after a row is deleted. It’s useful for cleaning up related data or logging the
deletion.
Use Case: Automatically remove any related records in an order_items table when an order is deleted.
21
CREATE TRIGGER after_order_delete AFTER DELETE ON orders FOR EACH ROW BEGIN DELETE
FROM order_items WHERE order_id = OLD.order_id; END;
A BEFORE UPDATE trigger runs before an update occurs. This is useful for validation or transformation of
data before it’s updated.
Use Case: Update the last_modified timestamp before updating any order record.
CREATE TRIGGER before_order_update BEFORE UPDATE ON orders FOR EACH ROW BEGIN SET
NEW.last_modified = NOW(); END;
22
EXPERIMENT 08
OBJECTIVE: Write SQL queries to create Views AND Cursors and apply on sample database.
A view is a virtual table created by a SELECT query. It doesn't store data itself but presents data from one or
more tables. Views are useful for simplifying complex queries, providing a level of abstraction, and managing
permissions.
We want to create a view to display customer names along with their total order amounts.
After creating the view, you can query it like a regular table:
A cursor is a database object used to retrieve and manipulate data row by row. Cursors are useful when you
need to perform operations on each row in a result set one at a time.
Suppose we want to process the orders table and print the order_id and order_amount for each order. We will
use a cursor to loop through the rows.
OPEN order_cursor;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Order ID: ' + CAST(@order_id AS VARCHAR(10)) + ', Order Amount: ' + CAST(@order_amount AS
VARCHAR(20));
24
EXPERIMENT 09
employees table:
departments table:
department_id department_name
1 HR
2 IT
3 Marketing
1. INNER JOIN
An INNER JOIN returns only the rows where there is a match in both tables.
FROM employees
ON employees.department_id = departments.department_id;
A LEFT JOIN returns all the rows from the left table and the matched rows from the right table. If no match is
found, NULL values are returned for columns of the right table.
FROM employees
ON employees.department_id = departments.department_id;
A RIGHT JOIN returns all the rows from the right table and the matched rows from the left table. If no match is
found, NULL values are returned for columns of the left table.
ON employees.department_id = departments.department_id;
A FULL JOIN returns all rows when there is a match in either the left or right table. If there is no match, NULL
values are returned for columns where there is no match.
FROM employees
ON employees.department_id = departments.department_id;
26
EXPERIMENT 10
This example shows how to create a simple stored procedure that takes no parameters and performs a basic
SELECT operation.
BEGIN
END;
A stored procedure can accept input parameters to filter the data or perform specific operations.
BEGIN
FROM employees
END;
Stored procedures can also have output parameters. These can be used to return values back to the calling
program.
BEGIN
FROM employees
END;
BEGIN
UPDATE employees
END;
Error handling can be implemented in stored procedures to handle unexpected situations (e.g., constraint
violations, invalid inputs, etc.).
BEGIN
BEGIN
END;
UPDATE employees
END;
BEGIN
BEGIN
END;
29