DEV Community

James K.
James K.

Posted on

Smarter Databases with SQL Views and Triggers

The majority of developers become proficient in SQL's fundamental CRUD operations, but that's like saying you're a pro driver just because you can brake and steer. The advanced toolkit of SQL, which includes views, triggers, indexes, and cursors, is explored in this article. These features turn your database from a basic storage container into a more responsive, intelligent system. The fundamentals of data manipulation are INSERT, SELECT, UPDATE, and DELETE, but we're going to learn how these sophisticated features let your database handle half of the work.

Views

A view in SQL is a virtual table that is based on the result set of a SQL SELECT query. It does not store the data itself but rather provides a way to access and manipulate the data stored in one or more tables. Views can be used to simplify complex queries, enhance security by restricting access to specific data (columns or rows), and present data in a specific format. Some advantages of using views are;

  • Simplify Complex Queries: Encapsulate complex joins and conditions into a single object.
  • Enhance Security: Restrict access to specific columns or rows.
  • Present Data Flexibly: Provide tailored data views for different users.

Views are used in queries like regular tables but do not contain data themselves; they fetch data from the underlying tables. They do not accept parameters and they can often be updated, but this depends on the complexity of the view. Some views are read-only.

Key Operations with Views

1. Creating a View

Views are created using the CREATE VIEW statement.

CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Enter fullscreen mode Exit fullscreen mode

2. Usage:

Once created, views can be queried like regular tables.

SELECT * FROM view_name;
Enter fullscreen mode Exit fullscreen mode

SQL allows us to delete an existing View. We can delete or drop View using the DROP statement. Here’s how to remove the MarksView:

DROP VIEW view_name;
Enter fullscreen mode Exit fullscreen mode

Example Usage

Assume we have the following table employees;

CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(100),
    salary DECIMAL(10, 2)
);
Enter fullscreen mode Exit fullscreen mode

To create a view to display employees from the Sales department;

CREATE VIEW sales_employees AS
SELECT id, name, salary
FROM employees
WHERE department = 'Sales';
Enter fullscreen mode Exit fullscreen mode

You can then query the view like this;

SELECT * FROM sales_employees;
Enter fullscreen mode Exit fullscreen mode

To update the view;

ALTER VIEW sales_employees AS
SELECT id, name, salary, ROUND(salary * 0.1, 2) AS bonus
FROM employees
WHERE department = 'Sales';
Enter fullscreen mode Exit fullscreen mode

When dropping the view, it is a safer approach to use the IF EXISTS clause to prevent errors if the view does not exist. Thus, to drop the view;

DROP VIEW IF EXISTS sales_employees;
Enter fullscreen mode Exit fullscreen mode

Conclusion

SQL Views provides an efficient solution for simplifying complex queries, improving security, and presenting data in a more accessible format. By mastering the creation, management, and updating of views, we can improve the maintainability and performance of our database systems.

Triggers

An SQL trigger is a database object containing SQL logic that is automatically executed when a specific database event occurs. In other words, a database trigger is "triggered" by a particular event.

Types of Triggers

  1. DML Triggers (Data Manipulation Language): These triggers fire in response to data manipulation events (INSERT, UPDATE, DELETE).
  2. DDL Triggers (Data Definition Language): These triggers fire in response to changes in the database schema (CREATE, ALTER, DROP).
  3. Logon Triggers: These triggers fire in response to logon events to the SQL Server.

Timing of Triggers

  1. BEFORE Triggers: These triggers execute before the triggering action is performed.
  2. AFTER Triggers: These triggers execute after the triggering action is performed.
  3. INSTEAD OF Triggers: These triggers replace the triggering action.

Key Operations with Triggers

1. Creating Triggers

The basic syntax of an SQL trigger includes the creation statement, the event that activates the trigger, and the SQL statements that define the trigger's actions. Here’s a general template for creating a trigger.

CREATE TRIGGER trigger_name
[BEFORE | AFTER] [INSERT | UPDATE | DELETE]
ON table_name
FOR EACH ROW
BEGIN
    -- SQL statements
END;
Enter fullscreen mode Exit fullscreen mode

2. Disabling Triggers

PostgreSQL provides an easy way to disable triggers on a per-table basis using the ALTER TABLE command.

ALTER TABLE table_name DISABLE TRIGGER trigger_name;
Enter fullscreen mode Exit fullscreen mode

Sample Usage

Using the Employees table schema in the previous section, the following are examples of triggers in action.

The BEFORE trigger below checks if the salary of a new employee is below 1000 before insertion. If it is, the trigger raises an error to prevent the insert, ensuring a minimum salary requirement is enforced.

-- Create a trigger function
CREATE OR REPLACE FUNCTION check_salary()
RETURNS TRIGGER AS $$
BEGIN
    -- Check if the new salary is below 1000
    IF NEW.salary < 1000.00 THEN
        -- If it is, raise an exception and block the insert
        RAISE EXCEPTION 'Salary must be at least 1000.00';
    END IF;

    -- Otherwise, allow the insert to proceed
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Create the BEFORE INSERT trigger using the function
CREATE TRIGGER before_insert_employees
BEFORE INSERT ON employees
FOR EACH ROW
EXECUTE FUNCTION check_salary();
Enter fullscreen mode Exit fullscreen mode

The AFTER trigger runs after a new employee is added, and if they're in the IT department, it creates a new audit table with a timestamped name. This simulates a DDL operation triggered by specific conditions.

-- Create a trigger function
CREATE OR REPLACE FUNCTION create_audit_table()
RETURNS TRIGGER AS $$
BEGIN
    -- Check if the inserted employee is in the 'IT' department
    IF NEW.department = 'IT' THEN
        -- Dynamically generate a new audit table with a timestamped name
        -- This simulates a DDL operation inside the trigger
        EXECUTE 'CREATE TABLE IF NOT EXISTS audit_employees_' || to_char(NOW(), 'YYYYMMDD_HH24MISS') || ' (
            log_id SERIAL PRIMARY KEY,
            emp_id INT,
            action_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )';
    END IF;

    -- Return NULL for AFTER trigger (since we don't need to modify row data)
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Create the AFTER INSERT trigger using the function
CREATE TRIGGER after_insert_employees
AFTER INSERT ON employees
FOR EACH ROW
EXECUTE FUNCTION create_audit_table();
Enter fullscreen mode Exit fullscreen mode

Advantages of Triggers

  • Data Integrity: Triggers help enforce consistency and business rules, ensuring that data follows the correct format.
  • Automation: Triggers eliminate the need for manual intervention by automatically performing tasks such as updating, inserting, or deleting records when certain conditions are met.
  • Audit Trail: Triggers can track changes in a database, providing an audit trail of INSERT, UPDATE, and DELETE operations.
  • Performance: By automating repetitive tasks, triggers improve SQL query performance and reduce manual workload.

Conclusion

SQL triggers are extremely useful tools that can really enhance your database's performance because they automate tasks, ensure data integrity, and provide error handling and logging capabilities.

Summary

Understanding CRUD is only the first step in learning SQL; real efficiency comes from utilizing the strong, sometimes underutilized features that SQL has to offer. Views can streamline complicated searches and triggers can automate integrity checks. You're not just generating queries when you use these tools; you're creating more intelligent, self-sufficient data systems. Your entire stack will become more maintainable, which will reduce the amount of work your application must do.

Top comments (0)