This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Are you facing performance related issues in PostgreSQL?
Do you want to know all your SQL Query Execution Statistics like: How many times same query executed, What is total and average time for queries and others.
If you are looking for these questions, this post is very helpful for you.
PostgreSQL provides pg_stat_statements module or extension which automatically records different types of statistic all running queries.
During the activity of Performance Optimization, We are always keen for long running queries of our Database Server.
We should configure pg_stat_statements module so that we can easily use require statistics for Performance Tuning.
Steps to configure and enable pg_stat_statements module:
First, Install pg_stat_statements Extension:
1 |
CREATE EXTENSION pg_stat_statements; |
Once we install the extension, It starts to log require query execution information in pg_stat_statements table.
Select the data of pg_stat_statements:
1 |
SELECT *FROM pg_stat_statements; |
If you get a below error, require to change few parameters in postgresql.conf file:
1 |
ERROR: pg_stat_statements must be loaded via shared_preload_libraries |
You can solve above error by changing this parameter in postgresql.conf file.
After changes in postgresql.conf, restart PostgreSQL service.
1 2 3 |
shared_preload_libraries = 'pg_stat_statements' pg_stat_statements.max = 10000 pg_stat_statements.track = all |
Execute few sample queries to check, how pg_stat_statements works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
CREATE TABLE tbl_ItemTransactions ( TranID SERIAL ,TransactionDate TIMESTAMPTZ ,TransactionName TEXT ); INSERT INTO tbl_ItemTransactions (TransactionDate, TransactionName) SELECT x, 'dbrnd' FROM generate_series('2016-01-01 00:00:00'::timestamptz, '2016-12-31 23:59:59'::timestamptz,'2 seconds'::interval) a(x); SELECT COUNT(1) FROM tbl_ItemTransactions; SELECT *FROM tbl_ItemTransactions WHERE TransactionDate BETWEEN '2016-02-08' AND '2016-04-08'; |
Check the tracked statistics in pg_stat_statements:
1 |
SELECT *FROM pg_stat_statements; |
Using below function, You can also reset pg_stat_statements:
1 |
SELECT *FROM pg_stat_statements_reset(); |