0% found this document useful (0 votes)
1 views

Adbmslab File

This document is a lab file for the Advanced Database Management System course at Shri Ramswaroop Memorial University for the session 2024-25. It includes various SQL query exercises covering data definition and manipulation, logical operators, SQL operators, and functions for character, numeric, date, and grouping operations. Each section provides objectives and examples of SQL queries to help students understand and apply database concepts.

Uploaded by

ayushi9727v
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Adbmslab File

This document is a lab file for the Advanced Database Management System course at Shri Ramswaroop Memorial University for the session 2024-25. It includes various SQL query exercises covering data definition and manipulation, logical operators, SQL operators, and functions for character, numeric, date, and grouping operations. Each section provides objectives and examples of SQL queries to help students understand and apply database concepts.

Uploaded by

ayushi9727v
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

SHRI RAMSWAROOP MEMORIAL

UNIVERSITY

LAB FILE
Session 2024-25

Advanced Database Management System Lab

(PCS1203)

SUBMITTED TO: SUBMITTED BY:


Name: Ayushi Verma

Roll No: 202410101070003

Group: M.Tech(DS)
1
S.No. Particulars Signature of Faculty Member
with Date

1. Write the queries for data definition and data


manipulation language.

2. Write SQL queries using logical operators.

3. Write SQL queries using SQL operators.

4. Write SQL Query using character, number,


date, and group functions.

5. Write SQL Query for extracting data from


more than one table.

6. Write SQL queries for sub queries and nested


queries.

7. Write SQL queries to implement Triggers in


database.

8. Write SQL queries to create Views AND


Cursors and apply on sample database.

9. Write SQL queries for different Join


operations of database.

10. Write SQL queries to implement procedures


in database.

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:

1. Data Definition Language (DDL) Queries

DDL statements are used to define and modify the structure of the database itself, such as tables, indexes, and
schemas.

Common DDL Statements:

 CREATE: Used to create databases, tables, views, etc.


 ALTER: Used to modify existing database objects (like tables).
 DROP: Used to delete databases, tables, views, etc.
 TRUNCATE: Used to remove all records from a table but retains the structure.

1)CREATE TABLE:

CREATE TABLE employees

( employee_id INT PRIMARY KEY,

first_name VARCHAR(50),

last_name VARCHAR(50),

hire_date DATE,

salary DECIMAL(10, 2) );

2)ALTER TABLE

ALTER TABLE employees

ADD COLUMN department_id INT;

3)DROP TABLE:

DROP TABLE employees;

4)TRUNCATE TABLE:

TRUNCATE TABLE employees;

2. Data Manipulation Language (DML) Queries

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.

1)SELECT (Retrieve data):

SELECT first_name, last_name, salary

FROM employees

WHERE salary > 50000;

2)INSERT INTO (Insert data):

INSERT INTO employees

(employee_id, first_name, last_name, hire_date, salary)

VALUES (1, 'John', 'Doe', '2024-01-15', 60000.00);

3) UPDATE (Modify existing data):

UPDATE employees

SET salary = 65000.00

WHERE employee_id = 1;

4) DELETE (Remove data):

DELETE FROM employees

WHERE employee_id = 1;

4
EXPERIMENT 02

OBJECTIVE: Write SQL queries using logical operators

The most commonly used logical operators in SQL are:

1. AND: Returns true if both conditions are true.


2. OR: Returns true if at least one condition is true.
3. NOT: Returns true if the condition is false.
4. BETWEEN: Checks if a value is within a range (inclusive).
5. IN: Checks if a value matches any value in a list.
6. LIKE: Searches for a specified pattern.
7. IS NULL: Checks for NULL values.

1. Using AND Operator

The AND operator filters data where both conditions must be true.

SELECT first_name, last_name, salary

FROM employees

WHERE salary > 50000 AND department_id = 2;

2. Using OR Operator

The OR operator filters data where at least one condition must be true.

SELECT first_name, last_name, salary

FROM employees

WHERE salary > 50000 OR hire_date < '2023-01-01';

3. Using NOT Operator

The NOT operator negates a condition, filtering records where the condition is false.

SELECT first_name, last_name, salary

FROM employees

WHERE NOT salary < 40000;

4. Using BETWEEN Operator

The BETWEEN operator filters data within a specific range (inclusive).

SELECT first_name, last_name, hire_date

FROM employees

WHERE hire_date 5

BETWEEN '2020-01-01' AND '2024-01-01';


5. Using IN Operator

The IN operator is used to check if a value matches any value in a list.

SELECT first_name, last_name, department_id

FROM employees

WHERE department_id IN (1, 2, 3);

6. Using LIKE Operator

The LIKE operator is used to search for a specified pattern.

SELECT first_name, last_name

FROM employees

WHERE first_name LIKE 'J%';

7. Using IS NULL Operator

The IS NULL operator checks whether a column contains NULL values.

SELECT first_name, last_name

FROM employees

WHERE department_id IS NULL;

6
EXPERIMENT 03

OBJECTIVE: Write SQL queries using SQL operators.

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

These operators are used for mathematical operations on numeric values.

 + (Addition)
 - (Subtraction)
 * (Multiplication)
 / (Division)
 % (Modulo)

1) Addition:

SELECT first_name, last_name, salary + 5000

AS new_salary FROM employees;

This query adds 5,000 to the salary of each employee and returns the new salary.

2) Subtraction:

SELECT first_name, last_name, salary – 3000

AS reduced_salary FROM employees;

This query subtracts 3,000 from the salary of each employee.

3) Multiplication:

SELECT first_name, last_name, salary * 1.1

AS salary_with_bonus FROM employees;

This query multiplies the salary by 1.1 to give a 10% bonus.

4) Division:

SELECT first_name, last_name, salary / 12

AS monthly_salary FROM employees;

This query divides the salary by 12 to calculate the monthly salary.

5) Modulo (remainder of division):

SELECT first_name, last_name, salary % 1000

AS salary_modulo FROM employees; 7


This query returns the remainder of the salary when divided by 1,000.

2. Comparison Operators

These operators are used to compare values.

 = (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:

SELECT first_name, last_name, salary

FROM employees

WHERE department_id = 2;

This query retrieves employees who work in department 2.

2) Not equal to:

SELECT first_name, last_name, salary

FROM employees

WHERE department_id != 3;

This query retrieves employees who do not work in department 3.

3) Less than:

SELECT first_name, last_name, salary

FROM employees

WHERE salary < 40000;

This query retrieves employees whose salary is less than 40,000.

4) Greater than or equal to:

SELECT first_name, last_name, hire_date

FROM employees

WHERE hire_date >= '2022-01-01';


8
This query retrieves employees hired on or after January 1, 2022.
5) BETWEEN:

SELECT first_name, last_name, salary

FROM employees WHERE salary

BETWEEN 40000 AND 60000;

This query retrieves employees with a salary between 40,000 and 60,000.

5. IN

The IN operator is used to check if a value matches any value in a list.

SELECT first_name, last_name, department_id

FROM employees

WHERE department_id IN (1, 2, 3);

This query retrieves employees who work in department 1, 2, or 3.

6. LIKE

The LIKE operator is used to search for a specified pattern.

SELECT first_name, last_name

FROM employees

WHERE first_name LIKE 'J%';

This query retrieves employees whose first name starts with the letter "J".

7. IS NULL

The IS NULL operator checks whether a column contains NULL values.

SELECT first_name, last_name

FROM employees

WHERE department_id IS NULL;

This query retrieves employees who do not have a department assigned (i.e., department_id is NULL).

3. Logical Operators

Logical operators allow for combining multiple conditions in a query.

 AND (True if both conditions are true)


 OR (True if at least one condition is true)
 NOT (True if the condition is false)

1) AND:
9
SELECT first_name, last_name, salary
FROM employees

WHERE salary > 50000 AND department_id = 2;

This query retrieves employees who have a salary greater than 50,000 and work in department 2.

2) OR:

SELECT first_name, last_name, salary

FROM employees

WHERE salary > 50000 OR hire_date < '2023-01-01';

This query retrieves employees who either have a salary greater than 50,000 or were hired before January 1,
2023.

3) NOT:

SELECT first_name, last_name, salary

FROM employees

WHERE NOT salary < 40000;

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:

SELECT first_name, last_name

FROM employees

WHERE department_id = 1 UNION

SELECT first_name, last_name

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

WHERE department_id = 1 INTERSECT

SELECT first_name, last_name

FROM employees

WHERE department_id = 2;

This query retrieves employees who work in both department 1 and department 2.

3) EXCEPT:

SELECT first_name, last_name

FROM employees

WHERE department_id = 1 EXCEPT

SELECT first_name, last_name

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

Character functions are used to manipulate string data.

Common Character Functions:

 UPPER(): Converts a string to uppercase.


 LOWER(): Converts a string to lowercase.
 CONCAT(): Concatenates two or more strings.
 LENGTH(): Returns the length of a string.
 SUBSTRING(): Extracts a substring from a string.
 TRIM(): Removes leading and trailing spaces from a string.

