![]() |
VOOZH | about |
A trigger in SQL is a special stored procedure that runs automatically when an INSERT, UPDATE, or DELETE operation occurs on a table. It helps automate actions and keep data consistent. Triggers are especially useful when we need to:
Example: Automatically Track When a User Record Is Updated
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100),
updated_at TIMESTAMP
);
This trigger automatically updates the updated_at field whenever the user record is modified.
CREATE TRIGGER update_timestamp
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
SET NEW.updated_at = CURRENT_TIMESTAMP;
END;
INSERT INTO users (id, name, email) VALUES (1, 'Amit', 'amit@example.com');Output:
π Screenshot-2026-01-22-111259UPDATE users SET email = 'amit_new@example.com' WHERE id = 1;Output:
π Screenshot-2026-01-22-111409Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
FOR EACH ROW
BEGIN
END;
Triggers can be categorized into different types based on the action they are associated with:
π types_of_sql_server_triggersData Definition Language (DDL) triggers run when commands like CREATE, ALTER, or DROP are used. They help track or stop changes to the database structure, such as creating, modifying, or deleting tables.
Example: Prevent Table Deletions
CREATE TRIGGER prevent_table_creation
ON DATABASE
FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS
BEGIN
PRINT 'you can not create, drop and alter table in this database';
ROLLBACK;
END;
Output:
DML triggers fire when we manipulate data with commands like INSERT, UPDATE, or DELETE. These triggers are perfect for scenarios where we need to validate data before it is inserted, log changes to a table, or cascade updates across related tables.
Example: To prevent unauthorized updates in a sensitive students table, we can create a trigger that blocks such changes.
CREATE TRIGGER prevent_update
ON students
FOR UPDATE, INSERT, DELETE
AS
BEGIN
RAISERROR ('You can not insert, update and delete rows in this table.', 16, 1);
END;
Output:
Note:
ROLLBACK TRANSACTIONcan included for safety, but in most casesRAISERRORitself will prevent the DML from completing.
Logon triggers run when a user logs in. They are used to track logins, control access, and limit sessions. Messages from these triggers are stored in the SQL Server error log.
Example: Track User Logins
CREATE TRIGGER track_logon
ON LOGON
AS
BEGIN
PRINT 'A new user has logged in.';
END;
Triggers can automatically perform tasks when data changes in a table. For example, in a student database, when a studentβs grades are updated, the total score should also be updated automatically.
CREATE TRIGGER update_student_score
AFTER UPDATE ON student_grades
FOR EACH ROW
BEGIN
UPDATE total_scores
SET score = score + :new.grade
WHERE student_id = :new.student_id;
END;
Triggers can be used to validate data before insertion. For example, a trigger can check that grades are between 0 and 100 before allowing them to be stored in the table.
CREATE TRIGGER validate_grade
BEFORE INSERT ON student_grades
FOR EACH ROW
BEGIN
IF :new.grade < 0 OR :new.grade > 100 THEN
RAISE_APPLICATION_ERROR(-20001, 'Invalid grade value.');
END IF;
END;
The trigger checks if the inserted grade is valid. If not, it throws an error and prevents the insertion.
We can use a query to list all triggers in SQL Server, which helps us manage and track triggers across multiple databases.
SELECT name, is_instead_of_trigger
FROM sys.triggers
WHERE type = 'TR';
SQL triggers can be specified to run BEFORE or AFTER the triggering event.
In a Student Report Database, a trigger automatically calculates the total and percentage when a new record is added. A BEFORE INSERT trigger does this before saving the data.
Query:
mysql>>desc Student;Output:
π Screenshot-2026-01-22-113840This SQL statement creates a trigger that calculates total and percentage before inserting student marks into the database. The trigger runs automatically whenever new data is added.
CREATE TRIGGER stud_marks
AFTER INSERT ON Student
FOR EACH ROW
BEGIN
UPDATE Student
SET
total = NEW.subj1 + NEW.subj2 + NEW.subj3,
per = (NEW.subj1 + NEW.subj2 + NEW.subj3) * 60.0 / 100
WHERE tid = NEW.tid;
END;
Output:
π Screenshot-2026-01-30-172018