Stored procedures in Redshift let you package SQL logic in reusable, parameter-driven routines executed with a single CALL statement.
A stored procedure is a named set of SQL statements written in PL/pgSQL or Python that runs on the cluster. It supports parameters, control-flow, and transaction management, enabling complex, reusable business logic.
Use procedures to encapsulate multi-step ETL, enforce data quality rules, or implement auditing wrapped in a single, version-controlled unit. They reduce repetitive code and centralize business rules.
Define the procedure with CREATE PROCEDURE, specify input parameters, language, and body. Use $$ delimiters for the code block.
CREATE OR REPLACE PROCEDURE add_order(
p_customer_id INT,
p_product_id INT,
p_qty INT)
LANGUAGE plpgsql
AS $$
DECLARE
v_price NUMERIC;
BEGIN
-- Get current product price
SELECT price INTO v_price FROM Products WHERE id = p_product_id;
-- Insert order header
INSERT INTO Orders(customer_id, order_date, total_amount)
VALUES (p_customer_id, CURRENT_DATE, v_price * p_qty)
RETURNING id INTO STRICT _order_id;
-- Insert order item
INSERT INTO OrderItems(order_id, product_id, quantity)
VALUES (_order_id, p_product_id, p_qty);
END;
$$;
Run the procedure with CALL and supply arguments in order.
CALL add_order(42, 7, 3);
No. Redshift supports positional parameters only. Ensure argument order matches the definition.
Use CREATE OR REPLACE to update logic without dropping privileges. Remove a procedure permanently with DROP PROCEDURE name(arg_types).
DROP PROCEDURE add_order(INT, INT, INT);
Use explicit transaction control (BEGIN, COMMIT) for multi-step DML. Validate inputs at the top of the routine. Keep procedures idempotent where possible and version them in source control.
Avoid dynamic SQL when static statements suffice; it slows compilation and complicates privileges. Always qualify object names with schema to prevent search-path surprises.
No. Return results through result sets (SELECT) or by assigning to variables and selecting them at the end.
Redshift lacks interactive debuggers. Use RAISE INFO statements for step-wise logging and examine STL_QUERY and SVL_STATEMENTTEXT views.
Not inherently. Procedures add orchestration; views remain more efficient for single-statement read-only queries.