Skip to main content

📦 Stored Procedures

Saved SQL scripts in the database

The Recipe Book Analogy

At a restaurant:

Without recipe book: Chef explains every dish step-by-step to each cook, every time. Inconsistent results, wastes time.

With recipe book: "Make the carbonara" → Chef follows saved recipe. Consistent, fast, standardized.

Stored Procedures are recipe books for your database. Save SQL scripts once, call them by name.


What Is a Stored Procedure?

Stored Procedure = Named, saved SQL script

Instead of:
  Application sends full SQL query each time

You have:
  Application says "call TransferMoney(A, B, 100)"
  Database executes the saved script

Benefits

âś“ Precompiled (faster execution)
âś“ Reusable (call from anywhere)
âś“ Access-controlled (permissions can be applied at the procedure level)
âś“ Maintainable (logic in one place)
âś“ Less network traffic (just procedure name)

Stored Procedure Structure

Basic Anatomy

CREATE PROCEDURE procedure_name(parameters)
BEGIN
  -- SQL statements
  SELECT, INSERT, UPDATE, DELETE...

  -- Logic
  IF, WHILE, CASE...

  -- Return results or status
END

Calling a Procedure

CALL TransferMoney(123, 456, 100.00);

Or from application:
db.call("TransferMoney", [account_from, account_to, amount])

Real-World Example: Money Transfer

Without Stored Procedure

Application code:
  1. Check if sender has enough balance
  2. Deduct from sender
  3. Add to receiver
  4. Log the transaction

4 separate database calls!
Business logic scattered in application.

With Stored Procedure

Database holds TransferMoney procedure:
  - All logic in one place
  - Wrapped in transaction
  - Returns success/failure

Application: CALL TransferMoney(...)
One call, all logic handled.

Stored Procedures vs Functions

AspectProcedureFunction
Call syntaxCALL procedure()SELECT function()
Return typeOptional OUT paramsReturns a value
Use in SELECTNoYes
Side effectsCan modify dataUsually read-only

Function Example

Function: CalculateTax(amount)
Returns: tax amount

Can use in queries:
  SELECT product, price, CalculateTax(price) AS tax
  FROM products;

Why Use Stored Procedures?

1. Performance

Without:
  Every query parsed, optimized, compiled

With:
  Procedure compiled ONCE
  Execution plan cached
  Faster subsequent calls

2. Security

Instead of:
  User can run any SQL (dangerous!)

With procedures:
  User can ONLY call specific procedures
  No direct table access
  Parameters validated

3. Consistency

Business logic in ONE place:
  - All applications call same procedure
  - Rules enforced at database level
  - No "forgetting" validation in one app

4. Reduced Network Traffic

Without:
  Send "SELECT * FROM users WHERE... (long query)"

With:
  Send "CALL GetActiveUsers()"
  Much smaller!

When to Use Stored Procedures

Good Fit

âś“ Complex business logic
âś“ Frequently reused operations
âś“ Security-sensitive operations
âś“ Performance-critical batch operations
âś“ Legacy system integration
âś“ Reporting and analytics

Not a Good Fit

âś— Simple CRUD operations
âś— Logic better suited for application layer
âś— Rapidly changing business rules
âś— Need database portability (procedures vary by vendor)
âś— Heavy use of external services

Stored Procedures in Different Databases

DatabaseLanguage
PostgreSQLPL/pgSQL
MySQLSQL/PSM
SQL ServerT-SQL
OraclePL/SQL

Portability Warning

Stored procedure syntax varies by database!

PostgreSQL: CREATE OR REPLACE FUNCTION
MySQL: CREATE PROCEDURE
SQL Server: CREATE PROC

Switching databases = rewriting procedures.

Common Patterns

Input Validation

IF amount <= 0 THEN
  RAISE EXCEPTION 'Amount must be positive';
END IF;

Error Handling

BEGIN
  -- Attempt operations
EXCEPTION
  WHEN division_by_zero THEN
    -- Handle error
  WHEN OTHERS THEN
    -- Log and rethrow
END;

Transaction Control

BEGIN TRANSACTION;
  -- Multiple operations
  IF error_occurred THEN
    ROLLBACK;
  ELSE
    COMMIT;
  END IF;

Common Mistakes

1. Too Much Logic in Procedures

Procedures with 1000+ lines = hard to maintain.
Keep focused. Split into smaller procedures.

2. No Error Handling

Procedure fails silently = data corruption.
Handle errors and return status.

3. Ignoring Testing

Stored procedures need testing too!
Unit test inputs, outputs, edge cases.

4. Security Assumptions

Procedures can still have SQL injection!
Parameterize inputs.

FAQ

Q: Stored procedures vs ORM?

ORMs generate SQL automatically. SPs are handwritten. SPs win for complex operations; ORMs better for simple CRUD.

Q: Can I debug stored procedures?

Yes! Most database tools have SP debuggers. Also: log to tables, use RAISE NOTICE.

Q: Impact on performance?

Generally faster due to precompilation. But poorly written procedures can still be slow.

Q: Are stored procedures going away?

No. Still widely used in enterprise, finance, and any performance-critical application.


Summary

Stored Procedures are precompiled SQL scripts saved in the database for reuse, access control, and performance.

Key Takeaways:

  • Saved SQL scripts called by name
  • Precompiled for faster execution
  • Controlled access through permissions
  • Business logic in one place
  • Not portable across database vendors
  • Great for complex, frequent, or sensitive operations

Stored procedures keep your database logic organized and efficient!

Related Concepts

Leave a Comment

Comments (0)

Be the first to comment on this concept.

Comments are approved automatically.