Bird
0
0

You want to write a PL/pgSQL function that deletes rows from a table whose name is passed as a parameter. Which approach correctly uses dynamic SQL with EXECUTE to achieve this?

hard📝 Application Q8 of 15
PostgreSQL - Advanced PL/pgSQL
You want to write a PL/pgSQL function that deletes rows from a table whose name is passed as a parameter. Which approach correctly uses dynamic SQL with EXECUTE to achieve this?
AEXECUTE format('DELETE FROM %I WHERE id = $1', table_name) USING id_value;
BEXECUTE 'DELETE FROM ' || table_name || ' WHERE id = id_value';
CPERFORM DELETE FROM table_name WHERE id = id_value;
DEXECUTE 'DELETE FROM ' || quote_literal(table_name) || ' WHERE id = id_value';
Step-by-Step Solution
Solution:
  1. Step 1: Use format() with %I for table name

    %I safely inserts the table name as an identifier to avoid SQL injection.
  2. Step 2: Use USING clause for parameter substitution

    USING passes the id_value safely to the query, avoiding string concatenation risks.
  3. Final Answer:

    EXECUTE format('DELETE FROM %I WHERE id = $1', table_name) USING id_value; -> Option A
  4. Quick Check:

    Use format() + USING for safe dynamic DELETE [OK]
Quick Trick: Use format() with %I and USING for safe dynamic queries [OK]
Common Mistakes:
  • Concatenating variables directly into query strings
  • Using quote_literal() for identifiers
  • Using PERFORM instead of EXECUTE for dynamic SQL

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes