Stored Procedures & Triggers in SQL
Today I explored two powerful concepts in SQL that are widely used in real-world applications:
πΉ Stored Procedure
A Stored Procedure is a group of SQL statements stored in the database and executed as a single unit.
It helps in:
- β Reusability of code
- β Better performance (since precompiled)
- β Security & access control
- β Easy debugging and maintenance
π Types of Stored Procedures
-
System Stored Procedures β Provided by SQL Server (e.g.,
sp_help
) - User-Defined Stored Procedures β Created by users for custom tasks
- Extended Stored Procedures β Call external functions
- Temporary Stored Procedures β Exist only for a session
π₯ Example of Stored Procedure
-- Creating a stored procedure to fetch employee details
CREATE PROCEDURE GetEmployeeDetails
AS
BEGIN
SELECT * FROM Employees;
END;
-- Execute the stored procedure
EXEC GetEmployeeDetails;
πΉ Triggers
A Trigger is a special kind of stored procedure that automatically executes when a specific event (INSERT, UPDATE, DELETE) occurs on a table.
It is useful for:
- β Maintaining data integrity
- β Automating auditing/logging
- β Enforcing business rules
π Types of Triggers
- BEFORE Trigger β Executes before the operation
- AFTER Trigger β Executes after the operation
- INSTEAD OF Trigger β Replaces the action
π₯ Example of Trigger
-- Creating a trigger to update last_updated column
CREATE TRIGGER UpdateLastModified
ON Employees
AFTER UPDATE
AS
BEGIN
UPDATE Employees
SET last_updated = GETDATE()
WHERE EmployeeID IN (SELECT EmployeeID FROM inserted);
END;
π Key Takeaway
Stored Procedures help in organizing and reusing SQL logic, while Triggers ensure automation and data integrity. Both are essential tools for working with databases efficiently.
π‘ Every day Iβm getting one step closer to mastering SQL and becoming a strong Data Analyst.
#DataAnalytics #SQL #StoredProcedure #Triggers #100DaysOfCode #LearningJourney
Top comments (0)