Bird
0
0

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:
  1. Step 1: Check RETURNS TABLE syntax

    RETURNS TABLE requires column names and types specified inside parentheses.
  2. 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.
  3. Step 3: Identify incorrect options

    B uses SETOF RECORD without column definition, C has invalid RETURNS clause, D misses column definitions.
  4. 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.
  5. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes