Which of the following is the correct way to declare a PostgreSQL function that returns a table with columns product_id INT and product_name TEXT?
easy📝 Syntax Q3 of 15
PostgreSQL - Advanced PL/pgSQL
Which of the following is the correct way to declare a PostgreSQL function that returns a table with columns product_id INT and product_name TEXT?
ACREATE FUNCTION get_products() RETURNS SETOF RECORD AS $$ BEGIN RETURN QUERY SELECT id, name FROM products; END; $$ LANGUAGE plpgsql;
BCREATE FUNCTION get_products() RETURNS TABLE(product_id INT, product_name TEXT) AS $$ BEGIN RETURN QUERY SELECT id, name FROM products; END; $$ LANGUAGE plpgsql;
CCREATE FUNCTION get_products() RETURNS INT, TEXT AS $$ BEGIN RETURN QUERY SELECT id, name FROM products; END; $$ LANGUAGE plpgsql;
DCREATE FUNCTION get_products() RETURNS TABLE AS $$ BEGIN RETURN QUERY SELECT id, name FROM products; END; $$ LANGUAGE plpgsql;
Step-by-Step Solution
Solution:
Step 1: Check RETURNS TABLE syntax
RETURNS TABLE requires column names and types specified inside parentheses.
Step 2: Analyze options
CREATE FUNCTION get_products() RETURNS TABLE(product_id INT, product_name TEXT) AS $$ BEGIN RETURN QUERY SELECT id, name FROM products; END; $$ LANGUAGE plpgsql; correctly declares columns and uses RETURN QUERY.
Step 3: Identify incorrect options
B uses SETOF RECORD without column definition, C has invalid RETURNS clause, D misses column definitions.
Final Answer:
CREATE FUNCTION get_products() RETURNS TABLE(product_id INT, product_name TEXT) AS $$ BEGIN RETURN QUERY SELECT id, name FROM products; END; $$ LANGUAGE plpgsql; is the correct syntax.
Quick Check:
RETURNS TABLE needs column definitions. [OK]
Quick Trick:RETURNS TABLE requires column names and types [OK]
Common Mistakes:
Omitting column definitions in RETURNS TABLE
Using RETURNS SETOF RECORD without specifying columns
Incorrect RETURNS clause syntax
Master "Advanced PL/pgSQL" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently