0% found this document useful (0 votes)
18 views11 pages

DBMS Unit 3

Uploaded by

Sri M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views11 pages

DBMS Unit 3

Uploaded by

Sri M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

DBMS Unit 3

Unit 3:-
11Q)

a)Define trigger? give examples for insert, update and delete


b)Differentiate row level and statement level Triggers?
A:
a)

A trigger is a database object that automatically executes a specified set of


actions when certain events occur within a database.

These events typically involve data manipulation language (DML)


statements such as INSERT, UPDATE, or DELETE operations on specific
tables.

Triggers are useful for enforcing business rules, maintaining data integrity,
and automating tasks within a database.

1. Insert Trigger: Automatically sets certain values or performs actions when


new data is inserted into a table.

2. Update Trigger: Enforces specific rules or constraints on data updates,


ensuring data consistency and integrity.

3. Delete Trigger: Performs actions, such as logging or cascading deletes,


when data is deleted from a table, providing control and maintaining an
audit trail of changes.

Example Database Schema:


We have a books table with the following columns:

id : Book ID

title : Book title

author : Book author

available : Indicates whether the book is available for borrowing ( TRUE if


available, FALSE if borrowed)

DBMS Unit 3 1
Trigger Example:

1. Insert Trigger:
Goal: When a new book is added, we want it to be automatically marked as
available.

CREATE TRIGGER set_book_available_trigger


BEFORE INSERT ON books
FOR EACH ROW
BEGIN
NEW.available := TRUE; -- New book is always available
END;

2. Update Trigger:
Goal: We don't want to allow changing the author of a borrowed book.

CREATE TRIGGER prevent_author_update_trigger


BEFORE UPDATE OF author ON books
FOR EACH ROW
BEGIN
IF OLD.available = FALSE THEN
RAISE EXCEPTION 'Cannot update author of borrowed b
ook';
END IF;
END;

3. Delete Trigger:
Goal: We want to log when a book is deleted from the database.

CREATE TABLE book_deletion_log (


book_id INT,
deletion_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TRIGGER log_book_deletion_trigger


AFTER DELETE ON books
FOR EACH ROW

DBMS Unit 3 2
BEGIN
INSERT INTO book_deletion_log (book_id) VALUES (OLD.i
d);
END;

Insert Trigger: Automatically sets new books as available.

Update Trigger: Prevents updating the author of borrowed books.

Delete Trigger: Logs the deletion of books into a separate table.

b)

Row-Level Triggers:
1. What They Do:

Row-level triggers execute once for each row affected by the triggering
event.

They can access and modify the data of the specific row that caused
the trigger to fire.

2. When They Fire:

Fired once for every row affected by the triggering event. For example,
if an UPDATE statement affects 5 rows, a row-level trigger associated
with that UPDATE statement will be fired 5 times, once for each row.

3. Use Cases:

Ideal for tasks that need to be performed on individual rows of data.

Often used for tasks like data validation, auditing changes to specific
rows, or enforcing row-level security policies.

4. Example:

Suppose you have a row-level trigger on a transactions table that


automatically calculates the total amount spent by a customer after
each transaction and updates their total_spent field in the customers
table accordingly.

Statement-Level Triggers:
1. What They Do:

DBMS Unit 3 3
Statement-level triggers execute once for each triggering event,
regardless of the number of rows affected by the event.

They do not have direct access to individual row data but can still
perform actions based on the overall outcome of the triggering event.

2. When They Fire:

Fired once for each triggering SQL statement, regardless of the number
of rows affected by that statement.

3. Use Cases:

Useful for tasks that need to be performed once for a batch of rows or
for the overall outcome of an operation.

Often used for tasks like logging high-level actions, enforcing global
constraints, or performing calculations across multiple rows.

4. Example:

Imagine you have a statement-level trigger on an orders table that


updates the order_count field in the customers table to reflect the total
number of orders placed by all customers whenever a new order is
inserted into the orders table.

Summary:
Row-Level Triggers operate on each row affected by the triggering event,
allowing for row-specific actions.

Statement-Level Triggers execute once for each triggering SQL statement,


