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