How to Write Stored Procedures in SQL

πŸ’‘ Concept Name

Stored Procedures are reusable SQL routines stored in the database, used to encapsulate logic and improve performance and maintainability.

πŸ“˜ Quick Intro

Instead of repeating SQL code, you can write it once as a stored procedure and call it by name. This improves performance, helps manage complex logic, and enhances security by controlling data access.

🧠 Analogy / Short Story

Think of a stored procedure like a reusable recipe. Instead of rewriting how to bake a cake every time, you store the instructions and just say β€œfollow the cake recipe.” It saves time, avoids mistakes, and ensures consistent results. Similarly, stored procedures help you reuse and standardize SQL logic in your database.

πŸ”§ Technical Explanation

  • πŸ› οΈ Stored procedures are defined using CREATE PROCEDURE followed by the procedure name and logic.
  • πŸ“₯ Parameters can be passed into procedures for dynamic behavior.
  • βš™οΈ They can include control flow, DML operations, loops, and conditions.
  • πŸ” Procedures help abstract and secure database access from users or applications.
  • πŸ”„ Execution is done using the EXEC or CALL statement (varies by SQL dialect).

🎯 Purpose & Use Case

  • βœ… Reuse complex queries and logic across multiple applications.
  • βœ… Control access to sensitive logic without exposing raw SQL to the client.
  • βœ… Improve performance by pre-compiling logic.
  • βœ… Use as part of data import/export pipelines or reporting logic.

πŸ’» Real Code Example

-- Create a procedure (SQL Server syntax)
CREATE PROCEDURE GetCustomerOrders
                    @CustomerID INT
AS
BEGIN
    SELECT OrderID, OrderDate, TotalAmount
    FROM Orders
    WHERE CustomerID = @CustomerID;
END;

-- Execute the procedure
EXEC GetCustomerOrders @CustomerID = 5;

❓ Interview Q&A

Q1: What is a stored procedure?
A: It's a precompiled set of SQL statements stored in the database, designed for reuse and logic encapsulation.

Q2: Why use stored procedures?
A: To simplify code reuse, enhance security, improve performance, and manage complex SQL logic.

Q3: Can stored procedures take parameters?
A: Yes, they support input and output parameters to make them flexible.

Q4: Are stored procedures faster than raw queries?
A: Often, yesβ€”they’re precompiled and optimized by the database engine.

Q5: What are common stored procedure dialects?
A: T-SQL (SQL Server), PL/pgSQL (PostgreSQL), PL/SQL (Oracle), and MySQL procedures.

Q6: Can a procedure return a result set?
A: Yes, it can return data via SELECT queries or OUT parameters.

Q7: How do you modify a stored procedure?
A: Use ALTER PROCEDURE or drop and recreate it depending on DBMS support.

Q8: What is the difference between stored procedures and functions?
A: Procedures don’t return a value directly like functions do, and they can perform actions like DML operations.

Q9: Can stored procedures call other procedures?
A: Yes, they can call other procedures or functions within their body.

Q10: Is error handling possible in stored procedures?
A: Yes, using TRY-CATCH (T-SQL), EXCEPTION blocks (PL/pgSQL), or DECLARE HANDLER (MySQL).

πŸ“ MCQs

Q1. What is a stored procedure in SQL?

  • A temp table
  • A table backup
  • Reusable SQL code stored in the database
  • A static view

Q2. Which keyword creates a stored procedure in SQL Server?

  • MAKE PROC
  • CREATE FUNCTION
  • CREATE PROCEDURE
  • BEGIN PROCEDURE

Q3. How do you execute a stored procedure?

  • SELECT FROM
  • EXEC or CALL
  • RUN PROC
  • CALL FUNCTION

Q4. What is one advantage of using stored procedures?

  • Slower execution
  • Worse readability
  • Better code reuse and security
  • Prevents joins

Q5. What is the syntax to pass a parameter?

  • $param
  • #param
  • @paramName
  • :param

Q6. Do stored procedures support control flow?

  • No
  • Only in Oracle
  • Yes, including IF, WHILE, etc.
  • Only loops are allowed

Q7. Which statement is used to modify a stored procedure?

  • CHANGE PROC
  • UPDATE PROC
  • ALTER PROCEDURE
  • MODIFY FUNCTION

Q8. Can stored procedures include INSERTs and DELETEs?

  • No
  • Only SELECT
  • Yes
  • Only UPDATE

Q9. What is PL/pgSQL?

  • A data type
  • A function format
  • PostgreSQL’s procedural language
  • A MySQL tool

Q10. Are procedures stored on the client or server?

  • Client
  • Browser
  • Server
  • App memory

πŸ’‘ Bonus Insight

Stored procedures can significantly reduce client-server traffic by bundling multiple SQL statements into a single call. Always test procedures with realistic data and use proper error handling to catch failures gracefully.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: