Experiment 6: Write The Queries To Implement The Subqueries Basic Subquery
Experiment 6: Write The Queries To Implement The Subqueries Basic Subquery
Correlated Subquery:
A correlated subquery is a subquery that references a column from the outer query.
Here's an example of a correlated subquery:
SELECT customer_name, order_date, order_amount FROM orders o WHERE order_amount =
( SELECT MAX(order_amount)FROM orders WHERE o.customer_id = customer_id );
This query selects the customer_name, order_date, and order_amount columns from the "orders" table
where the order_amount is equal to the maximum order_amount for that customer. The subquery is
correlated with the outer query by referencing the customer_id column from the outer query.
Subquery in a FROM Clause:
A subquery can also be used in the FROM clause to create a temporary table that can be
used in the outer query. Here's an example of a subquery in a FROM clause:
SELECT customer_name, num_orders FROM ( SELECT customer_id, COUNT(*) AS num_orders
FROM orders GROUP BY customer_id ) AS order_counts JOIN customers ON
order_counts.customer_id = customers.customer_id;
This query selects the customer_name and num_orders columns from a subquery that counts the
number of orders for each customer and groups themby customer_id. The subquery is used to create a
temporary table called "order_counts" that is joined with the "customers" table to get the
customer_name column. By using subqueries in MySQL, we can perform more complex queries that
involve multiple tables and conditions. Subqueries can also be used to create temporary tables that can
be joined with other tables to retrieve the desired data.
OUTPUT
Experiment 7
Write the queries to implement the set operations.
MySQL supports the following set operations:
1) UNION - combines the results of two or more SELECT statements into a single result set.
2) INTERSECT - returns only the common rows between two or more SELECT statements.
3) EXCEPT or MINUS - returns only the rows that are unique to one SELECT statement and not
found in the other SELECT statement.
4) To implement these set operations in MySQL, you can use the following syntax:
UNION :
SELECT column1, column2, ... FROM table2;
Example :-
SELECT name, age, city FROM customers
UNION
SELECT name, age, city FROM employees;
INTERSECT:
MySQL does not have a built-in INTERSECT operator, but you can simulate it using a INNER JOIN.
SELECT column1, column2, ... FROM table1
INNER JOIN table2 ON table1.column = table2.column;
SELECT column1, column2, ... FROM table1
INNER JOIN table2 ON table1.column = table2.column;
Example:-
SELECT name, age, city FROM customers
INNER JOIN employees ON customers.name = employees.name;
EXCEPT or MINUS:
MySQL does not have a built-in EXCEPT or MINUS operator, but you can simulate it using a LEFT
JOIN with a WHERE clause to exclude the rows that exist in the second table.
SELECT column1, column2, ... FROM table1
LEFT JOIN table2 ON table1.column = table2.column
WHERE table2.column IS NULL;
Example :-
SELECT name, age, city FROM customers
LEFT JOIN employees ON customers.name = employees.name WHERE employees.name IS NULL
OUTPUT
Experiment 8
Write the queries to create the views and queries based on views.
FROM orders
GROUP BY customer_id; This view groups the orders by customer_id and calculates the total amount of
orders for each customer.
Next, we can query the view to find the customers with the highest total order amount: SELECT
customer_id, total_amount
FROM customer_order_totals
LIMIT 10;
This query selects the customer_id and total_amount columns from the customer_order_totals view, orders
the results by total_amount in descending order, and limits the results to the top 10 customers by total order
amount.
This is just one example of how to create a view and query it in MySQL. Views can be useful for
simplifying complex queries, creating virtual tables, and improving performance by reducing the amount of
data that needs to be queried.
OUTPUT
Experiment 9
In MySQL, control structures are used to control the flow of execution of SQL statements. There
are three main types of control structures in MySQL:
1) Conditional statements
2) Loops
3) Stored procedures.
Conditional statements:
Conditional statements in MySQL are used to execute a specific set of statements based on a condition. The
most commonly used conditional statement is the IF statement, which has the following syntax: IF condition
THEN
statement1;
ELSE
statement2;
END IF;
Here's an example of using the IF statement in MySQL:
IF 10 > 5 THEN
SELECT '10 is greater than 5';
ELSE
SELECT '10 is not greater than 5'; END
IF; Loops:
Loops in MySQL are used to execute a set of statements repeatedly until a certain condition is met. The two
main types of loops in MySQL are WHILE loops and REPEAT loops.
WHILE loops:
The WHILE loop in MySQL has the following syntax: WHILE condition DO
statement1;
END WHILE;
Here's an example of using the WHILE loop in MySQL:
SET @i = 1;
WHILE @i <= 5 DO
SELECT @i;
SET @i = @i + 1;
END WHILE;
REPEAT loops:
The REPEAT loop in MySQL has the following syntax:
SET @i = 1;
REPEAT
SELECT @i;
SET @i = @i + 1;
UNTIL @i > 5
END REPEAT;
Stored procedures:
Stored procedures in MySQL are a set of SQL statements that are stored in the database and can be executed
by calling the procedure. Stored procedures can contain control structures like conditional statements and
loops.
Here's an example of a stored procedure in MySQL that uses a conditional statement: DELIMITER
//
CREATE PROCEDURE get_customer_details (IN customer_id INT) BEGIN
IF customer_id IS NOT NULL THEN
SELECT * FROM customers WHERE id = customer_id;
ELSE
SELECT * FROM customers;
END IF;
END //
DELIMITER ;
DELIMITER //
CREATE PROCEDURE get_customer_details (IN customer_id INT) BEGIN
IF customer_id IS NOT NULL THEN
SELECT * FROM customers WHERE id = customer_id;
ELSE
SELECT * FROM customers;
END IF;
END //
DELIMITER ; Overall, control structures in MySQL are essential for controlling the flow of execution and
enabling more complex SQL statements.
OUTPUT
Experiment 10 :
Demonstrate the concept of Exception Handling.
MySQL supports exception handling through the use of DECLARE, SIGNAL, and
RESIGNAL statements. Exception handling is used to catch and handle errors that occur during the
execution of SQL statements. Here's an example of how exception handling works in MySQL:
BEGIN
DECLARE exit handler for custom_exception
SELECT 'An error occurred.';
IF 10 > 5 THEN
SIGNAL custom_exception SET message_text = 'An error occurred.';
END IF;
END;
In this example, we declare a custom exception using the DECLARE statement, specifying a condition
for when the exception should be triggered. We then use the BEGIN and END keywords to define a
block of SQL statements that may cause an error.
Next, we use the DECLARE EXIT HANDLER statement to define a handler that will execute if the
custom exception is triggered. In this case, the handler simply selects a message to display.
Finally, we use the IF statement to check for a condition that could trigger the exception. If the condition
is true, we use the SIGNAL statement to raise the custom exception and provide a message to be
displayed by the handler.
Note that RESIGNAL statement is also available in case you want to re-raise an existing exception with
the same error code and message.
Overall, exception handling in MySQL is a powerful tool for catching and handling errors during the
execution of SQL statements. By using custom exceptions and handlers, you can define specific error
conditions and responses to make your SQL code more robust and resilient.
OUTPUT
Experiment 11
Demonstrate the concept of Functions and Procedures.
In MySQL, functions and procedures are two types of database objects that can be used to execute a set
of SQL statements. Both functions and procedures can accept parameters, perform calculations or
operations, and return results. However, there are some differences between them.
Functions:
Functions in MySQL are used to perform a specific task and return a single value. Here's an example of
how to create a function:
CREATE FUNCTION my_function (param1 INT, param2 INT) RETURNS INT BEGIN
DECLARE result INT;
SET result = param1 + param2;
RETURN result;
END;
In this example, we create a function called my_function that accepts two integer parameters and returns
their sum. We declare a local variable called result to store the calculated value and then use the
RETURN statement to return the result to the caller.
Procedures:
Procedures in MySQL are similar to functions, but they can be used to perform a set of operations that
may not necessarily return a value. Here's an example of how to create a procedure:
CREATE PROCEDURE my_procedure (IN param1 INT, IN param2 INT)
BEGIN
UPDATE my_table SET column1 = param1 WHERE column2 = param2;
END;
In this example, we create a procedure called my_procedure that accepts two integer parameters and
updates a table based on those parameters. We use the UPDATE statement to modify the data in the
table.
To call the procedure, we can use the following query:
CALL my_procedure(1, 2);
This will execute the procedure and update the my_table table accordingly.
Overall, functions and procedures are powerful tools in MySQL for performing calculations, operations,
and data manipulation. By defining custom functions and procedures, you can create more efficient and
OUTPUT
flexible SQL code that can be reused across multiple queries and applications.
Experiment 12
Demonstrate the concept of Triggers.
In MySQL, triggers are special database objects that can be used to automatically execute SQL
statements in response to certain events or changes in the database. Triggers can be useful for
implementing data validation, auditing, or other types of business logic that require automatic responses
to database events.
Inside the trigger, we use the INSERT INTO statement to insert a new row into the my_log_table table,
which records information about the event. We use the NOW() function to retrieve the current
timestamp, and we include a message to indicate that a new row was inserted into the original table.
Once the trigger is created, it will automatically execute whenever a new row is inserted into the
my_table table. The trigger will insert a new row into the my_log_table table, recording the event.
OUTPUT
Overall, triggers in MySQL are a powerful tool for implementing automatic responses to database
events. By defining custom triggers, you can automate tasks, enforce data integrity, and add auditing
capabilities