Quick summary
Summarize this blog with AI
An AI analytics agent gives different answers to the same business question because the question has more than one reasonable answer in your data, and nobody has written down which one is official. Better prompts and a bigger schema will not fix that. Define each metric once, implement it in one governed object, show the agent only that curated layer, and check its answers against known results before anyone trusts them.
What was tested: every SQL statement in this guide ran on PostgreSQL 18.7 in a throwaway local cluster, and the outputs shown are pasted from those runs. The fixture is fictional. Snowflake, Databricks, and Power BI were not available, so those sections were checked against each vendor's current documentation only. Product details change often, so confirm them in your own environment.
Why the same question gets 25, 24, and 21
Ask an agent for "active vendors last month" three times and you may get three different counts. Each one can be defensible. One run counts vendors whose account status is active. Another counts vendors that placed an order in the month. A third leaves out vendors whose only order was refunded. The model is not malfunctioning. It is filling a gap in the definition, and it can fill it differently each time.
Revenue has the same problem. If refund logic lives in dozens of BI workbooks, an agent that writes SQL against raw tables has to choose its own rules. These include whether a refund reduces the month of the order or the month of the refund, and whether intercompany or test orders count. Its net revenue can then be several percent away from the finance dashboard, even when both sets of SQL are correct.
Giving the agent the whole warehouse usually makes this worse. With 1,400 tables, it has more chances to pick a deprecated table, a staging copy, or a join path that duplicates rows. The fix is to remove ambiguity, not to add context.
Build a fixture that shows the ambiguity
This fixture has six vendors, eight orders, and three refunds. Every row is there to separate one interpretation from another. V5 is a new vendor with no orders. V6 is suspended but ordered in October. V3's only October order was fully refunded. Order 2 was placed in September and refunded in October.
CREATE SCHEMA raw;
CREATE SCHEMA metrics;
CREATE TABLE raw.vendors (
vendor_id text PRIMARY KEY,
status text NOT NULL, -- current account status
created_at date NOT NULL
);
CREATE TABLE raw.orders (
order_id int PRIMARY KEY,
vendor_id text NOT NULL REFERENCES raw.vendors,
order_date date NOT NULL,
amount numeric(10,2) NOT NULL
);
CREATE TABLE raw.refunds (
refund_id int PRIMARY KEY,
order_id int NOT NULL REFERENCES raw.orders,
refund_date date NOT NULL,
amount numeric(10,2) NOT NULL
);
INSERT INTO raw.vendors VALUES
('V1','active', '2025-03-01'),
('V2','active', '2025-06-15'),
('V3','active', '2026-01-10'),
('V4','active', '2026-02-01'),
('V5','active', '2026-10-18'),
('V6','suspended','2025-09-01');
INSERT INTO raw.orders VALUES
(1,'V4','2026-09-15',200.00),
(2,'V1','2026-09-28',150.00),
(3,'V1','2026-10-03',300.00),
(4,'V2','2026-10-10',120.00),
(5,'V3','2026-10-12', 80.00),
(6,'V6','2026-10-20', 50.00),
(7,'V2','2026-10-30',100.00),
(8,'V1','2026-11-02', 90.00);
INSERT INTO raw.refunds VALUES
(101, 2,'2026-10-05',150.00),
(102, 5,'2026-10-14', 80.00),
(103, 7,'2026-11-04', 40.00);
Three readings of "active vendors in October"
Each of these is SQL an agent could plausibly write:
-- Reading 1: vendors whose account status is active
SELECT count(*) AS active_vendors_by_status
FROM raw.vendors
WHERE status = 'active';
-- Reading 2: vendors with at least one order in October 2026
SELECT count(DISTINCT vendor_id) AS vendors_with_oct_orders
FROM raw.orders
WHERE order_date >= DATE '2026-10-01'
AND order_date < DATE '2026-11-01';
-- Reading 3: vendors with at least one October order that was not fully refunded
SELECT count(DISTINCT o.vendor_id) AS vendors_with_kept_oct_orders
FROM raw.orders o
LEFT JOIN (
SELECT order_id, sum(amount) AS refunded
FROM raw.refunds
GROUP BY order_id
) r USING (order_id)
WHERE o.order_date >= DATE '2026-10-01'
AND o.order_date < DATE '2026-11-01'
AND o.amount - coalesce(r.refunded, 0) > 0;
active_vendors_by_status
--------------------------
5
vendors_with_oct_orders
-------------------------
4
vendors_with_kept_oct_orders
------------------------------
3
Five, four, and three from the same six vendors. Reading 1 ignores the month completely and includes V4 and V5, which placed no October orders. Reading 2 includes V3, whose only order was refunded. Reading 3 includes V6, which is suspended today. None of these is wrong in SQL terms. They answer different questions.
Two readings of monthly net revenue
Next, attribute refunds two ways. The first query charges each refund to the month of the original order. The second charges it to the month the refund happened:
-- Refunds attributed to the ORDER month
SELECT date_trunc('month', o.order_date)::date AS month,
sum(o.amount) AS gross,
sum(coalesce(r.refunded, 0)) AS refunds,
sum(o.amount - coalesce(r.refunded, 0)) AS net_revenue
FROM raw.orders o
LEFT JOIN (
SELECT order_id, sum(amount) AS refunded
FROM raw.refunds GROUP BY order_id
) r USING (order_id)
GROUP BY 1 ORDER BY 1;
-- Refunds attributed to the REFUND month
WITH g AS (
SELECT date_trunc('month', order_date)::date AS month, sum(amount) AS gross
FROM raw.orders GROUP BY 1
), rf AS (
SELECT date_trunc('month', refund_date)::date AS month, sum(amount) AS refunds
FROM raw.refunds GROUP BY 1
)
SELECT month,
coalesce(g.gross, 0) AS gross,
coalesce(rf.refunds, 0) AS refunds,
coalesce(g.gross, 0) - coalesce(rf.refunds, 0) AS net_revenue
FROM g FULL JOIN rf USING (month)
ORDER BY month;
month | gross | refunds | net_revenue
------------+--------+---------+-------------
2026-09-01 | 350.00 | 150.00 | 200.00
2026-10-01 | 650.00 | 120.00 | 530.00
2026-11-01 | 90.00 | 0 | 90.00
month | gross | refunds | net_revenue
------------+--------+---------+-------------
2026-09-01 | 350.00 | 0 | 350.00
2026-10-01 | 650.00 | 230.00 | 420.00
2026-11-01 | 90.00 | 40.00 | 50.00
October net revenue is 530 under one rule and 420 under the other, a 26% gap on the same data. Order-month attribution has another side effect. September dropped from 350 to 200 after the month ended, and October would have shown 570 on October 31 before the November 4 refund lowered it. Neither rule is wrong. You must choose one and write it down.
Write a metric contract
A metric contract is a short written definition that a person can review and that a view can implement. Keep it next to the code, in the view comment, a YAML file, or the semantic model description, so it cannot drift. For this fixture:
| Field | Net revenue | Active vendors |
|---|---|---|
| Grain | Vendor per calendar month | Vendor per calendar month |
| Formula | Gross order amount minus refunds | Count of vendors with at least one qualifying order |
| Time attribution | Orders by order date; refunds by refund date (closed months do not restate) | Order date |
| Inclusions | All orders, all vendor statuses | Orders not fully refunded as of query time |
| Exclusions | None in this fixture (in real data: test vendors, intercompany) | Current account status is ignored |
| Owner | Finance analytics | Marketplace operations |
| Known answers | Sep 350.00, Oct 420.00, Nov 50.00 | Sep 1, Oct 3, Nov 1 |
The owner column matters most. When an agent's answer is disputed, the owner decides whether the agent or the definition is wrong. Without an owner, every disagreement becomes another debate.
Implement the contract in one canonical view
Put the logic in one place and expose it in its own schema. The view comments carry the definition, so any tool that reads catalog metadata can see it:
CREATE VIEW metrics.vendor_month AS
WITH order_net AS (
SELECT o.order_id, o.vendor_id,
date_trunc('month', o.order_date)::date AS month,
o.amount,
o.amount - coalesce(sum(r.amount), 0) AS kept_amount
FROM raw.orders o
LEFT JOIN raw.refunds r ON r.order_id = o.order_id
GROUP BY o.order_id, o.vendor_id, o.order_date, o.amount
), gross AS (
SELECT vendor_id, month,
sum(amount) AS gross_revenue,
bool_or(kept_amount > 0) AS has_kept_order
FROM order_net
GROUP BY vendor_id, month
), refunds_booked AS (
SELECT o.vendor_id,
date_trunc('month', r.refund_date)::date AS month,
sum(r.amount) AS refunds
FROM raw.refunds r
JOIN raw.orders o ON o.order_id = r.order_id
GROUP BY 1, 2
)
SELECT vendor_id, month,
coalesce(g.gross_revenue, 0) AS gross_revenue,
coalesce(b.refunds, 0) AS refunds,
coalesce(g.gross_revenue, 0) - coalesce(b.refunds, 0) AS net_revenue,
coalesce(g.has_kept_order, false) AS is_active
FROM gross g
FULL JOIN refunds_booked b USING (vendor_id, month);
COMMENT ON VIEW metrics.vendor_month IS
'One row per vendor per month. net_revenue = gross order amount in the order month minus refunds in the refund month. is_active = at least one order in the month not fully refunded. Owner: finance analytics.';
COMMENT ON COLUMN metrics.vendor_month.is_active IS
'Active vendor: >= 1 order placed in this month whose amount was not fully refunded. Account status is ignored.';
CREATE VIEW metrics.monthly_kpis AS
SELECT month,
sum(gross_revenue) AS gross_revenue,
sum(refunds) AS refunds,
sum(net_revenue) AS net_revenue,
count(*) FILTER (WHERE is_active) AS active_vendors
FROM metrics.vendor_month
GROUP BY month;
The FULL JOIN is deliberate. A vendor with refunds in a month but no orders in that month still needs a row, otherwise those refunds disappear from the total. The order_net CTE aggregates refunds per order before anything is summed, which prevents the classic fan-out where an order with two refunds is counted twice.
Test the view and the agent against known answers
Work out the expected values by hand from the fixture, then compare them in SQL. If a test fails, either the logic or the expectation is wrong. The data cannot be, because you wrote it.
WITH expected(month, metric, value) AS (
VALUES (DATE '2026-09-01', 'net_revenue', 350.00),
(DATE '2026-10-01', 'net_revenue', 420.00),
(DATE '2026-11-01', 'net_revenue', 50.00),
(DATE '2026-10-01', 'active_vendors', 3),
(DATE '2026-11-01', 'active_vendors', 1)
), actual AS (
SELECT month, 'net_revenue' AS metric, net_revenue AS value FROM metrics.monthly_kpis
UNION ALL
SELECT month, 'active_vendors', active_vendors FROM metrics.monthly_kpis
)
SELECT e.month, e.metric, e.value AS expected, a.value AS actual,
CASE WHEN a.value = e.value THEN 'PASS' ELSE 'FAIL' END AS result
FROM expected e
LEFT JOIN actual a USING (month, metric)
ORDER BY e.metric, e.month;
month | metric | expected | actual | result
------------+----------------+----------+--------+--------
2026-10-01 | active_vendors | 3 | 3 | PASS
2026-11-01 | active_vendors | 1 | 1 | PASS
2026-09-01 | net_revenue | 350.00 | 350.00 | PASS
2026-10-01 | net_revenue | 420.00 | 420.00 | PASS
2026-11-01 | net_revenue | 50.00 | 50.00 | PASS
Use the same pattern on the agent. Paste the SQL it generated into a candidate CTE and compare it with the canonical answer. Here the agent used Reading 2:
WITH candidate AS (
SELECT count(DISTINCT vendor_id) AS value
FROM raw.orders
WHERE order_date >= DATE '2026-10-01'
AND order_date < DATE '2026-11-01'
), canonical AS (
SELECT active_vendors AS value
FROM metrics.monthly_kpis
WHERE month = DATE '2026-10-01'
)
SELECT c.value AS agent_answer, k.value AS canonical_answer,
CASE WHEN c.value = k.value THEN 'PASS' ELSE 'FAIL' END AS result
FROM candidate c CROSS JOIN canonical k;
agent_answer | canonical_answer | result
--------------+------------------+--------
4 | 3 | FAIL
Keep a set of 10 to 30 business questions, each with its expected answer on the fixture or on a frozen production snapshot, and rerun them whenever you change the model, the instructions, or the agent configuration. For more on this approach, see how to test SQL queries with expected results.
Restrict the agent to the curated layer
Give the agent a database role that can read the metrics schema and nothing else. In PostgreSQL, a view runs with its owner's privileges by default, so the agent can query the view without having access to the raw tables:
CREATE ROLE agent_reader LOGIN;
GRANT USAGE ON SCHEMA metrics TO agent_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA metrics TO agent_reader;
SET ROLE agent_reader;
SELECT month, net_revenue, active_vendors
FROM metrics.monthly_kpis WHERE month = DATE '2026-10-01';
SELECT count(*) FROM raw.orders;
month | net_revenue | active_vendors
------------+-------------+----------------
2026-10-01 | 420.00 | 3
psql:grants.sql:7: ERROR: permission denied for schema raw
LINE 1: SELECT count(*) FROM raw.orders;
That error is the goal. Once the agent cannot reach raw, it cannot write Reading 2. Two operational notes: GRANT SELECT ON ALL TABLES covers only views that exist when you run it, so add ALTER DEFAULT PRIVILEGES or re-grant when you add views. Also keep deprecated tables out of the curated schema rather than labeling them "do not use".
Expose definitions in your platform's semantic layer
A plain view fixes the logic but not the vocabulary: the agent still has to guess that "sellers" means vendors. The major platforms now offer objects that hold metrics, descriptions, and synonyms for AI tools to read. Keep the same contract and the same known-answer tests, whichever you use.
Snowflake semantic views
A semantic view is a schema-level object created with CREATE SEMANTIC VIEW. It defines logical tables, relationships, facts, dimensions, and metrics. Tables, facts, dimensions, and metrics accept COMMENT and WITH SYNONYMS. The command also has optional clauses for AI guidance, including AI_SQL_GENERATION and AI_VERIFIED_QUERIES. You query it with the SEMANTIC_VIEW(...) construct, and Cortex Agents can use it as a tool and generate SQL from its definitions. Put your contract text in the metric comments and your known-answer questions in verified queries.
Databricks metric views
Metric views are Unity Catalog objects defined in YAML. A definition has a source, fields (the docs prefer this term; dimensions is still accepted), and measures whose expressions must use aggregate functions. You reference a measure in a query with the MEASURE function. Databricks lists Genie as a consumer and documents agent metadata such as synonyms and display names, plus connections from external BI tools including Power BI.
Power BI semantic models and Copilot
Microsoft recommends adding business-critical calculations as reviewed measures, for example a [Net Sales] measure with the approved treatment of returns. It also recommends filling in the Description property of measures, tables, and columns, starting with the business meaning, unit, and exclusions. Copilot uses only the first 200 characters, so put the rule first. Prep data for AI, a preview on the Home ribbon in Desktop and on the semantic model page in the service, includes an AI data schema (the Simplify data schema tab), AI instructions, and verified answers. Q&A must be enabled on the model. When the model is ready, you can mark it Approved for Copilot in its settings. Microsoft's guidance is blunt: fix modeling problems in the model itself, because instructions can't correct inaccurate relationships or inappropriate aggregations.
Require the SQL and log disagreements
- Always show the query. Configure the agent, or your instructions, to return the SQL or DAX with every number. In Power BI, use How Copilot arrived at this. A number without its query cannot be reviewed.
- Log every question and answer. Store the question text, generated SQL, result, and timestamp. Group by normalized question and flag any that returned more than one distinct value. Each flag is a missing definition or a missing synonym.
- Route disputes to the metric owner. Either the agent strayed from the canonical object, so you tighten the schema or add a verified query, or the contract was ambiguous, so the owner updates it and the tests.
- Reconcile against the BI tool on a schedule. If the agent and a dashboard disagree, use the steps in why two dashboards disagree: match grain, date basis, and filters before blaming either side.
The same habits apply when you use a general chat assistant to draft SQL. The AI workflow for analysts covers reviewing generated queries in more detail.
Checklist
- List the 10 to 30 questions people actually ask the agent.
- For each metric, write the contract: grain, formula, time attribution, inclusions, exclusions, owner.
- Build a fixture where the competing interpretations give different numbers.
- Implement each metric once, in a view, semantic view, metric view, or measure, with the contract in its description.
- Write known-answer tests and run them on every change.
- Give the agent access to the curated layer only, and keep deprecated objects out of it.
- Require the generated query with every answer, log answers, and review questions with more than one distinct result.
FAQ
Can I fix inconsistent answers with better prompts or instructions?
Instructions help with vocabulary and defaults, but they cannot fix logic the agent has to rebuild every time. If refunds are handled differently in three places, the agent can still pick any of them. Put the rule in one governed object first, then use instructions to point the agent at it.
Should refunds reduce the order month or the refund month?
Both are valid. Refund-month attribution keeps closed months stable and usually matches how finance books refunds. Order-month attribution shows the true net value of each month's sales, but past months change as refunds arrive. Choose one with the metric owner, record it in the contract, and offer the other as a separately named metric if people need both.
Is a plain SQL view enough, or do I need a semantic layer?
A view with comments and restricted grants already removes most of the inconsistency, and it works in any database. A semantic view, metric view, or Power BI semantic model adds synonyms, relationships, and verified questions that agents can read, so phrasing variations still map to the same metric. Start with the view and the tests, then move them into your platform's semantic layer.