1) UPPER():

SELECT first_name, last_name,

UPPER(first_name) AS upper_first_name

FROM employees;

This query retrieves the employee's first name and converts it to uppercase.

2) CONCAT():

SELECT CONCAT(first_name, ' ', last_name) AS full_name

FROM employees;

This query combines the first name and last name of employees into a full name.

3) LENGTH():

SELECT first_name, last_name, LENGTH(first_name) AS first_name_length

FROM employees;

This query retrieves the first name and calculates the length of the first name.

4) SUBSTRING():

SELECT first_name, SUBSTRING(first_name, 1, 3) AS short_name FROM employees;.

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

Numeric functions are used for mathematical operations.

Common Numeric Functions:

 ABS(): Returns the absolute value of a number.


 ROUND(): Rounds a number to the nearest integer or specified decimal places.
 CEIL(): Returns the smallest integer greater than or equal to a given number.
 FLOOR(): Returns the largest integer less than or equal to a given number.
 MOD(): Returns the remainder of a division operation.

1) ABS():

SELECT employee_id, salary, ABS(salary - 50000) AS salary_difference

FROM employees;

This query calculates the absolute difference between an employee's salary and 50,000.

2) ROUND():

SELECT first_name, last_name, ROUND(salary, 2) AS rounded_salary

FROM employees;

This query rounds the salary of each employee to 2 decimal places.

3) CEIL():

SELECT first_name, last_name, CEIL(salary / 1000) * 1000 AS rounded_up_salary

FROM employees;

This query rounds the salary of each employee up to the nearest thousand.

4) FLOOR():

SELECT first_name, last_name, FLOOR(salary / 1000) * 1000 AS rounded_down_salary

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

Date functions are used to manipulate date and time values.

Common Date Functions:

 CURRENT_DATE: Returns the current date.


 NOW(): Returns the current date and time.
 DATEADD(): Adds a specified time interval to a date.
 DATEDIFF(): Returns the difference between two dates.
 EXTRACT(): Extracts a part (e.g., year, month, day) of a date.

1) CURRENT_DATE:

SELECT employee_id, first_name, last_name, hire_date, CURRENT_DATE AS current_date

FROM employees;

This query retrieves the current date along with employee details.

2) NOW:

SELECT first_name, last_name, hire_date, NOW() AS current_timestamp

FROM employees;

This query retrieves the current timestamp along with the employee's information.

3) DATEADD() (Add 10 days to hire date):

SELECT first_name, last_name, hire_date, DATEADD(DAY, 10, hire_date) AS new_hire_date

FROM employees;

This query adds 10 days to the hire date of each employee.

4) DATEDIFF() (Calculate difference between hire date and today):

SELECT first_name, last_name, DATEDIFF(CURRENT_DATE, hire_date) AS days_worked

FROM employees;

This query calculates the number of days each employee has worked by subtracting the hire date from the
current date.

5) EXTRACT() (Get the year from the hire date):

SELECT first_name, last_name, EXTRACT(YEAR FROM hire_date) AS hire_year 14


FROM employees;
This query retrieves the year portion of each employee's hire date.

4. Group Functions

Group functions (also known as aggregate functions) are used to perform calculations on a set of rows.

Common Group Functions:

 COUNT(): Counts the number of rows.


 SUM(): Calculates the sum of a numeric column.
 AVG(): Calculates the average of a numeric column.
 MIN(): Returns the minimum value in a column.
 MAX(): Returns the maximum value in a column.

1) COUNT():

SELECT department_id, COUNT(*) AS total_employees

FROM employees

GROUP BY department_id;

This query counts the number of employees in each department.

2) SUM():

SELECT department_id, SUM(salary) AS total_salary

FROM employees

GROUP BY department_id;

This query calculates the total salary of employees in each department.

3) AVG():

SELECT department_id, AVG(salary) AS average_salary

FROM employees

GROUP BY department_id;

This query calculates the average salary of employees in each department.

4) MIN():

SELECT department_id, MIN(salary) AS lowest_salary

FROM employees

GROUP BY department_id;
15
This query finds the lowest salary in each department.
5) MAX():

SELECT department_id, MAX(salary) AS highest_salary

FROM employees

GROUP BY department_id;

This query finds the highest salary in each department.

16
EXPERIMENT 05

OBJECTIVE: Write SQL Query for extracting data from more than one table.

1. Using INNER JOIN

The INNER JOIN returns records that have matching values in both tables.

Example: Suppose you have two tables:

 orders: order_id, customer_id, order_date


 customers: customer_id, customer_name

SELECT orders.order_id, orders.order_date, customers.customer_name

FROM orders

INNER JOIN customers ON orders.customer_id = customers.customer_id;

2. Using LEFT JOIN (or LEFT OUTER JOIN)

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.

SELECT orders.order_id, orders.order_date, customers.customer_name

FROM orders

LEFT JOIN customers ON orders.customer_id = customers.customer_id;

3. Using RIGHT JOIN (or RIGHT OUTER JOIN)

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).

SELECT orders.order_id, orders.order_date, customers.customer_name

FROM orders

RIGHT JOIN customers ON orders.customer_id = customers.customer_id;

4. Using FULL JOIN (or FULL OUTER JOIN)

The FULL JOIN returns all records when there is a match in either the left (orders) or the right (customers)
table.

SELECT orders.order_id, orders.order_date, customers.customer_name

FROM orders

FULL OUTER JOIN customers ON orders.customer_id = customers.customer_id;

5. Using a Subquery (Nested SELECT)


17
A subquery is a query nested inside another query. This is useful when you need to extract data based on a
condition from another table.

SELECT order_id, (SELECT customer_name FROM customers WHERE customers.customer_id =


orders.customer_id) AS customer_name FROM orders;

18
EXPERIMENT 06

OBJECTIVE: Write SQL queries for sub queries and nested queries

1. Subquery in the WHERE Clause

A subquery can be used in the WHERE clause to filter results based on the results of another query.

Example 1: Using a subquery in WHERE to filter results:

Suppose you have two tables:

 orders: order_id, customer_id, order_date


 customers: customer_id, customer_name

SELECT order_id, order_date FROM orders

WHERE customer_id IN (

SELECT customer_id FROM customers

WHERE customer_name LIKE 'John%' );

2. Subquery in the SELECT Clause

A subquery can be used in the SELECT clause to return a single value for each row processed by the main
query.

Example 2: Subquery in SELECT to get customer names with each order:

You want to return the order_id and the customer_name for each order. The customer name is in a different
table (customers).

SELECT order_id, (SELECT customer_name

FROM customers

WHERE customers.customer_id = orders.customer_id) AS customer_name FROM orders;

3. Subquery in the FROM Clause

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.

Example 3: Subquery in FROM to get total order amounts by customer:

SELECT customer_id, total_order_amount FROM

( SELECT customer_id, SUM(order_amount) AS total_order_amount

FROM orders GROUP BY customer_id ) AS total_orders

WHERE total_order_amount > 1000; 19


4. Subquery in the HAVING Clause

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.

Example 4: Subquery in HAVING to filter groups:

SELECT customer_id, SUM(order_amount) AS total_order_amount

FROM orders GROUP BY customer_id HAVING SUM(order_amount) > ( SELECT


AVG(total_order_amount)

FROM ( SELECT SUM(order_amount) AS total_order_amount

FROM orders GROUP BY customer_id ) AS avg_orders );

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:

SELECT order_id, order_amount, customer_id

FROM orders o

WHERE order_amount > ( SELECT AVG(order_amount)

FROM orders WHERE customer_id = o.customer_id );

6. Nested Query (Multiple Subqueries)

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 WHERE order_id IN ( SELECT order_id

FROM orders

WHERE order_amount > ( SELECT AVG(order_amount) FROM orders ) );

20
EXPERIMENT 07

OBJECTIVE: Write SQL queries to implement Triggers in database.

1: AFTER INSERT Trigger

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;

2: BEFORE INSERT Trigger

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;

3: AFTER UPDATE Trigger

An AFTER UPDATE trigger fires after a row is updated. You may use this to automatically update or log
changes to the database.

Use Case: Log changes to an order when an order’s status is updated.

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;

4: BEFORE DELETE Trigger

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;

5: AFTER DELETE Trigger

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;

6: BEFORE UPDATE Trigger

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.

1. Creating Views in SQL

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.

Example 1: Create a View

Suppose we have a customers and orders table in a sample database:

 customers table has columns: customer_id, customer_name, customer_email


 orders table has columns: order_id, customer_id, order_date, order_amount

We want to create a view to display customer names along with their total order amounts.

CREATE VIEW customer_order_summary AS SELECT c.customer_id, c.customer_name,


SUM(o.order_amount) AS total_order_amount FROM customers c JOIN orders o ON c.customer_id =
o.customer_id GROUP BY c.customer_id, c.customer_name;

Querying the View:

After creating the view, you can query it like a regular table:

SELECT * FROM customer_order_summary;

2. Creating Cursors in SQL

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.

