0 votes
127 views
in DataBase Management System by (98.9k points)
edited
Explain Views & Trigger with an example.

1 Answer

0 votes
by (98.9k points)
selected by
 
Best answer

Views and triggers are two important database objects used to improve the functionality and security of a database. Here's an explanation of both, along with examples:

  1. Views: A view is a virtual table that is based on the result of a SELECT statement. Views are used to provide an abstracted layer of data to users, hiding the underlying complexity of the database schema. Views are often used to simplify complex queries or to provide a more restricted view of the data to certain users.

For example, suppose we have a table called "Orders" with columns for "OrderID", "CustomerID", "OrderDate", and "TotalAmount". We could create a view that shows only the "OrderID" and "TotalAmount" columns:



CREATE VIEW OrderSummary AS SELECT OrderID, TotalAmount FROM Orders;

Now, users can query the "OrderSummary" view instead of the "Orders" table, which can simplify queries and reduce the risk of accidentally modifying the underlying data.

  1. Triggers: A trigger is a special type of stored procedure that is automatically executed in response to certain database events, such as INSERT, UPDATE, or DELETE operations on a table. Triggers can be used to enforce business rules, audit changes to data, or perform complex calculations based on the data.

For example, suppose we have a table called "Customers" with columns for "CustomerID", "Name", and "Balance". We could create a trigger that automatically updates a log table whenever a customer's balance changes:



 

CREATE TRIGGER UpdateLog AFTER UPDATE ON Customers FOR EACH ROW BEGIN INSERT INTO BalanceLog (CustomerID, OldBalance, NewBalance, ChangeDate) VALUES (OLD.CustomerID, OLD.Balance, NEW.Balance, NOW()); END;

Now, whenever a user updates a customer's balance in the "Customers" table, the trigger will automatically insert a new row into the "BalanceLog" table, recording the old and new balances, the date of the change, and the customer's ID. This can be useful for auditing and tracking changes to the data.

Related questions

0 votes
1 answer 117 views
0 votes
1 answer 159 views
0 votes
1 answer 142 views
0 votes
1 answer 111 views
0 votes
1 answer 220 views
0 votes
1 answer 143 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

561 users

...