Concept Flow - Functions returning TABLE
Call function
Function starts
Execute RETURN QUERY
Build result rows
Return table result
Receive rows in caller
The function is called, runs its query, builds rows, and returns them as a table to the caller.
CREATE FUNCTION get_users() RETURNS TABLE(id INT, name TEXT) AS $$ BEGIN RETURN QUERY SELECT user_id, user_name FROM users; END; $$ LANGUAGE plpgsql;
| Step | Action | Query Executed | Rows Built | Output |
|---|---|---|---|---|
| 1 | Function called | N/A | N/A | Start function execution |
| 2 | Execute RETURN QUERY | SELECT user_id, user_name FROM users | [(1, 'Alice'), (2, 'Bob'), (3, 'Carol')] | Rows prepared to return |
| 3 | Return rows | N/A | [(1, 'Alice'), (2, 'Bob'), (3, 'Carol')] | Output table returned to caller |
| 4 | Function ends | N/A | N/A | Execution complete |
| Variable | Start | After RETURN QUERY | Final |
|---|---|---|---|
| result_rows | empty | [(1, 'Alice'), (2, 'Bob'), (3, 'Carol')] | [(1, 'Alice'), (2, 'Bob'), (3, 'Carol')] |
CREATE FUNCTION name() RETURNS TABLE(col1 type, col2 type) AS $$ BEGIN RETURN QUERY SELECT ...; END; $$ LANGUAGE plpgsql; - RETURN QUERY runs a SELECT and returns all rows as a table - Caller receives multiple rows as function output - Empty SELECT returns empty table result