making them suitable for batch operations or high-level actions across
multiple rows.

12Q)

a)Explain about aggregate operators with examples?


b)Explain UNION,INTERSECT,EXCEPT operations with
examples?
A:
a)

DBMS Unit 3 4
Aggregate operators are functions used in databases and data analysis to
perform calculations on groups of rows and return a single result.

They are commonly used with the SQL language for querying databases

1. COUNT: This operator counts the number of rows in a group.

Examples:

Count(*): Returns the total number of records .i.e 6.

Count(salary): Return the number of Non-Null values over the column


salary. i.e 5.

Count(Distinct Salary): Return the number of distinct Non-Null values over


the column salary .i.e 4

2. SUM: This operator calculates the sum of values in a numeric column.

Example:

sum(salary): Sum all Non-Null values of Column salary i.e., 310

sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.

3. AVG: This operator calculates the average value of a numeric column.

Example:

Avg(salary) = Sum(salary) / count(salary) = 310/5

Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4

4. MIN: This operator finds the minimum value in a column.

Example:

Min(salary): Minimum value in the salary column except NULL i.e., 40

5. MAX: This operator finds the maximum value in a column.

Example:

Max(salary): Maximum value in the salary i.e., 80.
Understanding with an example:

Id Name Salary

1 A 802

2 B 403

DBMS Unit 3 5
3 C 604

4 D 705

5 E 606

6 F NULL

--Count the number of employees


SELECT COUNT(*) AS TotalEmployees FROM Employee;

-- Calculate the total salary


SELECT SUM(Salary) AS TotalSalary FROM Employee;

-- Find the average salary


SELECT AVG(Salary) AS AverageSalary FROM Employee;

-- Get the highest salary


SELECT MAX(Salary) AS HighestSalary FROM Employee;

-- Determine the lowest salary


SELECT MIN(Salary) AS LowestSalary FROM Employee;

Output:

TotalEmployees
6
TotalSalary
3120
AverageSalary
624
HighestSalary
802
LowestSalary
403

b)

UNION Operator:

DBMS Unit 3 6
The UNION operator could be used to find the result set or combination of two
or more tables.

Terms and Conditions for using UNION:

Each table used within UNION must have the same number of columns.

The columns must have the same data types.

The columns in each table must be in the same order.

Syntax:

SELECT columnnames FROM table1


UNION AL
SELECT columnnames FROM table2;

Example:

Emp1 Table

Emp2 Table

SELECT Country
FROM Emp1

DBMS Unit 3 7
UNION

SELECT Country
FROM Emp2
ORDER BY Country;

Output:

INTERSECT Operator:

The SQL Server INTERSECT operator is a powerful tool that allows database
developers and analysts to retrieve the common elements from two or more
result sets.

Syntax:

SELECT column1, column2, …


FROM table1
INTERSECT
SELECT column1, column2, …
FROM table2;

Example:
Table 1

DBMS Unit 3 8
Table 2

-- Find customers who have placed orders


SELECT CustomerID
FROM Customers
WHERE CustomerID IS NOT NULL
INTERSECT
SELECT CustomerID
FROM Orders
WHERE CustomerID IS NOT NULL;

Output:

DBMS Unit 3 9
The output gives common data of column CustomerId in both table.
EXCEPT Operator:

EXCEPT keyword is an operator that is used to retrieve distinct rows from the
left query result set that are not present in the right query result set in a given
query. It can be useful in finding the difference between two sets of data.
The syntax for the EXCEPT operator is given as follows

Syntax:

SELECT column1, column2, …


FROM table1
EXCEPT
SELECT column1, column2, …
FROM table2;

Example Tables:

CustomerID CustomerName

1 Alice

2 Bob

3 Charlie

PreferredCustomerID CustomerName

1 Alice

2 Bob

DBMS Unit 3 10
Now the task is two find the customers who are not Preferred Customers. To
be more specific we need customers in the first table except the customers in
the second table. It can be done using the following query.

SELECT CustomerID, CustomerName


FROM Customers
EXCEPT
SELECT PreferredCustomerID, CustomerName
FROM PreferredCustomers;

Output:

DBMS Unit 3 11

You might also like