SQL

Updated at:

PolarDB for PostgreSQL (Compatible with Oracle) provides three views for monitoring SQL performance. Query these views to identify slow queries, high-resource statements, and execution bottlenecks.

ViewPurposeRequires
pg_stat_statementsTracks execution time, row counts, and block I/O per SQL statementpg_stat_statements plug-in
polar_stat_sqlExtends pg_stat_statements with CPU usage, lock waits, query plan node stats, and storage I/O metricspolar_stat_sql plug-in
polar_stat_query_countAggregates execution counts by SQL type (DQL, DML, DDL, DCL)polar_stat_sql plug-in

Start with pg_stat_statements for general query performance analysis. Use polar_stat_sql when you need deeper diagnostics—CPU time, lock contention, or I/O latency at the statement level. Use polar_stat_query_count for a high-level workload overview.

pg_stat_statements

pg_stat_statements records execution statistics for every distinct SQL statement, normalized by query structure. Use it to find slow queries and high-frequency statements.

Prerequisites

Before querying this view, create the plug-in:

CREATE EXTENSION pg_stat_statements;

Parameters

ParameterTypeDescription
useridoidObject identifier (OID) of the user who ran the statement
dbidoidOID of the database where the statement ran
queryidbigintInternal hash code derived from the statement's parse tree
querytextNormalized text of the SQL statement
callsbigintNumber of times the statement was executed
total_timedouble precisionTotal execution time. Unit: milliseconds
min_timedouble precisionShortest single execution time. Unit: milliseconds
max_timedouble precisionLongest single execution time. Unit: milliseconds
mean_timedouble precisionAverage execution time. Unit: milliseconds
stddev_timedouble precisionPopulation standard deviation of execution time. Unit: milliseconds
rowsbigintTotal rows retrieved or affected
shared_blks_hitbigintTotal shared-block cache hits
shared_blks_readbigintTotal shared blocks read by the statement
shared_blks_dirtiedbigintTotal shared blocks dirtied
shared_blks_writtenbigintTotal shared blocks written
local_blks_hitbigintTotal local-block cache hits
local_blks_readbigintTotal local blocks read by the statement
local_blks_dirtiedbigintTotal local blocks dirtied
local_blks_writtenbigintTotal local blocks written
temp_blks_readbigintTotal temporary blocks read
temp_blks_writtenbigintTotal temporary blocks written
blk_read_timedouble precisionTotal time spent reading blocks. Unit: milliseconds. Non-zero only when track_io_timing is set to on
blk_write_timedouble precisionTotal time spent writing blocks. Unit: milliseconds. Non-zero only when track_io_timing is set to on

Query examples

Find the slowest queries by average execution time:

SELECT
    query,
    calls,
    mean_time AS avg_ms,
    max_time AS max_ms
FROM pg_stat_statements
ORDER BY mean_time DESC
LIMIT 10;

Find the most frequently executed queries:

SELECT
    query,
    calls,
    total_time,
    mean_time AS avg_ms
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 10;

Find queries with the highest disk read volume (potential index candidates):

SELECT
    query,
    calls,
    shared_blks_read,
    shared_blks_hit,
    100.0 * shared_blks_hit / NULLIF(shared_blks_hit + shared_blks_read, 0) AS cache_hit_pct
FROM pg_stat_statements
ORDER BY shared_blks_read DESC
LIMIT 10;

polar_stat_sql

polar_stat_sql extends pg_stat_statements with additional metrics: CPU usage, memory, OS-level I/O, query plan node statistics, lock wait times, and storage layer I/O. Use it when pg_stat_statements points to a problem but you need to pinpoint the root cause.

Prerequisites

Before querying this view, create the plug-in:

CREATE EXTENSION polar_stat_sql;

Parameters

Identity

ParameterTypeDescription
queryidbigintQuery ID, matches queryid in pg_stat_statements
datnamenameDatabase name
rolnamenameUsername

CPU and memory

ParameterTypeDescription
user_timedoubleTime spent in user mode
system_timedoubleTime spent in system (kernel) mode
minfltsbigintNumber of recycled pages or minor faults
majfltsbigintNumber of major page faults
nswapsbigintNumber of page swaps

OS-level I/O

ParameterTypeDescription
readsbigintBytes read from disk
reads_blksbigintBlocks read from disk
writesbigintBytes written to disk
writes_blksbigintBlocks written to disk
io_open_numbigintNumber of file open operations
io_seek_countbigintNumber of file seek operations
io_open_timedoubleTime spent on file open operations. Unit: microseconds
io_seek_timedoubleTime spent on file seek operations. Unit: microseconds

IPC and context switches

ParameterTypeDescription
msgsndsbigintIPC messages sent
msgrcvsbigintIPC messages received
nsignalsbigintSemaphores received
nvcswsbigintVoluntary context switches
nivcswsbigintInvoluntary context switches

Query plan node statistics

All rows, time, and count metrics below correspond to operations in the query execution plan.

ParameterTypeDescription
scan_rowsdoubleRows read by scan node operations
scan_timedoubleTime spent on scan node operations
scan_countbigintNumber of scan node operations
join_rowsdoubleRows read by join node operations
join_timedoubleTime spent on join node operations
join_countbigintNumber of join node operations
sort_rowsdoubleRows read by sort node operations
sort_timedoubleTime spent on sort node operations
sort_countbigintNumber of sort node operations
group_rowsdoubleRows read by group node operations
group_timedoubleTime spent on group node operations
group_countbigintNumber of group node operations
hash_rowsdoubleRows read by hash node operations
hash_memorybigintMemory used by hash node operations. Unit: bytes
hash_countbigintNumber of hash node operations

Parsing and planning time

ParameterTypeDescription
parse_timedoubleTime spent parsing the SQL statement
analyze_timedoubleTime spent analyzing the SQL statement
rewrite_timedoubleTime spent rewriting the SQL statement
plan_timedoubleTime spent generating the execution plan
execute_timedoubleTime at which the statement was executed

Lock waits

ParameterTypeDescription
lwlock_waitdoubleLightweight lock (lwlock) wait time
rel_lock_waitdoubleTable lock wait time
xact_lock_waitdoubleTransaction lock wait time
page_lock_waitdoublePage lock wait time
tuple_lock_waitdoubleRow lock wait time

Storage I/O

ParameterTypeDescription
shared_read_psbigintRead IOPS
shared_write_psbigintWrite IOPS
shared_read_throughputbigintRead throughput. Unit: bytes
shared_write_throughputbigintWrite throughput. Unit: bytes
shared_read_latencydoubleRead latency. Unit: microseconds
shared_write_latencydoubleWrite latency. Unit: microseconds

Diagnosing performance issues

Use the following observations and queries to investigate specific performance problems.

ObservationLikely causeAction
High lwlock_wait or rel_lock_waitLock contention between concurrent sessionsIdentify conflicting queries by joining with pg_stat_statements on queryid; review transaction isolation levels or reduce lock scope
High shared_read_latency or large reads_blksExcessive disk reads; missing index or low cache hit rateCheck pg_stat_statements.shared_blks_read for the same queryid; consider adding an index or increasing shared_buffers
High majfltsMemory pressure causing pagingReview memory allocation for the workload; check hash_memory for hash-heavy queries
High sort_time or hash_memorySpill to disk during sort or hash operationsIncrease work_mem for affected sessions
High plan_time relative to execute_timeFrequent re-planning of the same queryUse prepared statements to cache query plans

polar_stat_query_count

polar_stat_query_count provides an aggregate count of executed statements grouped by SQL type and command type. Use it for a quick workload overview—for example, to see whether your database is read-heavy or write-heavy.

Prerequisites

Before querying this view, create the polar_stat_sql plug-in:

CREATE EXTENSION polar_stat_sql;

Parameters

ParameterTypeDescription
sqltypetextSQL language category. Valid values: DQL, DML, DDL, DCL
cmdtypetextSpecific command type. Examples: SELECT, INSERT, UPDATE
countbigintTotal number of executions

Query example

Get an overview of workload distribution by SQL type:

SELECT sqltype, cmdtype, count
FROM polar_stat_query_count
ORDER BY count DESC;