How to Query a Database Using AI: Context and Examples
Query a database with AI using clear business context. Compare live data with indexed copies, verify freshness, and reproduce SQL and follow-up examples.

To query a database using AI, connect an approved data source, explain the business meaning of its fields, ask a specific question, and check the returned answer. A useful assistant needs both schema context (which tables and columns exist) and business context (what terms such as “active user” mean). A query can execute successfully and still answer the wrong question.
This guide takes one question from an ambiguous request to a checked result, then tests two follow-ups. First, choose live data, an indexed copy or a historical snapshot: the same question can produce different correct answers when the data is from different times. Download the editable context brief and synthetic PostgreSQL reference to adapt the workflow. The worksheet is editorial material, not a built-in product template or automatic import feature.
Updated November 11, 2026. AskYourDatabase publishes this guide. The SQL references were checked locally in PGlite, a PostgreSQL 18.3 WebAssembly runtime; they do not measure an AI model's accuracy or establish results on your database. The new freshness example runs separately in Python's in-memory SQLite and does not call a database service or AI model.
Choose how the AI will access the data
An AI query may mean a generated SQL statement, a connected database answer, or a search over documents. Decide which output you need before choosing a tool.
| Workflow | What you provide | What you receive | Check before relying on it |
|---|---|---|---|
| Disconnected SQL drafting | Approved schema excerpt and question | SQL text to run elsewhere | Dialect, missing columns and actual execution results |
| Connected database assistant | Permitted connection, schema and business context | Query results and conversational follow-ups | Execution identity, metric meaning and model data flow |
| Native warehouse agent | Supported warehouse sources and agent context | Answers within that platform | Source scope, warehouse permissions and query costs |
| Document question answering | Text or documents | Retrieved passages or summaries | Whether the answer actually requires live database calculations |
If you are choosing an engine-specific workflow, start with the database query generator and database chooser. For SQL construction, use the SQL pattern chooser and runnable JOIN aggregation example to distinguish missing-row tests from multi-table totals. For the broader concept, see natural language database querying. This article focuses on preparing context and keeping meaning consistent through a conversation.
Current alternatives also expose context controls: DBeaver AI Chat can scope database context, and Google's authored-context guide describes business instructions and schema guidance. These are different product workflows, not evidence that every assistant supports the same controls.
For a compact product introduction, the worked database conversation on the homepage shows a paid-order question and a region-only follow-up. Use the context brief below when adapting that workflow to your own schema.
Should an AI assistant query live data or use an indexed copy?
Use a live database query when the answer needs the current permitted rows and an exact calculation. Use an indexed copy when finding relevant passages or records is the main task and its refresh policy meets your needs. Use a retained snapshot or sufficient history when the question asks what was true at an earlier time. These choices can coexist, but every answer needs a clear source and time boundary.
Here, “indexed copy” means a separate retrieval/search copy of source content. It does not mean a normal database index that accelerates a SQL query against the same tables. Adding a database index does not turn connected SQL into document retrieval.
| Question | Starting data path | What the answer must establish |
|---|---|---|
| How many open orders exist now? | Query approved current tables or reporting views | Status definition, readable scope, execution time and complete aggregate |
| Which policy explains this order exception? | Retrieve relevant passages from an approved document source or index | Document identity, version, effective date and applicable permissions |
| What did the Monday report show? | Retained Monday snapshot or reconstructable history | Snapshot identity and the metric definition used then |
| Why does this order conflict with the policy? | Separately retrieve the policy and query the order | Two evidence sources and their timestamps; do not treat a retrieved paragraph as a live row |
Microsoft documents both synced and federated connectors: one indexes external content, while the other retrieves it at request time. That is evidence of distinct architectural choices, not a claim that AskYourDatabase implements those Microsoft connectors or a general document-retrieval system.
“Live” also needs qualification. A query against a delayed replica, materialized view or imported reporting table can be fresh relative to that object while lagging the operational source. Record the last completed refresh where relevant. In PostgreSQL, Read Committed uses a new snapshot for each statement; two follow-up queries can legitimately see different committed data. A chat session does not itself freeze a database snapshot.
Reproduce a stale-copy mismatch
Consider four invented records. At a fictional 09:00, North has A=10, B=20 and C=5 usage units; South has X=99. A retrieval copy and a historical snapshot are made then. At 09:05, A changes to 12, B is deleted and a new North record D=8 appears. South is excluded from this reporting question.
| Evidence path | North record IDs | North units | Valid interpretation |
|---|---|---|---|
| Copy captured at 09:00, before refresh | A, B, C | 35 | The copied state at 09:00 |
| Current source after 09:05 changes | A, C, D | 25 | The current source state in this example |
| Largest one record from the old copy | B only | 20 | A selected-record subtotal, not the complete North total |
| Copy after a complete refresh | A, C, D | 25 | The refreshed state, after checking all changes arrived |
| Preserved 09:00 snapshot after refresh | A, B, C | 35 | The historical state, intentionally unchanged |
Download and run the offline freshness example with python3 freshness-example.py. It creates only an in-memory SQLite database and checks ten assertions covering source changes, copied rows, totals, selected-row incompleteness, refresh and retained history. The copy is modeled as a SQL table: no vector retrieval, AI response, production connector or permission enforcement is tested.
Three records exist in both the old and new North populations, so a row-count check alone misses the update, deletion and insertion. Reconcile IDs and values as well as totals. The 35-to-25 difference does not establish bad arithmetic or a hallucination: first inspect which state the answer used. Calling 35 “current at 09:05” would be wrong in this fixture; calling it the 09:00 snapshot would be correct.
The one-record subtotal demonstrates incomplete evidence, not the behavior of a particular search engine. Retrieving a handful of relevant rows cannot establish a whole-table aggregate unless a separate complete calculation supplies it. For an index pipeline, verify updates and deletions explicitly. Azure AI Search's indexer documentation distinguishes rerunning or resetting an indexer from deleting orphaned indexed documents. Refresh is a process to validate, not just a timestamp to display.
Check freshness and access before accepting the answer
Use these steps in an authorized staging evaluation with synthetic data. They are proposed product checks, not results observed from an AskYourDatabase deployment:
- Name the source. Record the connection, reporting object, metric version and relevant last completed refresh. State whether “now” means source state, replica state or an earlier snapshot.
- Change one fixture record. Ask the same bounded question before and after an approved update, insertion and deletion. Inspect the actual executed query and returned IDs; a fresh-looking answer may reuse earlier conversation content.
- Check a new conversation and a follow-up. Establish when each path performs another query and when it uses prior context. Label old evidence instead of silently presenting it as newly retrieved.
- Test revoked access separately. With test identities, confirm that a previously allowed record is no longer available to new requests after authorization changes. Also review already stored history, downloaded exports and copied index entries; blocking future reads does not erase earlier copies.
- Record failures honestly. If the live source is unavailable or freshness cannot be established, return that limitation or an explicitly labeled older result. Do not report an empty set as proof of zero activity after a failed query.
For AskYourDatabase, evaluate the supported database connection and the query that actually ran. Schema and training context help choose and explain a query; they are not a substitute for querying current rows. Schema embeddings used to select context are also different from a complete indexed copy of transactional rows. Do not infer that every follow-up reruns SQL, that connected access implies zero retained results, or that document training provides a permission-aware RAG service.
Use the security and data-flow guide for retained messages and model processing, and the audit evidence guide to link an answer to its query and execution record. The warehouse assistant versus maintained SQL guide addresses a separate decision: who owns repeatable metric logic. Once the data path is agreed, prepare the business context below and evaluate a limited workflow through Desktop or the embedded chatbot guide.
Prepare a reference guide the AI can use
Start with one reporting task and only its relevant tables. A complete database dump is rarely a useful explanation of business meaning. Have the data owner confirm the following fields in your context brief:
| Context | Example for this guide | Mistake it prevents |
|---|---|---|
| Entity and row grain | One user per context_users row; one event per context_events row | Counting events as people |
| Relationship | Many events can belong to one user; join on user_id | Joining on a display label or multiplying rows |
| Activity definition | At least one project_created or report_exported event | Treating a login as meaningful activity |
| Exclusions | Ignore test users and events without a known user | Counting internal tests or anonymous events |
| Reporting time | September 2026 in UTC, start inclusive and end exclusive | Including October or changing the timezone |
| Region meaning | User's current region, not region at event time | Claiming a historical breakdown the schema cannot provide |
| Output | Count distinct users; show zero for known regions without activity | Dropping an inactive region |
A foreign key explains how two tables relate. It does not tell the assistant which actions count as activity. Likewise, a boolean named is_test needs a rule saying whether to exclude it. If the team disagrees about the definition, settle that disagreement before interpreting a generated chart.
Keep definitions short enough to review. Give each metric an owner and review date. Store credentials in the connection configuration, never in a prompt or training example. For a large schema, begin with approved reporting views and document their grain; giving a view a friendly name does not make its joins or access controls correct.
Turn “How many active users?” into an answerable question
The first question is underspecified. It could mean logins, purchases, project creation, or any event. It also omits a period and whether test accounts count. A useful clarification establishes those facts before producing a confident number.
Here is the complete request for our synthetic example:
Count distinct non-test users with at least one project_created or
report_exported event from September 1, 2026 at 00:00 UTC up to, but
not including, October 1, 2026 at 00:00 UTC. Ignore events without a
known user. Return the count and state the filters used.
The sample has five users and eight events. User 1 has two qualifying September events in North. User 2 has only a September login, plus qualifying events just outside the period. User 3 has a qualifying South event exactly at the start. User 4 is a test user. User 5 is in West with no events. One event has no user ID. The expected answer is 2 active users, not three activity events.
Run the reference SQL file in one disposable local PostgreSQL session if you want to reproduce the example. It creates temporary tables and inserts synthetic rows before the three reference queries. Those temporary tables are a local demonstration, not a promise that a separate AI connection can access them. An administrator should prepare a separate authorized test dataset for product evaluation.
SELECT COUNT(DISTINCT u.user_id) AS active_users
FROM context_users AS u
JOIN context_events AS e ON e.user_id = u.user_id
WHERE u.is_test = false
AND e.event_type IN ('project_created', 'report_exported')
AND e.occurred_at >= TIMESTAMPTZ '2026-09-01 00:00:00+00'
AND e.occurred_at < TIMESTAMPTZ '2026-10-01 00:00:00+00';
active_users
2
Inspect the logic, not just whether SQL ran. Replacing COUNT(DISTINCT u.user_id) with COUNT(*) returns 3. Including login events also returns 3, for a different reason. Making the upper time boundary inclusive adds user 2's October event and again returns 3. The same wrong number can hide several different mistakes.
PostgreSQL's aggregate documentation explains the distinction between counting input rows and non-null values. Apply the intended entity count before discussing model quality.
For a custom chatbot implementation, use the database lookup and answer-return contract to distinguish verified results, empty matches and failures before composing the response.
Use follow-up questions without losing the original scope
Next ask: “Break that down by current user region, including regions with no active users.” Retain the activity definition, UTC dates and test-user exclusion. The new grouping should not silently redefine the metric.
SELECT u.region, COUNT(DISTINCT e.user_id) AS active_users
FROM context_users AS u
LEFT JOIN context_events AS e
ON e.user_id = u.user_id
AND e.event_type IN ('project_created', 'report_exported')
AND e.occurred_at >= TIMESTAMPTZ '2026-09-01 00:00:00+00'
AND e.occurred_at < TIMESTAMPTZ '2026-10-01 00:00:00+00'
WHERE u.is_test = false
GROUP BY u.region
ORDER BY u.region;
region | active_users
North | 1
South | 1
West | 0
The event filters stay in the join condition, so users with no matching event remain available for grouping. Counting distinct event-side user IDs gives West zero instead of counting the left-hand user row. This example includes regions represented by non-test users; an independent region dimension would be needed to show a region with no such users at all.
Then ask: “Now only count report exporters; keep the same period and show zero regions.” Change the event condition to e.event_type = 'report_exported'. Expected results are North 1, South 0, West 0. The download includes the complete query. Record what changed and what stayed fixed; conversational memory is something to check, not assume.
If you ask for “region at the time of activity,” this schema is insufficient. It stores only the user's current region. A responsible next step is to request event-time region data or a historical mapping. A plausible answer invented from the current field would misrepresent the question.
Apply the workflow in AskYourDatabase
AskYourDatabase supports connected analysis across database types including PostgreSQL, MySQL, SQL Server, BigQuery and Snowflake. Pick one permitted connection for the first evaluation. Supporting several connectors does not mean one query can automatically join all of them.
- Prepare a connection. Follow the connection instructions with a database owner. Use a limited reporting identity and an approved sample. The PostgreSQL setup guide covers connection and timezone checks; the MySQL guide covers its own setup and SQL boundaries.
- Add definitions and examples. The training documentation explains documentation and question/SQL examples. Desktop exposes the Train workflow; Website Chatbot has documentation and SQL example configuration. Adapt concise parts of the context brief to the controls in your version.
- Ask the known-answer question. Keep the reference result separate so you can distinguish an actual calculation from repeating an answer placed in context. Review query details through the available product or administrator tools; an embedded end-user response may not expose SQL.
- Check the follow-ups. Verify that adding a grouping or narrowing the event type preserves the other filters. Try a fresh conversation to distinguish reusable documentation from context available only in the current chat.
- Save the approved definition. Update documentation or examples deliberately. A correction in one conversation is not proof of permanent automatic learning or model fine-tuning.
This existing product screenshot illustrates the documentation workflow. It is not a screenshot of the synthetic active-user example or a measured accuracy result. The downloadable worksheet belongs to this article; the product does not automatically populate it for you.
For personal connected analysis, start with Desktop and check the current plans. For a website integration, use the embedded database chatbot guide, which covers a separate application and user-access workflow.
Diagnose a wrong answer before adding more examples
| Symptom | Inspect first | Next action |
|---|---|---|
| SQL fails to execute | Engine, actual column names, types and permissions | Correct the dialect or schema reference; do not grant broad access to hide the error |
| Count is too high | Row grain, duplicate activity and join cardinality | Compare the entity IDs against an independent reference |
| Count is plausible but different | Definition, exclusions, timezone and date boundaries | Restate the approved metric and inspect the applied filters |
| Follow-up changes the total unexpectedly | Which filters were retained or removed | Make the change explicit and rerun the original question |
| Answer uses an unavailable dimension | Whether the field or historical mapping exists | Request the missing data or narrow the question |
| Chart and explanation disagree | Actual returned rows, labels, units and aggregation | Validate the data before changing the visualization |
We checked eight local reference cases, including the base total, both follow-ups, three deliberately wrong queries and two data mutations. Duplicating a qualifying event leaves the distinct-user total at 2; changing the test user to a non-test user raises it to 3. These checks validate the example's logic, not AskYourDatabase's generated answers.
For a repeatable evaluation across more questions, use the text-to-SQL acceptance test kit. Keep held-out questions out of training, record actual failures, and rerun earlier cases after revising context. For a reusable report after the definition is stable, follow the SQL dashboard implementation guide.
Approve the data path before connecting sensitive information
Desktop's local database connection does not imply offline AI processing. Schema, questions and selected results can be included in model requests. Hosted Chatbot and private deployment have different storage and connection paths; read the security and data-flow documentation before choosing one.
Prompt instructions are not access controls. Restrict readable tables and rows using the approved database and application configuration, then test the actual user identity. Read-only credentials can still expose everything they can read and permit expensive queries. Set appropriate operational limits with the database owner. A synthetic result check cannot prove tenant isolation or transport security.
Frequently asked questions
How do I query a database using AI?
Connect a supported database through an approved account, supply the relevant schema and business definitions, then ask a question with a clear period and output. Check the executed query and results through the available product or administrator tools before relying on the answer.
What schema context should I give an AI database assistant?
Provide the relevant tables, row grain, keys, relationships, field meanings and valid codes. Add metric definitions, time zones, units, exclusions and a reviewed question-and-SQL example. Schema names alone rarely define terms such as active user or net revenue.
Can AI explore my database without SQL knowledge?
A connected assistant can help ask follow-up questions and explain results without requiring you to write every query. Database setup, permissions and important result checks still need a qualified owner. Missing data and ambiguous business definitions cannot be solved by fluent wording alone.
Does AskYourDatabase automatically learn every correction?
Do not assume a chat correction becomes permanent shared knowledge. Add approved documentation and SQL examples through the supported training workflow, then check a fresh conversation. These features provide context; they are not a guarantee of model fine-tuning or correct future answers.
Is the downloadable context brief a built-in product template?
No. It is an editable worksheet published with this guide. Review and adapt its fields, then transfer appropriate content into the documentation and SQL example fields supported by your product version. It does not automatically import a schema or configure permissions.
Can one AI question join all my database connections?
Support for several database engines does not establish cross-database federation. Verify the query engine, connection scope and approved data path. Use an authorized reporting layer or an explicitly supported integration when a question requires data from separate systems.
Should an AI assistant query live data or use an indexed copy?
Use live queries for current permitted rows and complete calculations, an indexed copy for retrieval when its refresh policy is acceptable, and retained snapshots or sufficient history for past-state questions. Verify the source, timestamp and permissions; a connected query can still read a delayed reporting source.
Does revoking database access delete earlier AI answers?
Do not assume so. New query authorization, retained conversation history, exported results and indexed copies are separate paths. Test new access with the actual user identity and review retention and deletion handling for each existing copy.
