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.
Jump into concepts and practice - no test required
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
RETURNS TABLE do?RETURNS TABLE clause defines that the function will return a set of rows with specified columns, like a table.RETURNS TABLE returns multiple rows and columns.id INT and name TEXT?RETURNS TABLE(id INT, name TEXT) matching the column names and types.RETURN QUERY SELECT 1, 'a'; which returns rows matching the table structure.CREATE FUNCTION get_numbers() RETURNS TABLE(num INT) AS $$ BEGIN RETURN QUERY SELECT generate_series(1,3); END; $$ LANGUAGE plpgsql;
SELECT * FROM get_numbers();?generate_series(1,3) as a table with column num.CREATE FUNCTION get_data() RETURNS TABLE(id INT, val TEXT) AS $$ BEGIN RETURN SELECT 1, 'a'; END; $$ LANGUAGE plpgsql;
RETURN QUERY, not just RETURN.RETURN SELECT which is invalid syntax; it should be RETURN QUERY SELECT.users table with columns id INT and name TEXT. Which function definition correctly achieves this?id INT and name TEXT, so the SELECT must output these types. CREATE FUNCTION get_upper_users() RETURNS TABLE(id INT, name TEXT) AS $$ BEGIN RETURN QUERY SELECT id, UPPER(name) FROM users; END; $$ LANGUAGE plpgsql; matches this.UPPER(name) to convert names to uppercase as required.