0
0
PostgreSQLquery~20 mins

Why advanced PL/pgSQL matters in PostgreSQL - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PL/pgSQL Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output of this PL/pgSQL function call?
Consider the following PL/pgSQL function that calculates factorial recursively. What will be the output of SELECT factorial(4);?
PostgreSQL
CREATE OR REPLACE FUNCTION factorial(n integer) RETURNS integer AS $$
BEGIN
  IF n <= 1 THEN
    RETURN 1;
  ELSE
    RETURN n * factorial(n - 1);
  END IF;
END;
$$ LANGUAGE plpgsql;
A24
B10
CError: function calls itself infinitely
D1
Attempts:
2 left
💡 Hint
Think about how factorial is defined mathematically and how recursion works.
🧠 Conceptual
intermediate
1:30remaining
Why use PL/pgSQL over plain SQL for complex logic?
Which of the following is the best reason to use PL/pgSQL instead of plain SQL for database operations?
APL/pgSQL automatically creates indexes for tables.
BPL/pgSQL runs faster than SQL for simple SELECT queries.
CPL/pgSQL allows procedural logic like loops and conditionals inside the database.
DPL/pgSQL replaces the need for any SQL queries.
Attempts:
2 left
💡 Hint
Think about what plain SQL can and cannot do inside the database.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in this PL/pgSQL block
What is the syntax error in the following PL/pgSQL code snippet?
PostgreSQL
DO $$
DECLARE
  counter integer := 0;
BEGIN
  WHILE counter < 5 LOOP
    RAISE NOTICE 'Counter is %', counter;
    counter := counter + 1;
  END LOOP;
END;
$$ LANGUAGE plpgsql;
AMissing semicolon after variable declaration
BIncorrect loop syntax
CRAISE NOTICE requires double quotes
DMissing BEGIN keyword
Attempts:
2 left
💡 Hint
Check punctuation after DECLARE section variables.
optimization
advanced
2:00remaining
Which PL/pgSQL approach improves performance for bulk inserts?
You want to insert 10,000 rows efficiently using PL/pgSQL. Which method is best for performance?
AUse a FOR loop with individual INSERT statements inside
BUse RAISE NOTICE to log each insert
CUse EXECUTE inside the loop for each insert
DUse a single INSERT with multiple VALUES rows
Attempts:
2 left
💡 Hint
Minimize the number of separate insert commands.
🔧 Debug
expert
2:30remaining
Why does this PL/pgSQL function raise an exception?
Given this function, why does calling SELECT divide(10, 0); raise an error?
PostgreSQL
CREATE OR REPLACE FUNCTION divide(a integer, b integer) RETURNS numeric AS $$
BEGIN
  RETURN a / b;
END;
$$ LANGUAGE plpgsql;
AFunction syntax is invalid due to missing RETURN type
BDivision by zero error occurs because no check prevents dividing by zero
CPL/pgSQL does not support division operator
DFunction must use EXECUTE for arithmetic operations
Attempts:
2 left
💡 Hint
Think about what happens when dividing by zero in SQL.