If you’re working with stored procedures in PostgreSQL and need to return values, here’s how you can do it:
1. Understanding Stored Procedures vs. Functions
In PostgreSQL, a stored procedure (CALL procedure_name()) does not return values directly.
If you need to return values, you should either:
- Use OUT parameters in a procedure.
- Use a function (SELECT function_name()), which can return a value or table.
2. Using OUT Parameters in a Stored Procedure
If you need to return multiple values, use OUT parameters:
CREATE PROCEDURE get_user_details(IN user_id INT, OUT username TEXT, OUT email TEXT)
LANGUAGE plpgsql
AS $$
BEGIN
SELECT name, email INTO username, email FROM users WHERE id = user_id;
END;
$$;
Calling the procedure:
CALL get_user_details(1, NULL, NULL);
OUT parameters will hold the returned values.
3. Using a FUNCTION Instead (Preferred for Returning Values)
If you need a single return value or a table, use a function instead:
CREATE FUNCTION get_user_email(user_id INT) RETURNS TEXT AS $$
DECLARE email TEXT;
BEGIN
SELECT users.email INTO email FROM users WHERE id = user_id;
RETURN email;
END;
$$ LANGUAGE plpgsql;
Calling the function:
SELECT get_user_email(1);
Functions can be used in SELECT queries, unlike procedures.
4. Key Takeaways
- Stored procedures don’t return values directly—use OUT parameters.
- Use functions (RETURNS) if you need to return a value or table.
- Functions can be used in SELECT statements, making them more flexible.