Your examples are little bit messy.
The first example is wrong - probably incorrect use of IN
keyword, and quote_literal()
is absolutely useless in this context. The second one is probably wrong too - if val1
is a variable. plpgsql variables are not visible inside the SQL string in an EXECUTE
statement. Next issue is INTO
in the SQL string.
postgres=# do $$
DECLARE rc int;
val1 varchar := 'Hello';
BEGIN
rc := (SELECT count(*) FROM xxx WHERE xxx.v = val1);
RAISE NOTICE '%', rc;
EXECUTE 'SELECT count(*) FROM xxx WHERE xxx.v = $1'
USING val1 INTO rc;
RAISE NOTICE '%', rc;
END;
$$;
NOTICE: 1
NOTICE: 1
DO
quote_literal()
is usually necessary for dynamic SQL, when you cannot use a USING
clause. In your example:
EXECUTE 'SELECT count(*) FROM xxx WHERE xxx.v = ' || quote_literal(val1)
INTO ...
It protects against SQL injection and ensures proper escaping.
Modern releases have the format()
function:
EXECUTE format('SELECT count(*) FROM xxx WHERE xxx.v = %L', val1) INTO ...
But EXECUTE ... USING
should be preferred.