Naresh
Naresh

Reputation: 25763

How to run a parameterized query from the PostgreSQL command line

I want to run the following parameterized query from the psql command line:

SELECT *
FROM users
WHERE username = :username;

How do I set the username parameter on the command line?

I tried this:

\set username 'john'

But when I run the query, I get the following error message:

ERROR:  column "john" does not exist
LINE 3: WHERE username = john;
                         ^

Upvotes: 11

Views: 7239

Answers (1)

Craig Ringer
Craig Ringer

Reputation: 324375

Per the psql documentation, to substitute a psql variable into a string as a literal, use :'variablename'

This isn't really a parameterised query in the usual sense, as the variable is interpolated into the query string. psql knows to escape single quotes, though, so a variable value ');DROP TABLE users;-- will appear literally instead of ending the string and running unwanted SQL.

Upvotes: 8

Related Questions