Intermediate Topic 30 of 51 Databases
Stored Procedures and Triggers
Server-side code run on demand or on events.
How it works
A stored procedure is a named block of SQL and procedural code saved in the database and executed on request, with parameters and control flow. A trigger is code that runs automatically in response to events such as INSERT, UPDATE or DELETE on a table, before or after the change, per row or per statement. Both keep logic close to the data, reduce round trips and can enforce rules consistently across applications.
Step-by-step walkthrough
- An application calls a stored procedure.
- The logic runs inside the database next to the data.
- Fewer network round trips are needed.
- A trigger runs automatically on INSERT, UPDATE or DELETE.
- Triggers can write audit logs but hide logic, use them with care.
Where it is used
Audit logging, maintaining summary tables, validating complex rules, batch jobs and encapsulating multi-step operations with permissions use procedures and triggers.
Common pitfall
Hidden trigger logic surprises developers, makes debugging and testing hard and can cause cascading effects or performance problems on bulk operations. Business logic split between application and database becomes hard to version and deploy. Procedural dialects are not portable. Use triggers sparingly, document them and keep them short and deterministic.
Where it fits in the course
Stored Procedures and Triggers is topic 30 of 51 in Databases, rated Intermediate. It follows MVCC. The next topic is Query Optimization.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Databases quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Databases quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Stored Procedures and Triggers?
Where do people use Stored Procedures and Triggers?
What is the most common mistake with Stored Procedures and Triggers?
What should I learn before this topic?
How can I practice it?
Is Stored Procedures and Triggers hard to learn?
How long does it take to learn Stored Procedures and Triggers?
Which topics are related to Stored Procedures and Triggers?
What should I study after Stored Procedures and Triggers?
Related topics
- MVCC (Databases)
- Query Optimization (Databases)
- Locking and Two-Phase Locking (Databases)
- Query Execution Plans (Databases)