Challenge - 5 Problems
Master of RETURN and RETURN NEXT
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
What is the output of this function using RETURN NEXT?
Consider the following PostgreSQL function that returns a set of integers using RETURN NEXT. What will be the output when calling
SELECT * FROM generate_numbers();?PostgreSQL
CREATE OR REPLACE FUNCTION generate_numbers() RETURNS SETOF INTEGER AS $$ DECLARE i INTEGER := 1; BEGIN WHILE i <= 3 LOOP RETURN NEXT i; i := i + 1; END LOOP; END; $$ LANGUAGE plpgsql;
Attempts:
2 left
💡 Hint
RETURN NEXT adds a row to the result set without ending the function.
✗ Incorrect
The function loops from 1 to 3, each time returning the current value with RETURN NEXT. This accumulates the rows 1, 2, and 3 in the result set.
❓ query_result
intermediate2:00remaining
What happens if RETURN is used inside a loop?
Given this PostgreSQL function, what will be the output of
SELECT * FROM return_in_loop();?PostgreSQL
CREATE OR REPLACE FUNCTION return_in_loop() RETURNS SETOF INTEGER AS $$ DECLARE i INTEGER := 1; BEGIN WHILE i <= 3 LOOP RETURN i; i := i + 1; END LOOP; END; $$ LANGUAGE plpgsql;
Attempts:
2 left
💡 Hint
RETURN immediately ends the function and returns a single value.
✗ Incorrect
The RETURN statement inside the loop exits the function on the first iteration, returning only 1.
📝 Syntax
advanced2:00remaining
Which function definition correctly uses RETURN NEXT to return multiple rows?
Select the function that correctly returns multiple rows using RETURN NEXT in PostgreSQL.
Attempts:
2 left
💡 Hint
RETURN NEXT is used to add rows to a set-returning function.
✗ Incorrect
Option A correctly uses RETURN NEXT twice to add two rows to the result set. Option A uses RETURN which ends the function immediately. Option A has wrong return type. Option A returns only one row.
🔧 Debug
advanced2:00remaining
Why does this function return no rows?
This function is intended to return numbers 1 to 3 using RETURN NEXT, but returns no rows. Why?
PostgreSQL
CREATE OR REPLACE FUNCTION faulty_function() RETURNS SETOF INTEGER AS $$ DECLARE i INTEGER := 1; BEGIN WHILE i <= 3 LOOP RETURN NEXT i; RETURN; i := i + 1; END LOOP; END; $$ LANGUAGE plpgsql;
Attempts:
2 left
💡 Hint
RETURN ends the function immediately, stopping further output.
✗ Incorrect
The RETURN after RETURN NEXT causes the function to exit after the first row, so only one row is returned. The loop never continues.
🧠 Conceptual
expert2:00remaining
How do RETURN and RETURN NEXT differ in set-returning functions?
In PostgreSQL set-returning functions, what is the key difference between RETURN and RETURN NEXT?
Attempts:
2 left
💡 Hint
Think about when the function stops returning rows.
✗ Incorrect
RETURN immediately ends the function and returns a single value, while RETURN NEXT adds a row to the output but allows the function to continue returning more rows.