Consider the following PostgreSQL function that uses dynamic SQL with EXECUTE to select data from a table:
CREATE OR REPLACE FUNCTION get_table_count(tablename text) RETURNS integer AS $$ DECLARE result integer; BEGIN EXECUTE 'SELECT count(*) FROM ' || quote_ident(tablename) INTO result; RETURN result; END; $$ LANGUAGE plpgsql;
Assuming there is a table named employees with 5 rows, what will be the output of SELECT get_table_count('employees');?
Think about how EXECUTE runs the SQL string and stores the result into the variable.
The function builds a SQL query dynamically using the table name, then executes it and stores the count into result. Since the table employees has 5 rows, the function returns 5.
Which of the following dynamic SQL statements in a PL/pgSQL block will cause a syntax error when using EXECUTE?
DECLARE sql_text text; BEGIN sql_text := 'SELECT * FROM ' || tablename; EXECUTE sql_text; END;
Remember how string concatenation works in PostgreSQL.
In PostgreSQL, string concatenation uses ||, not +. Using + causes a syntax error.
You have a PL/pgSQL function that runs dynamic SQL with EXECUTE multiple times for the same table name. Which approach improves performance by avoiding repeated parsing?
Think about how PostgreSQL handles query planning and execution.
Preparing a statement once and executing it multiple times avoids repeated parsing and planning, improving performance for repeated dynamic queries.
Given the following PL/pgSQL code snippet, what is the cause of the error?
DECLARE tablename text := 'users'; result integer; BEGIN EXECUTE 'SELECT count(*) FROM tablename' INTO result; RETURN result; END;
Check how variables are included in dynamic SQL strings.
The string 'SELECT count(*) FROM tablename' is taken literally, so PostgreSQL looks for a table named 'tablename', which likely does not exist. The variable must be concatenated or formatted into the string.
Which of the following statements best explains a security risk when using dynamic SQL with EXECUTE in PostgreSQL?
Think about how user input can affect SQL commands.
If user input is concatenated directly into dynamic SQL without using functions like quote_ident or quote_literal, attackers can inject malicious SQL code, causing security breaches.