A plain-language question about revenue has to pass through schema context, business definitions and database permissions before its answer can be trusted. This is the path from tables to answers, layer by layer.

Ask "What was revenue in the North region last quarter?" and a language model can often return a SQL query that runs. Whether the number it produces is the number your finance team would sign off is a separate question. The query might sum gross order value when finance reports net of refunds. It might count a partial quarter. It might read a table the person asking was never meant to see.
Getting from a PostgreSQL database to answers people can rely on is mostly work on the layers around the model: what it is shown, what the words mean, what the database allows, and what the person sees alongside the answer.
Public text-to-SQL benchmarks are a useful guide to where difficulty lies, as long as you read them for their shape and not their leaderboard.
Spider, published at EMNLP 2018, contains 10,181 questions and 5,693 unique SQL queries over 200 databases in 138 domains. Its defining choice was to put different databases in the training and test sets, so a model had to generalise to schemas it had never seen. The best model in the original paper reached 12.4% exact-match accuracy in that setting [1].
BIRD, published at NeurIPS 2023, moved closer to real data: 12,751 question-SQL pairs over 95 databases totalling 33.4 GB, across 37 professional domains. It deliberately includes messy values and questions that need external knowledge to connect business language to columns. The authors report ChatGPT at 40.08% execution accuracy against 92.96% for humans [2].
Spider 2.0, presented at ICLR 2025, uses 632 enterprise workflow tasks. Its databases often have more than 1,000 columns, live in systems such as BigQuery and Snowflake, and can require reading metadata and documentation to solve. The best configuration the authors tested solved 21.3% of tasks, compared with 91.2% on Spider 1.0 and 73.0% on BIRD [3].
Model scores have moved a long way since 2018, and they will keep moving. The pattern across the three papers is the useful part. Accuracy falls as schemas grow and as questions depend on knowledge that is not written in the column names. Missing context is a bigger obstacle than SQL syntax. That is a design problem the data team owns, and a better model does not remove it.
operational tables
|
v
reporting schema / data marts <- what exists to be queried
|
v
described schema (comments) <- what each table and column means
|
v
business definitions <- what "revenue", "active", "quarter" mean
|
v
question --> table selection --> SQL generation
|
v
validation (read-only, allowed tables)
|
v
execution under a restricted role
|
v
answer + SQL + row count + caveats
Each box removes a class of wrong answer. The sections below take them in order.
The first decision is which database the model queries. Pointing it at the live transactional schema is tempting because the data is current, but operational tables are normalised for writes, carry internal status codes, and mix personal data with business facts. A reporting schema or a read replica with a curated set of tables is a better starting point.
Curated usually means data marts: tables or views shaped around a business process at a declared grain, such as one row per order line. A model asked about revenue has far less room to go wrong if there is one sales_order_line table with a clearly named net amount than if it must reconstruct revenue from orders, payments, refunds and currency tables. The modelling side of this is covered in Data marts and dashboards: what each is for.
Views are a cheap way to publish that curated surface in PostgreSQL. By default a view reads its underlying tables with the privileges of the view's owner. Since PostgreSQL 15 you can create a view with security_invoker = true, which makes PostgreSQL check the base tables against the privileges and row-level security policies of the user running the query [4][5]. For an analytics role, invoker semantics are usually the safer default, because the view cannot quietly widen what the role can read.
A model sees names and types. amt, amt2 and flag_x tell it nothing. PostgreSQL has a built-in place for meaning: COMMENT ON, which stores a description against a table, column or other object, readable through psql's \d commands and the obj_description and col_description functions [6].
COMMENT ON TABLE reporting.sales_order_line IS
'One row per order line. Excludes cancelled orders. Source: order service, refreshed nightly.';
COMMENT ON COLUMN reporting.sales_order_line.net_amount_inr IS
'Line value in INR after discounts and after refunds. Use this for revenue.';
COMMENT ON COLUMN reporting.sales_order_line.gross_amount_inr IS
'Line value in INR before discounts and refunds. Not revenue.';
Keeping descriptions in the database has two advantages over a separate document. They travel with the schema, so a tool that discovers the schema picks them up without a second integration. They are also reviewed by the same people who change the tables.
One caution from the PostgreSQL documentation: there is no security mechanism for viewing comments, and any user connected to a database can see all comments in it [6]. Descriptions should explain meaning. They should never contain credentials, customer names or anything sensitive.
When a schema has hundreds of tables, sending all of it with every question is slow and dilutes the context. A common pattern is a first step that narrows the catalogue to relevant tables, then a second step that writes SQL against that subset. If a model does the narrowing, check its choice against the catalogue in code: a table name that does not exist should stop the request there, before any SQL is written.
Comments describe columns. Definitions describe the words people use in questions. This is what is often called a semantic layer, and it does not need a product to start. A table that the data team owns is enough.
| Term in a question | Agreed definition | SQL expression | Grain and caveats |
|---|---|---|---|
| Revenue | Net of discounts and refunds, INR | sum(net_amount_inr) | Order line; additive across all dimensions |
| Orders | Distinct non-cancelled orders | count(DISTINCT order_id) | Distinct count: recompute at each level, do not add subtotals |
| Average order value | Revenue divided by orders | sum(net_amount_inr) / nullif(count(DISTINCT order_id), 0) | Ratio: compute from sums, never average it |
| Last quarter | Most recent complete financial quarter, as finance defines it | date_trunc bounds stated in the answer | Exclude the current, partial quarter |
| North region | Regions mapped in dim_region.zone = 'North' | join to dim_region | Mapping owned by sales operations |
BIRD's inclusion of "external knowledge" in its task design reflects the same idea: many questions can only be answered correctly if someone has written down what a term means in that organisation [2]. The table above is that knowledge, made explicit. It can be supplied to the model as context, used to check generated SQL, or turned into views so that the model never has to reconstruct the definition at all. The last option is the most reliable, and it is a design judgement worth making early.
The "last quarter" row is easy to overlook. If the organisation's financial year does not start in January, "Q1" means different months to the finance team and to a calendar. Either the definition fixes it, or the answer must state the date range it used.
Everything so far improves accuracy. Permissions decide exposure, and they should not depend on the model behaving.
The connection that runs generated SQL should use a dedicated role with SELECT on the reporting schema and nothing else. PostgreSQL's predefined role pg_read_all_data, added in version 14, grants read access to every table, view and sequence [7][8]. For a question-answering tool that is usually far more than it needs. Explicit grants on a reporting schema are easier to reason about.
Where different users may see different rows, row-level security belongs in the database. Once enabled on a table, every normal read must be allowed by a policy, and with no policy the default is deny [9]. Two details matter for analytics. Superusers and roles with BYPASSRLS always bypass policies, and table owners do too unless the table uses FORCE ROW LEVEL SECURITY [9]. pg_read_all_data does not bypass RLS on its own [7]. Tenant-level patterns are covered in Tenant isolation patterns for multi-tenant SaaS.
The controls that stop a generated query from writing, running forever or escaping its role are a topic of their own. Making natural-language SQL safer has reproducible PostgreSQL examples, including a rejected write.
An answer is trustworthy when someone can check it without re-doing the work. That means the response carries more than a sentence:
The fifth point needs a design decision. A system that always produces a confident paragraph will sometimes produce a confident paragraph about nothing. Decide in advance what the response says when a query returns no rows, and keep any written explanation tied to the rows that came back, with no causes the data does not show.
There is a security angle too. The question, the schema descriptions and the result values are all text that reaches the model. OWASP lists prompt injection, including indirect injection through external content, as the first risk in its 2025 Top 10 for LLM applications, and recommends least privilege, separating untrusted content, and validating outputs with deterministic code [10]. A column value that says "ignore previous instructions" should be treated as data, and the database permissions above are what make that safe even when the model misreads it.
Not every question needs every layer on day one. The table below is a way to decide what to build first.
| Question type | Example | Minimum layers before it is reliable |
|---|---|---|
| Lookup on one curated table | "How many orders yesterday?" | Reporting schema, comments, read-only role |
| Aggregate with a business term | "Revenue by region last quarter" | Plus written definitions, stated date bounds |
| Ratio or comparison | "Which region's average order value grew fastest?" | Plus ratio-from-sums rule, complete-period rule |
| Row-level data for a person | "Show my team's open complaints" | Plus RLS or per-user views |
| Cross-process question | "Do late deliveries reduce repeat orders?" | Plus conformed dimensions; treat answers as exploratory |
The last row deserves a note. Causal questions can be phrased conversationally, but a SQL query returns correlations at best. A system that answers them should say what was measured and stop there.
If you are evaluating this for your own PostgreSQL data, the DataMantri product page describes what it does today: it connects to PostgreSQL and MongoDB, discovers schemas, lets analysts shape reusable SQL data marts, and generates, validates and runs read-only SQL on PostgreSQL to answer plain-language questions. It has been verified on PostgreSQL with a demo dataset.
Prepared with AI-assisted research and drafting.