How to Format SQL Triggers: CREATE TRIGGER Syntax and Organization
By Sharon Ben-Moshe · October 12, 2026 · 1 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Format SQL triggers across PostgreSQL, MySQL, and SQL Server. Master BEFORE vs AFTER events, FOR EACH ROW logic, and clean trigger function layout.
Quick answer
Format SQL triggers with clear visual separation between trigger declaration and execution logic. In PostgreSQL, triggers call a separate standalone function returning TRIGGER; format the trigger function with clean BEGIN...END indentation and define the CREATE TRIGGER statement below it. In MySQL and SQL Server, format the trigger body with explicit event handling and row-level references.
FAQs
What is the difference between BEFORE and AFTER triggers?
BEFORE triggers fire prior to writing changes to the table, allowing you to validate or modify values in `NEW.col`. AFTER triggers fire after data is written, making them ideal for audit logging and cascading updates.
How do triggers access modified data?
In PostgreSQL and MySQL, row triggers access the incoming and outgoing records via `NEW` and `OLD` records. In SQL Server, triggers inspect the special `inserted` and `deleted` virtual tables.
Why does PostgreSQL require a separate trigger function?
PostgreSQL decouples the procedural trigger function (CREATE FUNCTION ... RETURNS TRIGGER) from the trigger binding (CREATE TRIGGER ... EXECUTE FUNCTION). This allows multiple tables to reuse the same audit or timestamp trigger function.
Are triggers recommended for business logic?
Use triggers sparingly. Triggers execute silently behind the scenes, making debugging difficult and complicating unit testing. They are best reserved for updated_at timestamps, immutable audit trails, and strict cross-table invariants.
Keep reading
Building an Enterprise SQL Style Guide: Formatting Standards, Linting, and Team Conventions
By Sharon Ben-Moshe · Oct 13, 2026
The complete blueprint for an enterprise SQL style guide. Standardize formatting, keyword casing, indentation, naming conventions, and CI linting.
Read postThe Master Guide to SQL Common Table Expressions (CTEs): Syntax, Optimization Fences, and Recursion
By Sharon Ben-Moshe · Oct 13, 2026
The definitive guide to SQL Common Table Expressions (CTEs). Master chaining, recursive hierarchies, data-modifying CTEs, and optimization fences.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.