Trigger
Trigger
A procedure that runs automatically when an event occurs.
Trigger
A procedure that runs automatically when an event occurs.
A trigger is a database procedure that runs automatically when a specific event (INSERT, UPDATE, DELETE) occurs. When a change is made to a table, it performs a defined action either before (BEFORE) or after (AFTER) the change.
Triggers are used for maintaining data integrity (applying complex business rules), automatically recording audit logs, automatically calculating derived data, synchronizing related tables, and so on. INSTEAD OF triggers can also be used to handle modification operations on views.
However, triggers run implicitly, which makes them hard to debug, and cascading execution can occur in which a trigger calls another trigger. They also affect performance, so excessive use should be avoided, and it is recommended to handle business logic at the application level whenever possible.
-- MySQL 트리거: 감사 로그 자동 기록
DELIMITER //
CREATE TRIGGER log_user_update
AFTER UPDATE ON users
FOR EACH ROW
BEGIN
INSERT INTO user_audit_log (
user_id,
old_email,
new_email,
changed_at,
changed_by
) VALUES (
OLD.id,
OLD.email,
NEW.email,
NOW(),
CURRENT_USER()
);
END //
DELIMITER ;
-- PostgreSQL 트리거: 자동 타임스탬프 갱신
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON orders
FOR EACH ROW
EXECUTE FUNCTION update_modified_column();
-- BEFORE 트리거: 데이터 검증 및 수정
DELIMITER //
CREATE TRIGGER validate_price
BEFORE INSERT ON products
FOR EACH ROW
BEGIN
IF NEW.price < 0 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Price cannot be negative';
END IF;
-- 자동으로 할인가 계산
IF NEW.discount_rate IS NOT NULL THEN
SET NEW.discounted_price = NEW.price * (1 - NEW.discount_rate);
END IF;
END //
DELIMITER ;
-- 재고 자동 감소 트리거
CREATE OR REPLACE FUNCTION decrease_stock()
RETURNS TRIGGER AS $$
BEGIN
UPDATE products
SET stock = stock - NEW.quantity
WHERE id = NEW.product_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'Product not found: %', NEW.product_id;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER on_order_item_insert
AFTER INSERT ON order_items
FOR EACH ROW
EXECUTE FUNCTION decrease_stock();
Security officer: We need to keep a full history of changes to important tables. Will that require a lot of application code changes?
DBA: With triggers, it can be done without changing application code. You just record to an audit table in the UPDATE and DELETE triggers.
Backend developer: Won't using triggers affect performance?
DBA: Slightly, but it's fine for something like audit logging. However, it's best to avoid complex logic and only do INSERT.
Interviewer: What should you be careful about when using triggers?
Candidate: First, triggers run implicitly, which makes them hard to debug. Second, cascading execution can occur in which a trigger calls another trigger, which can cause infinite loops or performance degradation. Third, since they run for every row, there are performance issues when processing large amounts of data.
Interviewer: Then when is it appropriate to use a trigger?
Candidate: They are suitable for simple, essential tasks such as audit logging and automatic timestamp updates. Complex business logic is better handled in the application.
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Senior: This trigger calls an external API. Is that not a problem?
Junior: I want to send a notification when an order is created.
Senior: Triggers run synchronously within the transaction. If the API times out, the INSERT fails too. This kind of thing should be handled asynchronously through a message queue or in the application.