Process Flow - Postgres functions basics
Start: Call function
Enter function body
Execute SQL statements
Return result
End function execution
When you call a Postgres function, it runs the SQL inside it and then returns a result.
CREATE FUNCTION add_numbers(a INT, b INT) RETURNS INT LANGUAGE plpgsql AS $$ BEGIN RETURN a + b; END; $$;
| Step | Action | Input Values | Operation | Result |
|---|---|---|---|---|
| 1 | Function called | a=3, b=5 | Start execution | No output yet |
| 2 | Execute RETURN | a=3, b=5 | Calculate a + b | 8 |
| 3 | Function ends | a=3, b=5 | Return result | 8 |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| a | undefined | 3 | 3 | 3 |
| b | undefined | 5 | 5 | 5 |
| result | undefined | undefined | 8 | 8 |
Postgres functions run SQL code inside them. Use CREATE FUNCTION with parameters and RETURN type. Inside, use RETURN to send back a result. Call function with inputs to get outputs. Functions help reuse SQL logic easily.
SELECT add_two_numbers(3, 4); return?CREATE FUNCTION add_two_numbers(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;
CREATE FUNCTION multiply_by_two(x integer) RETURNS integer AS $$ BEGIN RETURN x * 2 END; $$ LANGUAGE plpgsql;
Pass the test and this pattern moves unknown