Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: How to pass parameters from command line?

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' }; 
like image 304
vol7ron Avatar asked Sep 12 '11 14:09

vol7ron


People also ask

How do I run a SQL script in PostgreSQL?

Another easiest and most used way to run any SQL file in PostgreSQL is via its SQL shell. Open the SQL shell from the menu bar of Windows 10. Add your server name, database name where you want to import the file, the port number you are currently active on, PostgreSQL username, and password to start using SQL shell.

What does <> mean in PostgreSQL?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.


1 Answers

You can use the -v construct e.g

psql -v v1=12  -v v2="'Hello World'" -v v3="'2010-11-12'" 

and then refer to the variables in sql as :v1, :v2 etc

select * from table_1 where id = :v1; 

Please pay attention on how we pass string/date value using two quotes " '...' "

like image 67
Gavin Avatar answered Oct 07 '22 04:10

Gavin