SQL performance analysis

Updated at:

When slow SQL queries occur or SQL statements consume excessive memory, use the tools described in this document to identify and analyze the problem.

Identify slow SQL statements

PolarDB for Oracle provides two methods for finding slow SQL statements, depending on whether the query has already finished.

Find slow statements that have finished

Query the pg_stat_statements view to rank completed statements by average execution time:

SELECT total_time / calls AS avg, query
FROM pg_stat_statements
ORDER BY avg DESC
LIMIT 10;

This returns the 10 statements with the highest average execution time, in descending order.

Find slow statements that are still running

Query pg_stat_activity to find statements that have been running for more than 1 second:

SELECT *
FROM pg_stat_activity
WHERE state <> 'idle'
  AND now() - query_start > interval '1 s'
ORDER BY query_start;

Analyze execution plans with EXPLAIN

EXPLAIN returns the execution plan for a SQL statement without running it. Use the plan to understand which operations consume the most time or resources.

Warning

EXPLAIN ANALYZE executes the statement and returns real runtime statistics. For statements that modify data (INSERT, UPDATE, DELETE), wrap them in a transaction and roll back after analysis to avoid unintended changes:

BEGIN;
EXPLAIN ANALYZE UPDATE orders SET status = 'closed' WHERE id = 1;
ROLLBACK;

Syntax

EXPLAIN [ ( option [, ...] ) ] statement
EXPLAIN [ ANALYZE ] [ VERBOSE ] statement

where option can be one of:
    ANALYZE [ boolean ]
    VERBOSE [ boolean ]
    COSTS  [ boolean ]
    BUFFERS [ boolean ]
    FORMAT { TEXT | XML | JSON | YAML }

Read EXPLAIN output

A typical EXPLAIN output line looks like this:

Seq Scan on orders  (cost=0.00..520.00 rows=10000 width=128)

The four values in parentheses mean (left to right):

  1. Startup cost — estimated cost before the first row is returned

  2. Total cost — estimated cost to return all rows

  3. Estimated rows — estimated number of rows returned by this node

  4. Estimated row width — estimated average width of each row, in bytes

Cost values are in arbitrary planner units, not milliseconds. When you run EXPLAIN ANALYZE, the output adds actual runtime values:

Seq Scan on orders  (cost=0.00..520.00 rows=10000 width=128)
                    (actual time=0.021..12.340 rows=9870 loops=1)

The most important thing to check is whether the estimated row count is close to the actual row count. Large discrepancies indicate stale statistics and can lead to poor plan choices.

Options

OptionDefaultDescription
ANALYZEFALSEExecutes the statement and returns actual runtime statistics alongside estimates.
VERBOSEFALSEAdds extra detail: output column list per node, table schema, function schema, column alias, and any trigger names called.
COSTSTRUEDisplays estimated startup cost, total cost, estimated row count, and estimated row width per plan node.
BUFFERSFALSEDisplays buffer usage per plan node (hit, updated, and removed blocks across shared, local, and temporary blocks). Requires ANALYZE TRUE.
FORMATTEXTOutput format. TEXT is human-readable. XML, JSON, and YAML are easier to parse programmatically. All formats return the same information.

Buffer types:

Buffer typeContains
Shared blocksData from regular tables and indexes
Local blocksData from temporary tables and their indexes
Temporary blocksShort-term data used by sorts, hashes, and similar operations

Analyze resource usage with views

The pg_stat_statements and polar_stat_sql extensions provide detailed resource consumption metrics for SQL statements. Enable both before use.

Set up the extensions

CREATE EXTENSION pg_stat_statements;
CREATE EXTENSION polar_stat_sql;
ALTER SYSTEM SET polar_stat_sql.enable_stat = on;
ALTER SYSTEM SET polar_stat_sql.enable_qps_monitor = on;
SELECT pg_reload_conf();

Expected output:

 pg_reload_conf
----------------
 t
(1 row)

pg_stat_statements

pg_stat_statements tracks cumulative execution statistics across all statements. For details on its columns and usage, see pg_stat_statements.

polar_stat_sql

polar_stat_sql provides deeper per-statement diagnostics organized into four categories:

CategoryWhat it tracks
Execution plan node statsNode-level metrics for scans, joins, aggregations, sorts, and hashes
Resource usageCPU time (system and user mode), I/O (read/write bytes), memory (requested pages and page swaps), the number of received and requested inter-process communication (IPC) messages, and voluntary and involuntary CPU context switches
Phase timingTime spent in each phase: parsing, analyzing, rewriting, planning, and executing
Latch and lock statsLatch and lock contention metrics

polar_stat_sql records accumulated data. To get accurate measurements for a specific statement, reset the counters before running it:

SELECT polar_stat_sql_reset();

Expected output:

 polar_stat_sql_reset
----------------------

(1 row)

What's next

After identifying slow or resource-intensive statements, consider:

  • Adding or updating indexes based on the scan and join patterns shown in EXPLAIN output

  • Running ANALYZE on affected tables to refresh planner statistics

  • Reviewing polar_stat_sql phase timing to determine whether bottlenecks are in parsing, planning, or execution