You want to create a function that accepts a variable number of text arguments and returns them as a JSON array. Which function definition correctly uses VARIADIC parameters to achieve this?
hard📝 Application Q8 of 15
PostgreSQL - Advanced PL/pgSQL
You want to create a function that accepts a variable number of text arguments and returns them as a JSON array. Which function definition correctly uses VARIADIC parameters to achieve this?
ACREATE FUNCTION to_json_array(VARIADIC args text) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql;
BCREATE FUNCTION to_json_array(args VARIADIC text[]) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql;
CCREATE FUNCTION to_json_array(VARIADIC args text[]) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql;
DCREATE FUNCTION to_json_array(args text[]) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql;
Step-by-Step Solution
Solution:
Step 1: Correct VARIADIC syntax
VARIADIC keyword must precede parameter name and type, which must be an array type.
Step 2: Check each option
CREATE FUNCTION to_json_array(VARIADIC args text[]) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql; correctly declares VARIADIC args text[]. CREATE FUNCTION to_json_array(args VARIADIC text[]) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql; has wrong keyword order. CREATE FUNCTION to_json_array(VARIADIC args text) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql; uses scalar type. CREATE FUNCTION to_json_array(args text[]) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql; lacks VARIADIC.
Final Answer:
CREATE FUNCTION to_json_array(VARIADIC args text[]) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql; -> Option C
Quick Check:
VARIADIC syntax + array type = CREATE FUNCTION to_json_array(VARIADIC args text[]) RETURNS json AS $$
SELECT to_json(args);
$$ LANGUAGE sql; [OK]
Quick Trick:VARIADIC before name, type must be array for variable args [OK]
Common Mistakes:
Placing VARIADIC after parameter name
Using scalar type with VARIADIC
Omitting VARIADIC keyword
Master "Advanced PL/pgSQL" in PostgreSQL
9 interactive learning modes - each teaches the same concept differently