Which queries use the most time in your database? Guessing doesn't work. The pg stat statements extension records every query shape, how often it ran, and how long it took.
We create the extension, reset it, and run a few queries. Then we ask for the top queries by total time. Similar queries are grouped, with values replaced by dollar signs. Run it. The heaviest query shapes, with call counts.
query.sqlsql
CREATE EXTENSION pg_stat_statements;SELECT pg_stat_statements_reset() IS NOT NULL AS reset;SELECT count(*) FROM orders WHERE customer_id = 7 \g /dev/nullSELECT count(*) FROM orders WHERE customer_id = 8 \g /dev/nullSELECT title FROM books WHERE book_id = 3 \g /dev/nullSELECT calls, round(total_exec_time::numeric, 3) AS ms, left(query, 50) AS queryFROM pg_stat_statementsWHERE query LIKE 'SELECT%FROM orders%' OR query LIKE 'SELECT title%'ORDER BY total_exec_time DESC;
Output
CREATE EXTENSION
reset
-------
t
(1 row)
calls | ms | query
-------+-------+----------------------------------------------------
2 | 0.096 | SELECT count(*) FROM orders WHERE customer_id = $1
1 | 0.008 | SELECT title FROM books WHERE book_id = $1
(2 rows)
Total time shows which queries cost the most overall. Mean time shows which are slow each time. Calls shows how often. Fix the top few, and you'll often fix most of the load.