Search code examples
databasepostgresqlpsql

Using psql command line within powershell - and formatting the output


I'm using this command within a powershell script to extract a single value into a file

.\psql -U myowner -d myDB -c "SELECT last_value FROM pg_sequences WHERE sequencename ='mytest'" -o c:\test.dat

This works OK, and dumps the output to test.dat as follows

 last_value
-------------
 13446137112
(1 row)

How do I loose the column header and the footer? I just want the value alone, no bumpf. i.e. just a file containing

 13446137112

I could probably hack something with powershell, but was hoping for a more elegant formatting option within psql

(psql v13.1, powershell v5.1, windows 11)

UPDATE - Abdul Azizs' answer is correct (thank-you). '-t' strips out the header and footer. Bonus points for striping off the leading spaces and extra blank lines


Solution

  • You can add in the -t / --tuples-only flag to enable tuples-only, this suppresses the column names and footers.

    .\psql -U myowner -d myDB -t -c "SELECT last_value FROM pg_sequences WHERE sequencename ='mytest'" -o c:\test.dat
    

    With the -t option, psql will output only the tuple data without the column header and footer.

    Check out PostgreSQL's app-psql for more info.