3

I am running a psql command that executes a complex query. There's nothing that query produces, as such, psql returns "(No rows)" in the output.

Is there a way to make psql to return an empty string?

I've tried using --pset=tuples-only=on and --pset=footer=off and -q in all variations, and it doesn't seem to work.

Footer option works while in psql shell prompt, but doesn't work from script.

Tried on 9.1.7, need this for 8.4, 9.1 and 9.2.

Alex
  • 897
  • 1
  • 11
  • 21

2 Answers2

2

May be good enough:

$ psql -Axt -c 'select 1 where 1=0'

produces an empty string

EDIT following comments: The command above produces an empty line, so that includes and end-of-line.

To produce nothing at all, remove the -x option.

Not that it would make any difference to the shell anyway, as shown below:

with -x:

r=`psql -Atx -d test -c "select 1 where 1=0"`  
echo $r | od -c  
0000000  \n  
0000001  

without -x:

r=`psql -At -d test -c "select 1 where 1=0"`
echo $r | od -c
0000000  \n
0000001
Daniel Vérité
  • 58,074
  • 15
  • 129
  • 156
  • This doesn't produce an empty string, it produces "no row" - which constitutes Alex' problem. `SELECT ''` produces an empty string. – Erwin Brandstetter Jan 18 '13 at 01:50
  • wfm; i just get a blank line, 9.2.2 – Eevee Jan 18 '13 at 02:07
  • 1
    OK, if you want NO line, then use psql -Atc "select '';" or select where 1=0 etc. If you use -Atxc then you will get a line because that's the expanded output. I use psql -Atc in bash scripts all the time because no headers or footers and you only get back one line per row. Using a proper read syntax with bash you can split each line into individual vars in bash btw. – Scott Marlowe Jan 18 '13 at 07:14
  • @Erwin: I can't see why you get "no rows". I don't and apparently others don't as well. – Daniel Vérité Jan 18 '13 at 10:45
  • @DanielVérité: Well, you are right since psql with the -x option inserts a line break for "no rows" as Scott explains. And that ends up to be the same as you detailed in your addendum. But it also changes the output format - which doesn't matter as long as the query returns no rows. – Erwin Brandstetter Jan 18 '13 at 19:20
2

Is there a way to make psql to return an empty string?

You can simply append SELECT '' after the first query. Ex.:

psql -Atp5432 mydb -c "SELECT 1 WHERE FALSE; SELECT ''"

Replace SELECT 1 WHERE FALSE with your complex query that doesn't return a row.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228