PostgreSQL Tutorial

Data Types

Querying & Filtering Data

Managing Tables

Modifying Data

Conditionals

Control Flow

Transactions & Constraints

Working with JOINS & Schemas

Roles & Permissions

Working with Sets

Subquery & CTEs

User-defined Functions

Important In-Built Functions

PostgreSQL PL/pgSQL

Variables & Constants

Stored Procedures

Working with Triggers

Working with Views & Indexes

Errors & Exception Handling

PostgreSQL - Introduction to Stored Procedures

Stored Procedures in PostgreSQL are part of the SQL standard and have been introduced in PostgreSQL 11. Prior to PostgreSQL 11, there were only functions, and many developers used them similarly to how stored procedures are used in other RDBMS systems. The main distinction is that stored procedures support transaction control, meaning they can manage their own transactions by using commit and rollback.

Key Features and Differences:

  1. Transaction Control: Stored procedures can manage their own transactions using COMMIT, ROLLBACK, and other transaction control statements, which isn't allowed in functions.

  2. CALL Keyword: Unlike functions that are invoked using SELECT, stored procedures are invoked using the CALL keyword.

  3. Return Value: Functions always return a value, while stored procedures do not have a return value.

Creating a Stored Procedure:

The basic syntax for creating a stored procedure is:

CREATE OR REPLACE PROCEDURE procedure_name (parameter_list)
LANGUAGE plpgsql
AS $$
BEGIN
   -- procedure body
END;
$$;

Example:

Suppose we have a table called users with columns id, name, and email. We can create a stored procedure to insert a new user:

CREATE OR REPLACE PROCEDURE insert_user(p_name VARCHAR, p_email VARCHAR)
LANGUAGE plpgsql
AS $$
BEGIN
   INSERT INTO users(name, email) VALUES (p_name, p_email);
   COMMIT;
END;
$$;

To call this procedure:

CALL insert_user('John Doe', 'johndoe@example.com');

Modifying Data:

Stored procedures can be used to perform operations that modify the database data. Inside the stored procedure, you can use INSERT, UPDATE, DELETE, and other DML operations.

Handling Errors:

You can use exception handling in stored procedures to manage errors:

CREATE OR REPLACE PROCEDURE some_procedure()
LANGUAGE plpgsql
AS $$
BEGIN
    -- some operations
EXCEPTION
    WHEN some_exception THEN
        -- handle exception
END;
$$;

Conclusion:

Stored procedures in PostgreSQL provide a way to encapsulate business logic, enhance security, and improve performance by reducing the need to send multiple queries from the client to the server. When combined with roles and privileges, they can be a powerful tool in managing and controlling access to data in the database.

  1. How to define a stored procedure in PostgreSQL:

    • Define a stored procedure using the CREATE PROCEDURE statement.
    CREATE OR REPLACE PROCEDURE procedure_name(parameters)
    AS
    $$ 
    -- SQL statements
    $$ LANGUAGE plpgsql;
    
  2. PL/pgSQL stored procedures in PostgreSQL:

    • Use the PL/pgSQL language for writing stored procedures in PostgreSQL.
    CREATE OR REPLACE PROCEDURE plpgsql_procedure()
    AS
    $$
    BEGIN
       -- PL/pgSQL statements
    END;
    $$ LANGUAGE plpgsql;
    
  3. Calling stored procedures in PostgreSQL:

    • Call a stored procedure using the CALL statement.
    CALL procedure_name(parameters);
    
  4. Parameters and arguments in PostgreSQL stored procedures:

    • Define and use parameters in stored procedures for dynamic behavior.
    CREATE OR REPLACE PROCEDURE param_procedure(param1 INTEGER, param2 VARCHAR)
    AS
    $$
    BEGIN
       -- Use parameters in SQL statements
    END;
    $$ LANGUAGE plpgsql;
    
  5. Returning values from stored procedures in PostgreSQL:

    • Use the OUT parameters to return values from stored procedures.
    CREATE OR REPLACE PROCEDURE return_procedure(IN param1 INTEGER, OUT result VARCHAR)
    AS
    $$
    BEGIN
       -- Perform operations
       result := 'Value';
    END;
    $$ LANGUAGE plpgsql;
    
  6. Handling errors in PostgreSQL stored procedures:

    • Implement error handling using EXCEPTION blocks.
    CREATE OR REPLACE PROCEDURE error_handling_procedure()
    AS
    $$
    BEGIN
       -- Code with error handling
    EXCEPTION
       WHEN others THEN
          -- Handle exception
    END;
    $$ LANGUAGE plpgsql;
    
  7. Conditional logic in stored procedures in PostgreSQL:

    • Use IF, CASE, and other conditional constructs in stored procedures.
    CREATE OR REPLACE PROCEDURE conditional_procedure(IN param BOOLEAN)
    AS
    $$
    BEGIN
       IF param THEN
          -- Execute if true
       ELSE
          -- Execute if false
       END IF;
    END;
    $$ LANGUAGE plpgsql;
    
  8. Transaction management in PostgreSQL stored procedures:

    • Manage transactions using BEGIN, COMMIT, and ROLLBACK statements.
    CREATE OR REPLACE PROCEDURE transaction_procedure()
    AS
    $$
    BEGIN
       -- Start transaction
       BEGIN
          -- SQL statements
       EXCEPTION
          WHEN others THEN
             -- Rollback on error
             ROLLBACK;
       END;
    
       -- Commit transaction
       COMMIT;
    END;
    $$ LANGUAGE plpgsql;
    
  9. Debugging stored procedures in PostgreSQL:

    • Use tools like RAISE NOTICE and logging for debugging stored procedures.
    CREATE OR REPLACE PROCEDURE debug_procedure()
    AS
    $$
    BEGIN
       -- Debugging statements
       RAISE NOTICE 'Debugging information';
    END;
    $$ LANGUAGE plpgsql;
    
  10. Dynamic SQL in PostgreSQL stored procedures:

    • Use dynamic SQL for building and executing queries dynamically.
    CREATE OR REPLACE PROCEDURE dynamic_sql_procedure(IN table_name VARCHAR)
    AS
    $$
    BEGIN
       EXECUTE 'SELECT * FROM ' || table_name;
    END;
    $$ LANGUAGE plpgsql;
    
  11. Stored procedures and triggers in PostgreSQL:

    • Use stored procedures in conjunction with triggers for automated responses to events.
    CREATE OR REPLACE FUNCTION trigger_function()
    RETURNS TRIGGER AS
    $$
    BEGIN
       -- Trigger logic
    END;
    $$ LANGUAGE plpgsql;
    
    CREATE TRIGGER example_trigger
    AFTER INSERT ON example_table
    FOR EACH ROW
    EXECUTE FUNCTION trigger_function();
    
  12. Using stored procedures for batch processing in PostgreSQL:

    • Leverage stored procedures for efficient batch processing tasks.
    CREATE OR REPLACE PROCEDURE batch_process_procedure()
    AS
    $$
    BEGIN
       -- Batch processing logic
    END;
    $$ LANGUAGE plpgsql;