I have a somewhat detailed query in a script that uses ? placeholders. I wanted to test this same query directly from the psql command line (outside the script). I want to avoid going in and replacing all the ? with actual values, instead I’d like to pass the arguments after the query.
Example:
SELECT *
FROM foobar
WHERE foo = ?
AND bar = ?
OR baz = ? ;
Looking for something like:
%> {select * from foobar where foo=? and bar=? or baz=? , 'foo','bar','baz' };
You can use the
-voption e.g:and then refer to the variables in SQL as
:v1,:v2etc:Please pay attention to how we pass string/date values using two quotes
" '...' "But this way of interpolation is prone to SQL injections, because it’s you who’s responsible for quoting. E.g. need to include a single quote?-v v2="'don''t do this'".A better/safer way is to let PostgreSQL handle it: