🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Stored Procedures

SQL AdvancedProceduresđŸŸĸ Free Lesson
SQL Advanced

Stored Procedures

Encapsulate business logic into reusable, precompiled SQL routines stored directly in the database.

  • Reusability — Write once, call from anywhere without duplicating SQL code
  • Security — Grant execution permissions without exposing underlying table access
  • Performance — Precompiled execution plans reduce parsing overhead on repeated calls Stored procedures are the backbone of enterprise database applications.

What Is a Stored Procedure?

Once created, a stored procedure's SQL is parsed and its execution plan is cached by the database engine. Subsequent calls reuse the cached plan, avoiding re-parsing and re-optimization — a significant performance benefit for complex queries.

-- Create a simple stored procedure
CREATE PROCEDURE GetActiveCustomers
AS
BEGIN
    SELECT customer_id, name, email, phone
    FROM customers
    WHERE status = 'ACTIVE'
    ORDER BY name;
END;

-- Execute the procedure
EXEC GetActiveCustomers;

Creating Procedures with Parameters

-- Procedure with input and output parameters
CREATE PROCEDURE GetCustomerOrderSummary
    @customer_id INT,
    @total_orders INT OUTPUT,
    @total_spent DECIMAL(10,2) OUTPUT
AS
BEGIN
    SELECT
        @total_orders = COUNT(*),
        @total_spent = ISNULL(SUM(total), 0)
    FROM orders
    WHERE customer_id = @customer_id;
END;

-- Call with output parameters
DECLARE @orders INT, @spent DECIMAL(10,2);
EXEC GetCustomerOrderSummary
    @customer_id = 42,
    @total_orders = @orders OUTPUT,
    @total_spent = @spent OUTPUT;

SELECT @orders AS TotalOrders, @spent AS TotalSpent;

Default Parameter Values

Parameters can have default values, making them optional when calling the procedure.

CREATE PROCEDURE SearchProducts
    @category NVARCHAR(50) = NULL,
    @min_price DECIMAL(10,2) = 0,
    @max_price DECIMAL(10,2) = 999999,
    @sort_by NVARCHAR(20) = 'name'
AS
BEGIN
    SELECT product_id, name, category, price
    FROM products
    WHERE (@category IS NULL OR category = @category)
      AND price BETWEEN @min_price AND @max_price
    ORDER BY
        CASE @sort_by
            WHEN 'name' THEN name
            WHEN 'price' THEN CAST(price AS NVARCHAR)
        END;
END;

-- Call with various parameter combinations
EXEC SearchProducts;                          -- all products
EXEC SearchProducts @category = 'Electronics'; -- electronics only
EXEC SearchProducts @min_price = 50, @max_price = 200;
EXEC SearchProducts @category = 'Books', @sort_by = 'price';

Control Flow in Procedures

Procedures support conditional logic and loops for complex business rules.

CREATE PROCEDURE ProcessOrder
    @order_id INT
AS
BEGIN
    DECLARE @status NVARCHAR(20);
    DECLARE @total DECIMAL(10,2);

    SELECT @status = status, @total = total
    FROM orders WHERE order_id = @order_id;

    IF @status = 'CANCELLED'
    BEGIN
        PRINT 'Order is already cancelled.';
        RETURN;
    END

    IF @total > 1000
    BEGIN
        UPDATE orders
        SET status = 'PENDING_APPROVAL',
            discount = @total * 0.10
        WHERE order_id = @order_id;

        INSERT INTO approval_queue (order_id, requested_by, request_date)
        VALUES (@order_id, SYSTEM_USER, GETDATE());
    END
    ELSE
    BEGIN
        UPDATE orders
        SET status = 'CONFIRMED'
        WHERE order_id = @order_id;

        INSERT INTO order_log (order_id, action, action_date)
        VALUES (@order_id, 'AUTO_CONFIRMED', GETDATE());
    END
END;

Modifying and Dropping Procedures

-- Alter an existing procedure
ALTER PROCEDURE GetActiveCustomers
    @min_order_count INT = 0
AS
BEGIN
    SELECT c.customer_id, c.name, c.email,
           COUNT(o.order_id) AS order_count
    FROM customers c
    LEFT JOIN orders o ON c.customer_id = o.customer_id
    WHERE c.status = 'ACTIVE'
    GROUP BY c.customer_id, c.name, c.email
    HAVING COUNT(o.order_id) >= @min_order_count
    ORDER BY order_count DESC;
END;

-- Drop a procedure
DROP PROCEDURE IF EXISTS GetActiveCustomers;

-- Check if a procedure exists
IF OBJECT_ID('GetActiveCustomers', 'P') IS NOT NULL
    PRINT 'Procedure exists';
ELSE
    PRINT 'Procedure does not exist';

Error Handling in Procedures

CREATE PROCEDURE TransferFunds
    @from_account INT,
    @to_account INT,
    @amount DECIMAL(10,2)
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        -- Validate sufficient balance
        DECLARE @balance DECIMAL(10,2);
        SELECT @balance = balance FROM accounts WHERE id = @from_account;

        IF @balance < @amount
        BEGIN
            RAISERROR('Insufficient funds. Available: %.2f', 16, 1, @balance);
            RETURN;
        END

        UPDATE accounts SET balance = balance - @amount WHERE id = @from_account;
        UPDATE accounts SET balance = balance + @amount WHERE id = @to_account;

        INSERT INTO transfers (from_id, to_id, amount, transfer_date)
        VALUES (@from_account, @to_account, @amount, GETDATE());

        COMMIT;
        PRINT 'Transfer completed successfully.';
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
            ROLLBACK;

        DECLARE @msg NVARCHAR(4000) = ERROR_MESSAGE();
        DECLARE @sev INT = ERROR_SEVERITY();
        RAISERROR(@msg, @sev, 1);
    END CATCH
END;

Advantages Over Inline SQL

FeatureStored ProcedureInline SQL
PerformancePrecompiled execution planParsed on every execution
SecurityGranular EXECUTE permissionsRequires direct table access
Network TrafficSingle call to executeFull SQL text sent each time
MaintainabilityCentralized, version-controlled logicScattered across application code
ReusabilityCall from multiple applicationsDuplicated across clients
SQL InjectionParameters are safe by designRequires careful escaping

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement