Bird
0
0

What will happen when the following PL/pgSQL block is executed?

medium📝 query result Q5 of 15
PostgreSQL - Advanced PL/pgSQL
What will happen when the following PL/pgSQL block is executed?
DECLARE
  col_name text := 'salary';
  total numeric;
BEGIN
  EXECUTE 'SELECT sum(' || col_name || ') FROM employees' INTO total;
  RAISE NOTICE 'Total salary: %', total;
END;
AIt causes a syntax error due to string concatenation
BIt raises a runtime error because sum() cannot be used dynamically
CIt prints the column name instead of sum
DIt calculates and prints the sum of the salary column
Step-by-Step Solution
Solution:
  1. Step 1: Understand dynamic query construction

    The query string concatenates the column name correctly to form a valid SQL sum query.
  2. Step 2: EXECUTE runs the query and INTO stores the result

    The sum is calculated and stored in total, then printed.
  3. Final Answer:

    It calculates and prints the sum of the salary column -> Option D
  4. Quick Check:

    Dynamic SQL with concatenation works for column names [OK]
Quick Trick: Concatenate strings to build dynamic queries safely [OK]
Common Mistakes:
  • Assuming string concatenation causes syntax errors
  • Believing sum() cannot be used dynamically
  • Forgetting to use INTO to capture results

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes