DEV Community

Ramya .C
Ramya .C

Posted on

πŸš€ Day 42 of My Data Analytics Journey !

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;
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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;
Enter fullscreen mode Exit fullscreen mode

🌟 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)