Keep your reporting agent off the table the cash registers write to
Set a measurable target, read the execution plan and move reports to a PostgreSQL materialized view before you reach for another index.
In brief
- Start from a measurable target and the execution history; don't tune at random.
- EXPLAIN ANALYZE really runs the statement: ROLLBACK undoes the side effects, but the client's database still takes the load.
- Point AI reports at a materialized view, agree on acceptable staleness, choose the refresh time and monitor the view's age.
When a reporting agent answers “what did each store sell this week?” by generating SQL against orders, it scans the same table the cash registers are constantly writing to. Say you are a week into deploying one for a retail chain, a hypothetical client. The demo ran smoothly. In production, the client’s operations team starts asking why the database is so much busier.
The prompt is not the problem. The agent cannot tell which tables serve transactions and which are meant for analysis; you have to know that on its behalf. The process below can be worked through on a laptop with PostgreSQL: set a target, read the execution plan, move the report to a materialized view, and only then consider indexes.
The schema is simplified for illustration: a table orders(id, store_id, created_at, amount, is_paid). You need a local PostgreSQL instance, permission to create tables and, ideally, a copy of the data large enough for execution plans to resemble production.
Step 1: What number must you hit, and which statements are worth fixing?
Oracle defines SQL tuning as an iterative process of meeting specific, measurable and achievable goals. So before typing any command, write the target down with the client. An illustrative one: “the weekly revenue report returns in under two seconds, and the agent running reports does not slow down order writes.”
Next, find the statements worth fixing. Oracle’s documentation advises reviewing execution history to find the statements responsible for most of the load and system resources, rather than tuning at random.
With an agent, this history usually reveals a pattern: a handful of aggregate queries, repeated with slightly different parameters. Those are your first candidates.
Check: you have a short list of statements causing the load and a target number the client has agreed to.
Step 2: Read the plan before running anything
According to Oracle, the execution plan is the primary diagnostic tool in manual tuning. EXPLAIN shows you the plan without running the statement, which makes it the safest step to take on a client’s database.
EXPLAIN
SELECT store_id, date_trunc('day', created_at) AS day, sum(amount)
FROM orders
WHERE created_at >= now() - interval '7 days'
GROUP BY 1, 2;
For real measurements, you need EXPLAIN ANALYZE. The PostgreSQL documentation warns plainly that this command actually runs the query, so any side effects happen as usual. For statements that write data, PostgreSQL recommends wrapping the command in a transaction and rolling it back.
Don’t mistake a rollback for safety. It undoes only the data changes; a heavy aggregate still runs in full and still weighs on the client’s transactional database.
For a read-only query like the one below, wrapping it in a transaction reduces nothing. Run it on a copy of the data, or off-peak once the operations team has agreed.
EXPLAIN (ANALYZE, BUFFERS)
SELECT store_id, date_trunc('day', created_at) AS day, sum(amount)
FROM orders
WHERE created_at >= now() - interval '7 days'
GROUP BY 1, 2;
The BUFFERS option reports I/O at each node of the plan, and PostgreSQL 18 turns it on by default with ANALYZE. Spelling it out still helps whoever reads your script later.
Step 3: Look at the rows, ignore the cost
Newcomers often compare the cost column as though it were milliseconds. It isn’t. The PostgreSQL documentation says cost units are arbitrary and do not match real time, and that the most important thing to check is whether estimated row counts are close to reality.
Suppose the node scanning orders estimates 1,000 rows but actually returns 900,000. The planner chose a strategy for a small set and then had to process one 900 times larger, and every decision above that node rests on the wrong number. Record this first, before you even think about an index.
Check: for each statement on your list, you know which node reads the most buffers and which has the least accurate estimate.
Step 4: Give the agent a summary to read
Oracle lists missing access structures, such as indexes and materialized views, as a typical cause of slow SQL. For AI reporting, a materialized view is usually the better choice: the agent reads a pre-aggregated table instead of hammering the transactional one.
Microsoft’s description of the Materialized View pattern stresses a valuable property: the view and the data in it are completely disposable, because they can always be rebuilt from the source. It is a specialized form of cache, so you can experiment, get it wrong and rebuild without touching the client’s original data.
CREATE MATERIALIZED VIEW report_daily_store_sales AS
SELECT store_id,
date_trunc('day', created_at) AS day,
sum(amount) AS revenue,
count(*) AS order_count
FROM orders
GROUP BY 1, 2;
The hardest question at this step lies outside the SQL. Microsoft advises deciding how stale the data may be first, then choosing whether to refresh on events, on a schedule or manually.
If regional directors look at the report only each morning, data a few hours old is fine; if they use it to move stock during the day, it is not. Ask during customer discovery rather than guessing.
Step 5: Refresh without locking out readers
A plain REFRESH MATERIALIZED VIEW blocks reads of the view while it runs, which leaves the agent waiting. The CONCURRENTLY version refreshes the view without locking out concurrent SELECTs, but it requires a UNIQUE index and allows only one refresh to run at a time.
CREATE UNIQUE INDEX report_daily_store_sales_key
ON report_daily_store_sales (store_id, day);
REFRESH MATERIALIZED VIEW CONCURRENTLY report_daily_store_sales;
One detail trips people up: the PostgreSQL documentation requires that index to use plain columns only, so it cannot be an expression index or have a WHERE clause. In the example above, date_trunc is already part of the view definition, so day is an ordinary column of the view and the index qualifies. Put date_trunc in the index instead, and the concurrent refresh will not run.
Remember, too, that the view is built from orders. Every full refresh makes the aggregate in the view definition scan the transactional table again, and Microsoft notes that refreshes consume compute. Refresh as rarely as the staleness threshold from step 4 allows, and schedule it off-peak instead of in the middle of a sales shift.
Indexes help the agent read quickly, but they are not free. Microsoft notes that maintaining indexes on the view adds write cost to every refresh cycle. Keep only the ones your reporting queries actually use.
Check: rerun EXPLAIN on the agent’s query, this time pointed at the view, with the ANALYZE and BUFFERS options from step 2, and compare buffer counts with step 3.
Step 6: A silently stale view is the most dangerous failure
When a trigger or refresh job is missed, Microsoft warns, the view silently returns outdated results. With an agent, this is worse than an obvious error: it answers fluently with yesterday’s numbers. The recommendation is to track the last refresh time and raise an alert when the view’s age exceeds the agreed threshold.
A simple approach is to have the refresh job write its completion time to a small log table, and a periodic check compare that time with the threshold from step 4. You can also let the agent read the timestamp and state “figures as of…” in its answer, so users are not misled.
When should you consider an index table?
Some queries are lookups by something other than the primary key, with no aggregation involved: finding orders by customer ID, for example. Microsoft’s Index Table pattern addresses this at the architecture level, with a separately built index table.
Carrying it over to PostgreSQL indexes is reasoning by analogy, and PostgreSQL itself lays down no such rule. Two pieces of the pattern’s advice are still worth an FDE’s attention.
The first: don’t create speculative index tables for queries the application never runs, or runs only occasionally. Each index table adds maintenance cost, so it should be reviewed and removed once nobody uses it. Applied to an agent, that means adding one only when the history from step 1 shows the query pattern really does recur.
The second: a low-selectivity key, such as the boolean column is_paid, is a poor candidate. The index table still incurs its full storage and throughput cost while barely narrowing the query. A flag with only two values splits the table in two; it does not help you find a few rows quickly.
Common mistakes
The most common mistake is running EXPLAIN ANALYZE in production and feeling safe because of the ROLLBACK, while the load still lands on the client’s database. The second is comparing costs between two plans and drawing conclusions in milliseconds.
The third is building a materialized view without anyone agreeing on acceptable staleness, so refreshes run on gut feel and no alert fires when they break.
In the other direction, don’t rush to index every column the agent has ever filtered on. Each index is a write cost the client’s transactional system must keep paying.
How to put this skill on your CV
If an FDE job description mentions hands-on work with client databases or production performance, lead with this skill when you answer interview questions.
On your CV, skip “proficient in SQL.” Write one structured line: the measurable target, the statement causing the load, the change you made (materialized view, UNIQUE index, concurrent refresh) and how you monitored stale data.
A small repo with scripts, execution plans from before and after, and a README explaining why you did not index the boolean column will be more persuasive than any certificate.
Agents will keep getting better at writing SQL. Understanding whom the client’s database is serving at any given moment, and why the agent should be kept away from it, remains the job of the FDE sitting beside the client’s operations team.
Was this article useful?
Thanks for the feedback!