Challenge - 5 Problems
Table Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a simple TABLE function
Consider the following PostgreSQL function that returns a table of numbers and their squares.
What is the output of
What is the output of
SELECT * FROM get_squares(3);?PostgreSQL
CREATE OR REPLACE FUNCTION get_squares(n integer) RETURNS TABLE(num integer, square integer) AS $$ BEGIN RETURN QUERY SELECT i, i*i FROM generate_series(1, n) AS i; END; $$ LANGUAGE plpgsql;
Attempts:
2 left
💡 Hint
The function returns numbers from 1 to n and their squares.
✗ Incorrect
The function uses generate_series(1, n) to produce numbers from 1 to n. For each number i, it returns i and i*i as columns num and square.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in TABLE function
Which option contains the correct syntax to define a PostgreSQL function returning a table with columns id (integer) and name (text)?
Attempts:
2 left
💡 Hint
A TABLE function must use RETURN QUERY inside a BEGIN...END block.
✗ Incorrect
Option C correctly uses BEGIN...END and RETURN QUERY. Option C misses BEGIN...END. Option C uses RETURN instead of RETURN QUERY. Option C misses semicolon after END.
❓ optimization
advanced2:00remaining
Optimizing a TABLE function with a loop
Given this function that returns numbers and their factorials, which option optimizes it best by avoiding explicit loops?
PostgreSQL
CREATE OR REPLACE FUNCTION factorials(n integer) RETURNS TABLE(num integer, fact bigint) AS $$ DECLARE f bigint := 1; BEGIN FOR i IN 1..n LOOP f := f * i; RETURN NEXT (i, f); END LOOP; END; $$ LANGUAGE plpgsql;
Attempts:
2 left
💡 Hint
PostgreSQL has a built-in factorial function.
✗ Incorrect
Option B uses the built-in factorial function for each number, avoiding manual loops. Option B tries a complex window function but is incorrect. Option B sums numbers, not factorials. Option B uses invalid syntax i!.
🔧 Debug
advanced2:00remaining
Debugging a TABLE function with missing RETURN QUERY
What error will this function raise when called?
CREATE OR REPLACE FUNCTION get_data() RETURNS TABLE(id integer, val text) AS $$ BEGIN SELECT id, value FROM data_table; END; $$ LANGUAGE plpgsql;Attempts:
2 left
💡 Hint
In PL/pgSQL, SELECT without INTO or RETURN QUERY causes error.
✗ Incorrect
The function runs SELECT but does not specify where to send results. It must use RETURN QUERY to return rows in TABLE functions.
🧠 Conceptual
expert2:00remaining
Understanding TABLE function behavior with OUT parameters
Which statement about PostgreSQL functions returning TABLE with OUT parameters is true?
Attempts:
2 left
💡 Hint
OUT parameters define the output columns and the function returns rows automatically.
✗ Incorrect
When a function declares OUT parameters, PostgreSQL treats it as returning a table. The function can assign values to OUT variables and use RETURN to return rows automatically.