pg_stat_statements Query Builder

pg_stat_statements is the fastest way to find out what a PostgreSQL server actually spends its time on, but the column names have moved twice: PostgreSQL 13 renamed total_time to total_exec_time when it split planning from execution, and PostgreSQL 17 renamed blk_read_time to shared_blk_read_time. That is why the query you copied from a blog post errors with "column does not exist". Pick your major version and what you are hunting for, and this builder writes the Top-N query with the right column names, the percentage-of-total column, a cache hit ratio, the filters that keep BEGIN and COMMIT out of the results, plus the extension setup and the reset commands. It all runs in your browser.

Do more than pg_stat_statements query builder — meet Chat2DB

Chat2DB is an AI-powered SQL client for Windows, macOS and Linux. Write SQL in natural language, format and optimize queries automatically, and manage MySQL, PostgreSQL, Oracle and 20+ other databases in one workspace.

How to use

  1. Select your PostgreSQL major version so the generated query uses the column names your server actually has.
  2. Choose what you are looking for - total time for load, mean time for a slow statement, temp blocks for queries spilling to disk - and set the row limit and minimum call count.
  3. Run the setup block once if the extension is not installed yet, then run the generated query and EXPLAIN the statements it puts at the top.

Frequently asked questions

Why does my pg_stat_statements query fail with "column total_time does not exist"?

Because you are on PostgreSQL 13 or newer and the query was written for 12 or older. Version 13 separated planning time from execution time, so total_time became total_exec_time, mean_time became mean_exec_time, min_time and max_time and stddev_time gained the same _exec_ infix, and new total_plan_time and mean_plan_time columns appeared. Version 17 made a second rename in the IO columns: blk_read_time and blk_write_time became shared_blk_read_time and shared_blk_write_time, with separate local_blk_ and temp_blk_ variants alongside them. Neither change is backward compatible, which is why monitoring scripts and blog snippets break silently across upgrades. Select your major version above and the generated SQL uses the correct spelling.

How do I enable pg_stat_statements?

It ships with PostgreSQL as a contrib module but is not active by default, because it needs shared memory allocated at startup. Add pg_stat_statements to shared_preload_libraries in postgresql.conf and restart the server - a reload is not enough for this parameter. Then run CREATE EXTENSION pg_stat_statements once in each database where you want to query the view. Set track_io_timing = on as well if you want the read and write time columns to hold anything other than zero. On managed services the steps differ slightly: on Amazon RDS and Aurora you add it to shared_preload_libraries in the parameter group and reboot, on Azure Database for PostgreSQL and Cloud SQL it is a server flag, and on several platforms the extension is already enabled. Non-superusers need membership in pg_read_all_stats to see statements from other users; without it they only see their own.

Should I sort by total_exec_time or mean_exec_time?

Sort by total_exec_time when you want to reduce load, and by mean_exec_time when you are chasing a specific slow statement a user complained about. The distinction matters more than it sounds: a 4 ms query executed two million times an hour consumes far more of the server than a 3-second report that runs twice a day, but a mean-time sort puts the report on top and buries the query that is actually saturating your CPU. A good habit is to read the total-time list first, then look at the max and stddev columns on those rows. A statement whose mean is 5 ms but whose max is 9 seconds is not a slow query - it is a query with an unstable plan or a locking problem, and the fix is different. Once you have the statement text, EXPLAIN (ANALYZE, BUFFERS) tells you why. Chat2DB can run these monitoring queries and the EXPLAIN side by side against the same connection: download it at https://chat2db.ai/download or use the web version at https://app.chat2db.ai.

More free SQL tools

SQL Formatter & Beautifier
Format and beautify SQL queries online with dialect-aware indentation and keyword casing.
SQL Validator & Syntax Checker
Check SQL syntax online for MySQL, PostgreSQL and more, with clear error messages.
SQL Minifier
Minify SQL by stripping comments and collapsing whitespace into a single line.
MySQL to PostgreSQL Converter
Convert MySQL DDL and queries to PostgreSQL syntax with a best-effort dialect translator.
CSV to SQL Converter
Turn CSV, TSV or pasted Excel data into SQL INSERT statements.
JSON to SQL Converter
Convert a JSON array of objects into SQL INSERT statements.
SQL IN Clause Generator
Paste a list of values and get a ready-to-use SQL IN (...) clause.
SQL Escape & Unescape
Escape single quotes and special characters for safe SQL string literals.
JDBC Connection String Builder
Build JDBC URLs for MySQL, PostgreSQL, SQL Server, Oracle, MariaDB and ClickHouse.
SQL Cheat Sheet
A practical SQL reference: joins, aggregation, window functions, DDL and dialect differences.
UUID Generator (v4 & v7)
Generate UUID v4 and time-ordered UUID v7 in bulk, as plain text, JSON, CSV or SQL.
Cron Expression Generator & Validator
Build and validate cron expressions with plain-English explanations and next run times.
PostgreSQL EXPLAIN Plan Visualizer
Turn EXPLAIN ANALYZE output into a readable plan tree with timings and tuning warnings.
PgBouncer Config Generator
Generate pgbouncer.ini and size connection pools from your app instances and CPU cores.
PostgreSQL Partition Table Generator
Generate RANGE, LIST and HASH partitioning DDL with child partitions and maintenance SQL.
pg_dump Command Generator
Build pg_dump and pg_restore commands with format, filter and parallel job options.
mysqldump Command Generator
Build mysqldump backup commands with scope, options and a matching restore command.
SQL Test Data Generator
Generate realistic fake rows as SQL INSERT statements, CSV or JSON, right in your browser.
PostgreSQL Config Calculator
Calculate tuned postgresql.conf settings from your RAM, CPU cores, connections and workload.
SQL DDL to Code Generator
Convert CREATE TABLE statements into TypeScript, Prisma, Drizzle, Go, JPA or SQLAlchemy models.
SQL Window Function Generator
Build ROW_NUMBER, RANK, LAG, LEAD and running-total OVER() clauses with PARTITION BY and frames.
Docker Compose PostgreSQL Generator
Generate a docker-compose.yml for PostgreSQL with volumes, healthchecks, init scripts and pgAdmin.
PostgreSQL Replication Config Generator
Generate streaming and logical replication config: postgresql.conf, pg_hba.conf, slots and pg_basebackup.
SQL Injection Checker
Scan code for SQL injection risks and rewrite unsafe queries with bound parameters.
SQL to ER Diagram Generator
Paste CREATE TABLE DDL and get an entity relationship diagram plus Mermaid erDiagram code.
Postgres Connection String Generator
Build PostgreSQL connection strings: libpq URI, DSN, JDBC, psycopg, SQLAlchemy, Npgsql and .env.
Postgres GRANT Statement Generator
Generate PostgreSQL GRANT, ALTER DEFAULT PRIVILEGES and REVOKE scripts for read-only or read-write roles.
Postgres COPY Command Generator
Build PostgreSQL COPY and psql \copy commands to import or export CSV with HEADER, DELIMITER, NULL and WHERE options.
Postgres CREATE INDEX Generator
Generate PostgreSQL CREATE INDEX statements: B-tree, GIN, GiST, BRIN, UNIQUE, CONCURRENTLY, partial WHERE, INCLUDE and expression indexes.
Postgres TO_CHAR Date Format Builder
Build PostgreSQL TO_CHAR date format patterns with live preview, presets and generated TO_CHAR / TO_TIMESTAMP statements.
Postgres FDW Setup Generator
Generate postgres_fdw CREATE SERVER, USER MAPPING and IMPORT FOREIGN SCHEMA SQL for querying a remote Postgres database.
Postgres EXCLUDE Constraint Generator
Generate PostgreSQL EXCLUDE constraint SQL: GiST/SP-GiST operators, btree_gist columns, partial WHERE and overlap-check verification.
pgvector Index & Schema Generator
Generate pgvector SQL: vector/halfvec columns, HNSW or IVFFlat indexes, tuned parameters and the matching nearest-neighbour query.
Postgres ALTER COLUMN TYPE Generator
Generate ALTER TABLE ALTER COLUMN TYPE SQL with the right USING cast, a table-rewrite verdict and a batched zero-downtime migration.
Postgres UPSERT Generator
Build INSERT ... ON CONFLICT DO UPDATE/DO NOTHING statements, the MERGE equivalent and the unique index they need.
pg_hba.conf Generator
Generate PostgreSQL client authentication rules with the right connection type, CIDR and auth method.
Postgres Trigger Generator
Generate CREATE TRIGGER SQL and plpgsql trigger functions: updated_at touch, JSONB audit log, operation guards and TG_OP skeletons.
Postgres VACUUM Command Generator
Build VACUUM / VACUUM FULL / ANALYZE commands with the right options, plus monitoring SQL and per-table autovacuum tuning.
SQL Pivot Generator (Rows to Columns)
Generate pivot queries with FILTER or CASE WHEN aggregates, the PostgreSQL crosstab() version and the reverse unpivot.
Epoch & Unix Timestamp Converter
Convert epoch to date and back with auto unit detection, plus to_timestamp and extract(epoch) SQL snippets.
pg_restore Command Generator
Build pg_restore or psql restore commands from a Postgres dump: archive format, parallel jobs, clean, no-owner and single-transaction options.
Postgres JSONB Query Builder
Generate JSONB queries from a nested path and operator, with the matching GIN or expression index and a JSONB cookbook.
SQL Schema Diff & Migration Generator
Compare two SQL schemas and generate the ALTER TABLE up and down migration, with lock and rewrite warnings.
Postgres Table Size Estimator
Estimate table and index size from your columns and row count, including tuple header, alignment padding and column-order savings.
Postgres Full Text Search Generator
Generate tsvector columns, GIN indexes, weighted ranking and ts_headline queries for PostgreSQL full text search.
Levenshtein Distance Calculator
Compute edit distance between two strings with the full DP matrix, edit path and matching Postgres fuzzy search SQL.
SQL Linter & Style Checker
Lint SQL for correctness traps, non-sargable predicates and style issues in your browser.
Database Normalization Analyzer
Find candidate keys and 1NF/2NF/3NF/BCNF violations, then get a lossless decomposition.
Connection Pool Size Calculator
Size your database connection pool from cores, latency and instances, with HikariCP, pgxpool, node-pg, SQLAlchemy and PgBouncer config.
PostgreSQL Error Code Lookup
Look up any SQLSTATE code or paste an error message to get the cause, the fix and how to catch it in your driver.
Postgres Autovacuum Calculator
Work out when autovacuum fires on a table, how much bloat builds up first, and generate per-table ALTER TABLE tuning.
SQL to MongoDB Query Converter
Convert a SQL SELECT into a MongoDB find() call or aggregation pipeline, with $lookup, $group, $match and $sort mapping.
pgloader Config Generator
Build a pgloader .load file to migrate MySQL, SQL Server, SQLite or CSV into PostgreSQL, with cast rules, table filters and verification SQL.
Postgres Upgrade Planner
Compare pg_upgrade, dump/restore and logical replication for a major version upgrade, with downtime estimates, commands and breaking changes.
SQL Join Visualizer
See INNER, LEFT, RIGHT, FULL, CROSS and anti joins run on real sample rows, with the SQL.
SCD Type 2 SQL Generator
Generate slowly changing dimension Type 2 DDL and load SQL for Postgres, Snowflake and BigQuery.
Postgres RLS Policy Generator
Generate PostgreSQL row level security policies for multi-tenant, per-user or role-based access.
Postgres Data Masking Generator
Build masked views, anonymization UPDATEs or PostgreSQL Anonymizer labels for sensitive columns.
Online SQL Playground
Run SQL in your browser against a sample SQLite database, with 10 checked practice exercises.
SQL CASE WHEN Generator
Build searched or simple CASE expressions with full queries and IF/IIF/DECODE equivalents per dialect.
SQL Set Operations Visualizer
See UNION, UNION ALL, INTERSECT and EXCEPT run on real rows, with counts and SQL per dialect.
Postgres Enum Type Generator
Generate CREATE TYPE, ADD VALUE, RENAME VALUE, safe value removal and enum-to-CHECK or lookup migrations.
Postgres Lock Conflict Checker
Check whether two PostgreSQL statements or LOCK TABLE modes block each other, with the conflict matrix and pg_locks queries.
Postgres Timezone Converter
Convert timestamps between IANA zones and generate AT TIME ZONE, SET timezone and date_trunc SQL with DST warnings.
Slow Query Log Analyzer
Group a MySQL or PostgreSQL slow query log by normalized query shape and rank the shapes by total time.
Postgres generate_series Builder
Build generate_series SQL for calendar tables, time buckets, gap-filled reports and test data, with a row preview.
Postgres Index Type Advisor
Pick between B-tree, Hash, GIN, GiST, SP-GiST, BRIN and HNSW for a column and query pattern, with the CREATE INDEX statement and operator class.
Postgres SERIAL to IDENTITY Converter
Convert a SERIAL or BIGSERIAL column to GENERATED AS IDENTITY with the correct setval, rollback and optional bigint widening.
Postgres DROP ROLE Helper
Generate the audit queries, REASSIGN OWNED, DROP OWNED and DROP ROLE script that clears "role cannot be dropped" errors.
AWS DMS Table Mapping Generator
Build a valid AWS DMS table-mappings.json with selection rules, schema and table renames, column removal and source row filters.
ClickHouse MergeTree Table Generator
Generate ClickHouse CREATE TABLE DDL with MergeTree engines, sorting keys, partitioning, TTL and compression codecs.
SQL Server to PostgreSQL Converter
Translate T-SQL DDL and queries to PostgreSQL: brackets, IDENTITY, NVARCHAR, TOP, GETDATE and more.
Docker Compose MySQL & MariaDB Generator
Generate docker-compose.yml for MySQL or MariaDB with volumes, healthchecks, init scripts and phpMyAdmin.
Oracle to PostgreSQL Converter
Translate Oracle DDL and SQL to PostgreSQL: VARCHAR2, NUMBER, NVL, DECODE, SYSDATE, sequences and more.
SQL Server Backup & Restore Command Generator
Generate T-SQL BACKUP and RESTORE scripts with compression, checksum, WITH MOVE, STOPAT and sqlcmd.
pgbench Command Generator
Build pgbench init and benchmark command lines for PostgreSQL load testing.
dbt schema.yml Generator
Turn a CREATE TABLE statement into a dbt schema.yml with data tests and a unit test skeleton.
DBML to SQL Converter
Convert DBML schemas to PostgreSQL or MySQL DDL, and turn existing CREATE TABLE statements back into DBML.
Liquibase Changelog Generator
Turn SQL DDL into a Liquibase changelog in XML, YAML, JSON or formatted SQL, with constraints and rollbacks.
OtterMind
OtterMind