Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get a history of queries made in postgres

Is it possible to get a history of queries made in postgres? and is it be possible to get the time it took for each query? I'm currently trying to identify slow queries in the application I'm working on.

I'm using Postgres 8.3.5

like image 957
Chiwai Chan Avatar asked Oct 06 '09 03:10

Chiwai Chan


People also ask

How do you get query history in pgAdmin 4?

The upper panel displays the SQL Editor. You can use the panel to enter, edit, or execute a query. It also shows the History tab which can be used to view the queries that have been executed in the session, and a Scratch Pad which can be used to hold text snippets during editing.


1 Answers

There's no history in the database itself, if you're using psql you can use "\s" to see your command history there.

You can get future queries or other types of operations into the log files by setting log_statement in the postgresql.conf file. What you probably want instead is log_min_duration_statement, which if you set it to 0 will log all queries and their durations in the logs. That can be helpful once your apps goes live, if you set that to a higher value you'll only see the long running queries which can be helpful for optimization (you can run EXPLAIN ANALYZE on the queries you find there to figure out why they're slow).

Another handy thing to know in this area is that if you run psql and tell it "\timing", it will show how long every statement after that takes. So if you have a sql file that looks like this:

\timing select 1; 

You can run it with the right flags and see each statement interleaved with how long it took. Here's how and what the result looks like:

$ psql -ef test.sql  Timing is on. select 1;  ?column?  ----------         1 (1 row)  Time: 1.196 ms 

This is handy because you don't need to be database superuser to use it, unlike changing the config file, and it's easier to use if you're developing new code and want to test it out.

like image 64
Greg Smith Avatar answered Oct 03 '22 01:10

Greg Smith