2

There is already a question "How can I time SQL-queries using psql?" but I am missing answer how to do that from command line. How to run script with (optional) timing from command line – without \timing [on|off] in the script, please?

asked Aug 6, 2014 at 9:44

1 Answer 1

6

You could use the shell command time

postgres@db:$ time psql db -c 'SELECT 1'
 ?column?
----------
 1
(1 row)
real 0m0.108s
user 0m0.040s
sys 0m0.032s

Or, to combine a meta command with an SQL command, you could pipe a string to psql:

postgres@db:~/script$ echo '\timing \\ SELECT 1;' | LANG=C psql
Timing is on.
 ?column?
----------
 1
(1 row)
Time: 0.000 ms

The manual:

The special sequence \\ (two backslashes) marks the end of arguments and continues parsing SQL commands, if any. That way SQL and psql commands can be freely mixed on a line. But in any case, the arguments of a meta-command cannot continue beyond the end of the line.

More options:

answered Aug 6, 2014 at 9:52
1
  • 3
    The time command would measure whole script not each query. Inspired by the second suggestion: { echo '\timing on;'; cat file.sql } |psql. Commented May 1, 2015 at 17:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.