0
0
PostgreSQLquery~20 mins

DO blocks for anonymous code in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
DO Blocks Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
1:30remaining
Output of a simple DO block with RAISE NOTICE
What will be the output message when this DO block runs in PostgreSQL?
PostgreSQL
DO $$
BEGIN
  RAISE NOTICE 'Hello from DO block!';
END $$;
AWARNING: Hello from DO block!
BERROR: syntax error near 'RAISE'
CNo output, the block runs silently
DNOTICE: Hello from DO block!
Attempts:
2 left
💡 Hint
RAISE NOTICE prints a message to the client.
📝 Syntax
intermediate
1:30remaining
Identify the syntax error in this DO block
Which option correctly identifies the syntax error in this DO block?
PostgreSQL
DO $$
BEGIN
  PERFORM 1/0;
END $$;
AMissing semicolon after PERFORM statement
BDivision by zero error at runtime, no syntax error
CIncorrect DO block delimiter, should use single quotes
DBEGIN block must be followed by DECLARE section
Attempts:
2 left
💡 Hint
Check if the code syntax is valid before runtime errors.
optimization
advanced
2:00remaining
Best way to loop 5 times in a DO block
Which DO block code efficiently loops exactly 5 times and raises a notice each iteration?
A
DO $$
BEGIN
  FOR i IN 1..5 LOOP
    RAISE NOTICE 'Iteration %', i;
  END LOOP;
END $$;
B
DO $$
DECLARE i INT := 1;
BEGIN
  WHILE i <= 5 LOOP
    RAISE NOTICE 'Iteration %', i;
    i := i + 1;
  END LOOP;
END $$;
C
DO $$
BEGIN
  FOR i IN ARRAY[1,2,3,4,5] LOOP
    RAISE NOTICE 'Iteration %', i;
  END LOOP;
END $$;
D
DO $$
DECLARE i INT;
BEGIN
  FOR i IN 1..5 LOOP
    RAISE NOTICE 'Iteration %', i;
  END LOOP;
END $$;
Attempts:
2 left
💡 Hint
PostgreSQL supports FOR loops with range syntax 1..5.
🔧 Debug
advanced
1:30remaining
Why does this DO block fail to compile?
This DO block fails with a syntax error. What is the cause?
PostgreSQL
DO $$
BEGIN
  RAISE NOTICE 'Value: %', my_var;
END $$;
AMissing semicolon after BEGIN
BRAISE NOTICE requires double quotes around the message
CVariable my_var is not declared before use
DDO blocks cannot use RAISE NOTICE
Attempts:
2 left
💡 Hint
Variables must be declared in DECLARE section before use.
🧠 Conceptual
expert
2:00remaining
Effect of transaction control commands inside DO blocks
Which statement about transaction control commands inside DO blocks is true?
ADO blocks run inside a single transaction and cannot contain COMMIT or ROLLBACK
BYou can use COMMIT and ROLLBACK inside DO blocks to control transactions
CDO blocks automatically commit after each statement inside them
DDO blocks run outside transactions and thus ignore COMMIT and ROLLBACK
Attempts:
2 left
💡 Hint
Consider how PostgreSQL treats anonymous code blocks and transactions.