</>
Skip to content
PostgreSQL lessons (28/38)

PostgreSQL — Procedures

Basic Procedure

CREATE PROCEDURE update_status(user_id INTEGER, new_status VARCHAR)
AS $$
BEGIN
    UPDATE users SET status = new_status WHERE id = user_id;
END;
$$ LANGUAGE plpgsql;

-- Call
CALL update_status(1, 'active');

Procedure with Transaction

CREATE PROCEDURE transfer_funds(from_id INTEGER, to_id INTEGER, amount DECIMAL)
AS $$
BEGIN
    UPDATE accounts SET balance = balance - amount WHERE id = from_id;
    UPDATE accounts SET balance = balance + amount WHERE id = to_id;
END;
$$ LANGUAGE plpgsql;

-- Call
CALL transfer_funds(1, 2, 100.00);

Procedure with Parameters

CREATE PROCEDURE add_user(
    p_name VARCHAR,
    p_email VARCHAR,
    OUT p_id INTEGER
)
AS $$
BEGIN
    INSERT INTO users (name, email) VALUES (p_name, p_email) RETURNING id INTO p_id;
END;
$$ LANGUAGE plpgsql;

Drop Procedure

DROP PROCEDURE update_status(INTEGER, VARCHAR);

Procedure vs Function

FeatureProcedureFunction
ReturnVia OUT paramsRETURN statement
CallCALLSELECT
TransactionsYesLimited
Use casesOperationsCalculations

Mini Practice

  1. Create a procedure
  2. Use transactions
  3. Add OUT parameters
  4. Call procedures

Up Next

Continue with Triggers — trigger functions.

Related Topics

Frequently Asked Questions about Procedures

What is Procedures in PostgreSQL?

Procedures is a fundamental concept in PostgreSQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Procedures?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Procedures.

Why is Procedures important in PostgreSQL?

Procedures is essential for PostgreSQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.