One query took 41% of database time this week
Postgres spent 9.8 hours executing queries this week. The orders lookup by customer and status alone took 4.0 hours across 182,400 calls.
Every Monday: the 10 Postgres queries with the most total execution time last week, with calls, mean time, cache hits and an index hint for each.
Reads
You get
The card on the right is a sample. Yours shows your own numbers and updates in place every run.
What lands on your board
Postgres spent 9.8 hours executing queries this week. The orders lookup by customer and status alone took 4.0 hours across 182,400 calls.
The slow query log catches the one 4-second report query and misses the 5 ms lookup that runs a million times a day, which is usually where the database time actually goes. pg_stat_statements has the real numbers, but it only shows totals since the last reset, so a week-on-week view needs someone to take snapshots.
The agent takes that snapshot every Monday, subtracts last week's, and ranks queries by the time they cost this week. For the top ones it reads a generic plan and points at the sequential scan or missing index behind it. It never creates an index itself.
Run select extversion from pg_extension where extname = 'pg_stat_statements'. Supabase, Neon, Amazon RDS and Cloud SQL all support it; if it is missing, create extension pg_stat_statements (it must also be in shared_preload_libraries, which needs a restart).
select queryid, query, calls, total_exec_time, mean_exec_time, rows, shared_blks_hit, shared_blks_read from pg_stat_statements where toplevel and save it with the date. Read stats_reset from pg_stat_statements_info too.
Match last Monday's snapshot by queryid and subtract calls and total_exec_time to get this week's numbers. If stats_reset is newer than the old snapshot, use the totals since the reset and say so.
For the top 10 by time, compute the cache hit ratio shared_blks_hit / (shared_blks_hit + shared_blks_read). For SELECTs, run explain (generic_plan) <query> (Postgres 16+, works with $1 placeholders) and note a Seq Scan on a large table or a sort spilling to disk.
Each query shortened to one line, its calls, mean time, total time and share of all database time this week, and a suggested index written as a create index concurrently statement for a person to review.
With BRIEFKIN_TOKEN set, the agent sends the result as one card that updates in place every run. Without it, you get the report in the chat.
Pick your agent, where the data comes from and how to schedule it; the commands below follow.
One command. It puts the SKILL.md in ~/.claude/skills and in ~/.agents/skills, which Codex, Cursor, Gemini CLI, Copilot CLI and OpenCode read too.
shellcurl -fsSL https://briefkin.dev/skills/postgresql-slow-queries-report/install | shAsk Claude Code:
promptRun the postgresql-slow-queries-report skillOr paste the prompt instead of installing:
promptConnect to my Postgres database read only. From pg_stat_statements (top-level statements), take a snapshot of queryid, query, calls, total_exec_time, mean_exec_time, rows, shared_blks_hit and shared_blks_read. If I have last week's snapshot, subtract it by queryid to get this week's calls and time; otherwise use totals since stats_reset from pg_stat_statements_info and say so. List the 10 queries with the most total time: a one-line version of the query, calls, mean time, total time, share of all time and cache hit ratio. For the top five SELECTs run explain (generic_plan) on Postgres 16 or newer and point out sequential scans on large tables or sorts on disk, with a suggested create index concurrently statement. Do not create indexes or reset the statistics.Mondays at 9:00, from cron on any machine where Claude Code is signed in:
crontab0 9 * * 1 claude -p "Run the postgresql-slow-queries-report skill"Add it with crontab -e. A laptop asleep at that time runs it when it wakes if you use launchd or Task Scheduler instead; GitHub Actions works for the API route.
Connect Briefkin once with curl -fsSL https://briefkin.dev/install | sh and every run lands on your board as a report card. How setup works
SKILL.md---
name: postgresql-slow-queries-report
description: "Every Monday: the 10 Postgres queries with the most total execution time last week, with calls, mean time, cache hits and an index hint for each. Use when the user asks for this, or when it runs on a schedule."
---
# Postgres slow queries report
Every Monday: the 10 Postgres queries with the most total execution time last week, with calls, mean time, cache hits and an index hint for each.
The slow query log catches the one 4-second report query and misses the 5 ms lookup that runs a million times a day, which is usually where the database time actually goes. `pg_stat_statements` has the real numbers, but it only shows totals since the last reset, so a week-on-week view needs someone to take snapshots.
The agent takes that snapshot every Monday, subtracts last week's, and ranks queries by the time they cost this week. For the top ones it reads a generic plan and points at the sequential scan or missing index behind it. It never creates an index itself.
## Two ways to get the data
Use the API or MCP route when you have an MCP server, a CLI or an API token for the app. Otherwise, if you can drive a browser the user is signed in to (Claude in Chrome, a Playwright or Chrome DevTools MCP server), use the browser route. Say which one you used.
## Route A: API or MCP server
### What you need
- A read-only role that is a member of `pg_read_all_stats`, so it can see the query text of other users, with the connection string in `DATABASE_URL`.
- Access through `psql` or a Postgres MCP server, plus a place to keep the weekly snapshot file between runs.
If something is missing, say what and stop; do not invent numbers.
### Steps
1. **Check the extension** (PostgreSQL): Run `select extversion from pg_extension where extname = 'pg_stat_statements'`. Supabase, Neon, Amazon RDS and Cloud SQL all support it; if it is missing, `create extension pg_stat_statements` (it must also be in `shared_preload_libraries`, which needs a restart).
2. **Take this week's snapshot** (PostgreSQL): `select queryid, query, calls, total_exec_time, mean_exec_time, rows, shared_blks_hit, shared_blks_read from pg_stat_statements where toplevel` and save it with the date. Read `stats_reset` from `pg_stat_statements_info` too.
3. **Subtract last week**: Match last Monday's snapshot by `queryid` and subtract `calls` and `total_exec_time` to get this week's numbers. If `stats_reset` is newer than the old snapshot, use the totals since the reset and say so.
4. **Look at the plans of the top queries** (PostgreSQL): For the top 10 by time, compute the cache hit ratio `shared_blks_hit / (shared_blks_hit + shared_blks_read)`. For SELECTs, run `explain (generic_plan) <query>` (Postgres 16+, works with `$1` placeholders) and note a `Seq Scan` on a large table or a sort spilling to disk.
5. **Report**: Each query shortened to one line, its calls, mean time, total time and share of all database time this week, and a suggested index written as a `create index concurrently` statement for a person to review.
## Route B: the browser
### What you need
- Signed in to the hosting console with a role that can open the SQL page for the production project; the editor runs as a superuser on Supabase, so no `pg_read_all_stats` grant is needed there.
If something is missing, say what and stop; do not invent numbers.
### Steps
Start at https://supabase.com/dashboard/project/_/sql/new. The user is signed in already; never type passwords or codes, and ask if a sign-in page appears.
1. **Open a SQL page for the database**: Postgres has no web UI of its own, so use your host's SQL page: the Supabase **SQL Editor** at the URL above (it asks which project), the Neon console **SQL Editor**, or the **Query** tab of a Railway Postgres service. For RDS or a self-hosted server, use whatever web client you already run (pgAdmin, Metabase); the steps are the same.
2. **Check the extension and take the snapshot**: Run `select extversion from pg_extension where extname = 'pg_stat_statements'`. Then run `select queryid, left(query, 120) as query, calls, round(total_exec_time::numeric) as total_ms, round(mean_exec_time::numeric, 1) as mean_ms, rows, shared_blks_hit, shared_blks_read from pg_stat_statements where toplevel order by total_exec_time desc limit 200`, and `select stats_reset from pg_stat_statements_info`.
3. **Subtract last week**: Paste last Monday's results into the chat (or keep them in a saved query named `pg_stat_snapshot_<date>` in the editor) so this week's calls and total time are the difference per `queryid`. If `stats_reset` is newer than that snapshot, use totals since the reset and say so.
4. **Read the plans of the top queries**: For the top 10 by time compute the cache hit ratio from the block counts. For SELECTs on Postgres 16 or newer run `explain (generic_plan) <query text>` in a new tab and note a `Seq Scan` on a large table or a sort spilling to disk.
5. **Report**: One line per query with calls, mean, total, share of all database time and cache hit ratio, then a `create index concurrently` suggestion for each sequential scan, written for a person to review. Run nothing that changes the database.
Note: Supabase also has a **Query Performance** report in the project dashboard built on the same view, which is a quick way to confirm the top rows but has no week-over-week subtraction. SQL editors cap result rows (the Supabase editor at a few hundred by default), so keep the `limit 200`; the top 10 are always inside it.
## The report
- **Total database time** this week and the change.
- **Top 10 queries** by total time: calls, mean time, total time, share and cache hit ratio.
- **Plan notes** for the top queries: sequential scans, disk sorts, the index that would help.
- **New this week**: heavy queries that did not appear last week, often a new feature.
## Post it to Briefkin
When `BRIEFKIN_TOKEN` is set, or `~/.config/briefkin/env` exists (the installer from https://briefkin.dev/docs writes it), also send the result to the user's Briefkin board as one card. Keep the `item_key` the same on every run so the card updates in place, use a new `event_id` per run, and put today's real numbers in place of the example ones. If the request fails, say so once and carry on.
```bash
[ -n "${BRIEFKIN_TOKEN:-}" ] || . ~/.config/briefkin/env
curl -sS -X POST "${BRIEFKIN_URL:-https://briefkin.dev}/v1/events" \
-H "authorization: Bearer $BRIEFKIN_TOKEN" \
-H "content-type: application/json" \
-d @- <<'JSON'
{
"v": 1,
"event_id": "postgresql-slow-queries-report/<date of this run, e.g. 2026-10-16>",
"item_key": "postgresql-slow-queries-report",
"project": "acme-api",
"source": "Postgres slow queries report skill",
"kind": "update",
"title": "One query took 41% of database time this week",
"summary": "Postgres spent **9.8 hours** executing queries this week. The orders lookup by customer and status alone took **4.0 hours** across 182,400 calls.",
"widget": [
{
"type": "Table",
"props": {
"columns": [
"Query",
"Calls",
"Mean",
"Total",
"Share"
],
"align": [
"left",
"right",
"right",
"right",
"right"
],
"rows": [
[
"select ... from orders where customer_id = $1 and status = $2",
"182,400",
"79 ms",
"240 min",
"41%"
],
[
"select ... from sessions where token = $1",
"1,240,000",
"5.1 ms",
"105 min",
"18%"
],
[
"select ... from events where org_id = $1 order by created_at",
"9,800",
"312 ms",
"51 min",
"9%"
],
[
"update inventory set reserved = reserved + $1 where sku = $2",
"64,000",
"28 ms",
"30 min",
"5%"
],
[
"select count(*) from audit_log where created_at > $1",
"420",
"2,140 ms",
"15 min",
"3%"
]
]
}
},
{
"type": "Callout",
"props": {
"text": "The orders query runs a Seq Scan on 2.1M rows. Suggested: create index concurrently on orders (customer_id, status).",
"tone": "warn"
}
}
]
}
JSON
```
Widgets come from the Briefkin catalog (https://briefkin.dev/v1/catalog). Without a token, just give the user the report.
## Run it on a schedule
Suggested: Mondays at 9:00 (`0 9 * * 1`). From cron, with the agent signed in on that machine:
```bash
0 9 * * 1 claude -p "Run the postgresql-slow-queries-report skill"
# Codex: codex exec, Gemini CLI: gemini -p, Copilot CLI: copilot -p, OpenCode: opencode run
```
Or use the agent's own scheduler (Claude Code routines, Codex automations, Claude or ChatGPT scheduled tasks): https://briefkin.dev/skills/postgresql-slow-queries-report#schedule
Source: https://briefkin.dev/skills/postgresql-slow-queries-report
A read-only role that is a member of pg_read_all_stats, so it can see the query text of other users, with the connection string in DATABASE_URL.
Access through psql or a Postgres MCP server, plus a place to keep the weekly snapshot file between runs.
postgres-mcp), whose --access-mode=restricted runs every statement in a read-only transaction with a time limit: claude mcp add --env DATABASE_URI=postgresql://report_reader:<password>@db.example.com:5432/app --transport stdio postgres -- uvx postgres-mcp --access-mode=restricted. In Codex and Cursor, put the same command, arguments and DATABASE_URI in the server config. Managed hosts such as Supabase and Neon run their own MCP servers.psql with a connection string. Claude Code and Codex can run psql "$DATABASE_URL" -X -A -F ',' -c "SELECT ..." directly; it needs only the client and the URL.CREATE ROLE report_reader LOGIN PASSWORD '...', GRANT CONNECT ON DATABASE app TO report_reader, then GRANT pg_read_all_data, pg_monitor TO report_reader on Postgres 14 and later (on older versions, grant USAGE on the schema and SELECT on its tables). Add ALTER ROLE report_reader SET default_transaction_read_only = on and ALTER ROLE report_reader SET statement_timeout = '30s'.The role is the safeguard that holds whichever tool connects: with only read privileges it can't write, alter or drop anything, pg_monitor lets it see the statistics views, and the timeout stops a runaway query. Point it at a read replica if you have one.
Because total time is what the database actually spends. A 2-second report that runs 400 times a week costs less than a 5 ms lookup that runs a million times. The table shows the mean too, so the slow-but-rare ones are still visible.
No. Resetting would wipe the numbers for other tools and people. The skill keeps its own weekly snapshot and subtracts it, which gives the same week-on-week view without touching the server.
No. The skill runs with your own agent and gives you the report in the chat. With a Briefkin token set, each run also posts it to your board as a report card, so you can glance at it instead of asking again.
Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot CLI, OpenCode, Windsurf and Amp all read SKILL.md files. The install command puts it in ~/.claude/skills and ~/.agents/skills, where they look. ChatGPT, the Claude app and Grok take the prompt instead. Pick your agent under "Install and run it" and the commands change to match.
Yes. Switch the data source to "Your browser" and the steps change to the PostgreSQL pages themselves: the agent opens supabase.com/dashboard/project/_/sql/new in a browser you are signed in to and reads the numbers off the page. Claude Code, Codex, Cursor, Claude app and ChatGPT can drive a browser out of the box; Gemini CLI, Copilot CLI and OpenCode need a Playwright or Chrome DevTools MCP server first. It is slower than the API and needs you signed in, so it suits a report you run by hand or from a scheduler on your own computer.
Skills are free to use with any agent. Briefkin is where their results land: one board for every report, number and question your agents send, with a ping when something needs you.
Free during the open beta. No card.