Example 2: Create and Use a Cursor

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.

Step 1: Declare the Cursor

DECLARE order_cursor CURSOR FOR SELECT order_id, order_amount FROM orders;

Step 2: Open the Cursor

OPEN order_cursor;

Step 3: Fetch Data Using the Cursor

FETCH NEXT FROM order_cursor INTO @order_id, @order_amount;

Step 4: Loop through the Cursor


23
A WHILE loop is used to fetch and process each row in the cursor:
DECLARE @order_id INT, @order_amount DECIMAL(10, 2);

OPEN order_cursor; FETCH NEXT FROM order_cursor INTO @order_id, @order_amount;

WHILE @@FETCH_STATUS = 0

BEGIN

-- Process each row

PRINT 'Order ID: ' + CAST(@order_id AS VARCHAR(10)) + ', Order Amount: ' + CAST(@order_amount AS
VARCHAR(20));

-- Fetch the next row

FETCH NEXT FROM order_cursor INTO @order_id, @order_amount; END;

-- Close and deallocate the cursor

CLOSE order_cursor; DEALLOCATE order_cursor;

24
EXPERIMENT 09

OBJECTIVE: Write SQL queries for different Join operations of database.

employees table:

employee_id name department_id manager_id


1 Alice 1 NULL
2 Bob 2 1
3 Charlie 1 1
4 David 3 2

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.

SELECT employees.name, departments.department_name

FROM employees

INNER JOIN departments

ON employees.department_id = departments.department_id;

2. LEFT JOIN (or LEFT OUTER JOIN)

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.

SELECT employees.name, departments.department_name

FROM employees

LEFT JOIN departments

ON employees.department_id = departments.department_id;

3. RIGHT JOIN (or RIGHT OUTER JOIN)

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.

SELECT employees.name, departments.department_name 25


FROM employees

RIGHT JOIN departments

ON employees.department_id = departments.department_id;

4. FULL JOIN (or FULL OUTER JOIN)

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.

SELECT employees.name, departments.department_name

FROM employees

FULL JOIN departments

ON employees.department_id = departments.department_id;

26
EXPERIMENT 10

OBJECTIVE: Write SQL queries to implement procedures in database.

1. Creating a Simple Stored Procedure

This example shows how to create a simple stored procedure that takes no parameters and performs a basic
SELECT operation.

CREATE PROCEDURE GetAllEmployees()

BEGIN

SELECT * FROM employees;

END;

2. Stored Procedure with Input Parameters

A stored procedure can accept input parameters to filter the data or perform specific operations.

CREATE PROCEDURE GetEmployeeByDepartment(IN department_id INT)

BEGIN

SELECT name, department_id

FROM employees

WHERE department_id = department_id;

END;

3. Stored Procedure with Output Parameters

Stored procedures can also have output parameters. These can be used to return values back to the calling
program.

CREATE PROCEDURE GetEmployeeCountByDepartment(IN department_id INT, OUT employee_count


INT)

BEGIN

SELECT COUNT(*) INTO employee_count

FROM employees

WHERE department_id = department_id;

END;

4. Stored Procedure with Multiple Input Parameters


27
Stored procedures can take multiple input parameters to perform more complex operations.
CREATE PROCEDURE UpdateEmployeeSalary(IN employee_id INT, IN new_salary DECIMAL)

BEGIN

UPDATE employees

SET salary = new_salary

WHERE employee_id = employee_id;

END;

5. Stored Procedure with Error Handling

Error handling can be implemented in stored procedures to handle unexpected situations (e.g., constraint
violations, invalid inputs, etc.).

CREATE PROCEDURE UpdateEmployeeSalaryWithCheck(IN employee_id INT, IN new_salary DECIMAL)

BEGIN

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION

BEGIN

SELECT 'Error: Could not update salary' AS error_message;

END;

UPDATE employees

SET salary = new_salary

WHERE employee_id = employee_id;

SELECT 'Salary updated successfully' AS status_message;

END;

6. Stored Procedure to Insert Data

Stored procedures can be used to insert new records into a table.

CREATE PROCEDURE AddNewEmployee(IN name VARCHAR(100), IN department_id INT, IN salary


DECIMAL)

BEGIN

INSERT INTO employees (name, department_id, salary) 28

VALUES (name, department_id, salary);


END;

7. Stored Procedure to Delete Data

A stored procedure can also be used to delete records from a table.

CREATE PROCEDURE DeleteEmployee(IN employee_id INT)

BEGIN

DELETE FROM employees WHERE employee_id = employee_id;

END;

29

You might also like