IT-Hardware & Networking
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
In SQL, a FUNCTION and a TRIGGER are both database objects, but they serve very different purposes.
Main difference
1. SQL FUNCTION
A function is a reusable block of SQL logic that you explicitly call.
Example
Calling it:
Result:
Characteristics of functions
Common uses
2. SQL TRIGGER
A trigger automatically executes when an event happens on a table.
Events:
Example
users,the trigger runs automatically.
Characteristics of triggers
Trigger timing
BEFORE trigger
Runs before operation.
Use case:
AFTER trigger
Runs after operation.
Use case:
Visual comparison
FUNCTION flow
TRIGGER flow
Real-world examples
FUNCTION example
Calculate bonus:
TRIGGER example
Maintain audit log automatically:
Important differences
Example together
Suppose you have:
Function
Used like:
Trigger
Automatically stores old salary whenever update happens.
Relationship between them
Sometimes triggers call functions internally.
Example:
When to use FUNCTION
Use functions when:
When to use TRIGGER
Use triggers when: