---
title: "Give Your AI Your Schema and Metric Definitions So Its First SQL Query Runs"
description: "Document tables, joins, metric logic, reporting rules, and data quirks in files your AI reads, so generated SQL uses your schema instead of guesses."
canonical: "https://scalewithsearch.com/articles/ai-for-data-analysts"
date: "2026-01-28"
modified: "2026-09-25"
---
## Site navigation

- [Scale With Search](https://scalewithsearch.com/)
- Services
  - Local
    - [All services](https://scalewithsearch.com/services)
    - [AI visibility tracking](https://scalewithsearch.com/services/ai-visibility-tracking)
    - [Google Maps rank tracking](https://scalewithsearch.com/services/google-maps-rank-tracking)
    - [Local SEO](https://scalewithsearch.com/services/local-seo)
    - [Google Business Profile management](https://scalewithsearch.com/services/google-business-profile)
  - Website and search
    - [SEO solutions](https://scalewithsearch.com/seo)
    - [Technical SEO](https://scalewithsearch.com/seo/technical-seo)
    - [On-page and content SEO](https://scalewithsearch.com/seo/on-page-and-content-seo)
    - [Semantic SEO and topical authority](https://scalewithsearch.com/seo/semantic-seo-and-topical-authority)
    - [Custom SEO tools](https://scalewithsearch.com/seo/custom-seo-tools)
    - [Site build](https://scalewithsearch.com/work#site-build)
    - [Whole website fix](https://scalewithsearch.com/work#whole-website-fix)
  - AI functions
    - [AI operations](https://scalewithsearch.com/ai-systems)
  - First step
    - [Working session](https://scalewithsearch.com/audit)
  - Start here
    - [Send your brief](https://scalewithsearch.com/work#send-your-brief)
    - [Example scope](https://scalewithsearch.com/work#review-the-example-scope)
    - [Prices and terms](https://scalewithsearch.com/work#prices-and-terms)
- Industries
  - Agencies
    - [SEO agencies and consultants](https://scalewithsearch.com/for/seo-agencies-and-consultants)
    - [Marketing agencies and freelancers](https://scalewithsearch.com/for/marketing-agencies-and-freelancers)
    - [AI visibility check for SEO agencies](https://scalewithsearch.com/check/seo-agencies-and-consultants)
    - [Marketing and SEO agencies](https://scalewithsearch.com/for/#group-agencies)
  - Browse by business
    - [Trades and field service](https://scalewithsearch.com/for/#group-trades)
    - [Real estate agents and teams](https://scalewithsearch.com/for/real-estate)
    - [Health, wellness, and animal care](https://scalewithsearch.com/for/#group-practices)
    - [Chiropractic and wellness practices](https://scalewithsearch.com/for/chiropractic-and-wellness-practices)
    - [Law, finance, and IT](https://scalewithsearch.com/for/#group-professional)
    - [Machine shops and manufacturers](https://scalewithsearch.com/for/#group-manufacturing)
    - [Restaurants, shops, studios, and nonprofits](https://scalewithsearch.com/for/#group-local-services)
  - [All industries](https://scalewithsearch.com/for/)
- Resources
  - Free tools
    - [AI visibility check](https://scalewithsearch.com/check)
    - [All free tools](https://scalewithsearch.com/tools/)
    - [Free starter kit (.zip)](https://scalewithsearch.com/kit/business-memory-starter-kit.zip)
  - Guides
    - [AI-native library](https://scalewithsearch.com/ai-native)
    - [Industry intelligence](https://scalewithsearch.com/intelligence)
    - [Office job guides](https://scalewithsearch.com/guides/)
    - [Business memory](https://scalewithsearch.com/articles/business-memory-for-ai-agents-guide)
    - [Agent governance](https://scalewithsearch.com/articles/ai-agent-governance-guide-small-business)
    - [Ownership and migration](https://scalewithsearch.com/articles/leaving-vendor-ai-memory-guide)
  - Articles
    - [All articles](https://scalewithsearch.com/articles/)
- About
  - Evidence
    - [Proof](https://scalewithsearch.com/proof)
  - Scale With Search
    - [About](https://scalewithsearch.com/about)
    - [How it works](https://scalewithsearch.com/how-it-works)

# Give Your AI Your Schema and Metric Definitions So Its First SQL Query Runs.

You need monthly recurring revenue (MRR) by customer segment. You ask AI for the SQL.

The query looks reasonable. You run it. Error: table `customers` does not exist. Your table is `accounts`. MRR is not a column; you calculate it from `subscription_value` and `billing_frequency`. Customer segment is stored as `tier_id`, not `segment_name`.

You paste the schema, explain the MRR calculation, and clarify the tier mapping. The second query is closer, but it joins on `user_id` when it should join on `account_id`, because your users table is not your accounts table.

Twenty minutes later the SQL works. Tomorrow, for another report, the assistant has forgotten the schema and you start over. An analyst does not need AI that writes generic SQL. You need AI that knows your database.

## Why a generic assistant writes broken SQL

ChatGPT can write SQL. It cannot write your SQL, because it does not know your schema or your business logic. It also does not know how your tables relate, your naming conventions, or what a field means in your company.

You work with five kinds of knowledge that the assistant does not have:

- the schema: table names, column names, data types, relationships;
- business logic: how revenue is calculated, what "active user" means, how churn is defined;
- reporting formats: what stakeholders want, how to group, what is a metric and what is a dimension;
- data quality: which columns are reliable, which have null problems, which need cleaning;
- recurring queries: the monthly reports and dashboards that run the same way each time.

Without them, table names, column names, and join logic are guesses. Sometimes the guess is close. Usually it is wrong.

## What the files must record

The schema file records your actual tables, columns, data types, primary keys, foreign keys, and indexes. It says that `accounts` exists and `customers` does not.

The business logic file records how revenue is calculated. It also defines "active user": a login in the last 30 days, a purchase, or an app open. It defines churn. It says which columns feed which metric.

The same file records relationships: how users relate to accounts, how transactions relate to subscriptions, which joins work, and which joins create duplicates.

The reporting file records stakeholder formats, default date ranges, rounding rules, and whether a report groups by month, week, or day.

The quirks section records the legacy column that no longer updates and the table with null problems. It also names the slow join to avoid and the calculation with edge cases.

## Build four context files

Claude Code reads a file named `CLAUDE.md` when a session starts. Use it to point to four files and to set rules:

```text
## Data context
Schema: context/database-schema.md (generated; do not edit by hand)
Metrics: context/business-logic.md
Reporting: context/reporting-standards.md
Saved queries: context/common-queries.md

## Rules
Use only tables and columns that appear in database-schema.md.
Use metric definitions from business-logic.md. Do not invent a definition.
Avoid tables marked deprecated.
Queries are read-only. Never write UPDATE, DELETE, or DDL.
```

`database-schema.md` lists each table and what it stores, columns with types and descriptions, keys, common joins, and tables to avoid. Generate it from the database so it does not drift. In Postgres, a query on `information_schema.columns` returns the table, column, and type for each column:

```sql
SELECT table_name, column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public'
ORDER BY table_name, ordinal_position;
```

Write the result into the file on a schedule. Add descriptions by hand in a second file.

`business-logic.md` holds metric formulas for MRR, churn, lifetime value (LTV), and customer acquisition cost (CAC). It also holds business definitions such as active user and qualified lead, segmentation rules, and edge cases.

`reporting-standards.md` holds stakeholder formats, default date ranges for monthly and quarterly reports, grouping preferences, and chart standards.

`common-queries.md` holds the reports that run on a schedule and the SQL pattern for each.

A business logic entry can be this short:

```text
## MRR
Source: subscriptions (join accounts on account_id; never on user_id)
Formula: monthly plans = subscription_value; annual plans = subscription_value / 12
Include: status = 'active' on the last day of the month
Segment: accounts.tier_id (1 = starter, 2 = growth, 3 = enterprise)
Round: whole dollars in stakeholder reports
Owner: finance analytics; last confirmed 2026-07-01
```

## Before and after: schema and metric definitions for AI SQL

Before: "Write SQL for MRR by customer segment." The assistant uses table `customers` (does not exist), column `mrr` (does not exist), and `segment` (stored as `tier_id`). You paste the schema, explain MRR, and clarify the tiers. The rewrite joins on `user_id`. You fix the join. It runs, but slowly, because it reads a deprecated table. Twenty minutes gone, and tomorrow you repeat it.

After: the same prompt. The assistant reads the schema, business logic, and reporting files and returns:

```sql
SELECT a.tier_id,
       date_trunc('month', s.period_end) AS month,
       ROUND(SUM(CASE s.billing_frequency
                   WHEN 'monthly' THEN s.subscription_value
                   WHEN 'annual'  THEN s.subscription_value / 12.0
                 END)) AS mrr
FROM accounts a
JOIN subscriptions s ON s.account_id = a.account_id
WHERE s.status = 'active'
GROUP BY a.tier_id, date_trunc('month', s.period_end)
ORDER BY month, a.tier_id;
```

It uses the accounts table, calculates MRR by the documented rule, joins on `account_id`, groups by `tier_id`, and rounds as the stakeholders expect. You run it and check the totals against last month's finance report.

Next request: "Add churn rate to that report." The assistant reads the churn definition in `business-logic.md`, uses the right columns, and extends the query. You check the first run by hand.

## A worked setup: schema and metric definitions for AI SQL

An analyst at a software company sets up the four files, mostly by copying documentation that already exists. When she asks for SQL, the assistant knows the schema, the logic, and the reporting standards. When she asks for Python to clean data, the assistant knows which columns have null problems. When she asks for a dashboard query, it knows what stakeholders want.

When the schema changes, she regenerates `database-schema.md`, and every later query uses the new schema. When a definition changes, such as a new MRR rule or churn window, she updates `business-logic.md` with the date and the owner. The assistant follows the new rule. When the assistant repeats a mistake, she writes the fix into the file. [How corrections become part of the system](/articles/corrections-become-system-memory) explains why that works better than a chat reminder.

The files also become the data dictionary. New analysts read them to onboard. Stakeholders read them to see where a number comes from. Plain Markdown keeps them readable by people and tools alike; see [why plain text is the durable layer for AI memory](/articles/plain-text-ai-memory).

## Test before you trust

Run three checks after setup, and again after each schema change.

1. Ask for a query on a table that does not exist. Pass: the assistant says it is not in the schema file. Fail: it invents columns.
2. Ask for MRR. Pass: the result matches the finance report for a closed month. Fail: fix the definition, not the query.
3. Ask for a query that deletes rows. Pass: the assistant refuses under the read-only rule. Fail: remove write permissions from the credential it uses.

The broader method for proving a run before it touches real systems is in [how to test an AI agent before production](/articles/test-an-ai-agent-before-production). Which files load first, and why, is covered in [what context should an agent read before it starts](/articles/what-context-should-an-agent-read).

## Keep the schema file from drifting

A schema file that is three migrations behind is worse than none. The assistant trusts it and writes queries against columns that moved.

Set two rules. First, regenerate `database-schema.md` on a schedule, such as every Monday, or as a step in your migration process. Second, add the generation date to the top of the file. Then add a rule to `CLAUDE.md`: if the schema file is older than seven days, say so before you write a query.

Keep hand-written descriptions in a second file, `context/schema-notes.md`, keyed by table and column. The generated file never overwrites them, and the assistant reads both.

## Data limits

Put structure in the files, not customer rows. Claude Code sends the content it reads, including query results it sees, to the model provider over the network ([Claude Code: Data usage](https://code.claude.com/docs/en/data-usage)). If the assistant runs queries, give it a read-only credential with access only to the schemas it needs. Keep personal data out of the prompts and out of the results it reads.

----

```text
                  .|########||.                                       .|########||.                                       .|########||.
               |##||.      .||##|.                                 |##||.      .||##|.                                 |##||.      .||##|.
             |#|.              .|#|.                             |#|.              .|#|.                             |#|.              .|#|.
           |#|                    |#|                          |#|                    |#|                          |#|                    |#|
         .#|                        |#.                      .#|                        |#.                      .#|                        |#.
        .#.                          .#|                    .#.                          .#|                    .#.                          .#|
       |#.                            .#|                  |#.                            .#|                  |#.                            .#|
      |#             ......             #|                |#             ......             #|                |#             ......             #|
     .#           ||#########|           #|              .#           ||#########|           #|              .#           ||#########|           #|
    .#.         |######||######|.        .#.            .#.         |######||######|.        .#.            .#.         |######||######|.        .#.
    #.        .##|###|##|#|######|        .#            #.        .##|###|##|#|######|        .#            #.        .##|###|##|#|######|        .#
   ||        |##|#||||||||||||#||#|        ||          ||        |##|#||||||||||||#||#|        ||          ||        |##|#||||||||||||#||#|        ||
   #        |#||||||||||||||||||||#|        #.         #        |#||||||||||||||||||||#|        #.         #        |#||||||||||||||||||||#|        #.
  ||       |#||||||||||||||||||||||#|       ||        ||       |#||||||||||||||||||||||#|       ||        ||       |#||||||||||||||||||||||#|       ||
  #       .#||||||||||||||||||||||||#|       #        #       .#||||||||||||||||||||||||#|       #        #       .#||||||||||||||||||||||||#|       #
 ||   ....|||#||||||##|#|||#|#||##||||....|. ||      ||   ....|||#||||||##|#|||#|#||##||||....|. ||      ||   ....|||#||||||##|#|||#|#||##||||....|. ||
 #.  .  ....|#  ....#|||   ||| .#|||  ....#. .#      #.  .  ....|#  ....#|||   ||| .#|||  ....#. .#      #.  .  ....|#  ....#|||   ||| .#|||  ....#. .#
 #   .  ||||#| .#####||  . .#| .#|||  ||||#   #.     #   .  ||||#| .#####||  . .#| .#|||  ||||#   #.     #   .  ||||#| .#####||  . .#| .#|||  ||||#   #.
.|   |||||  #. |#|||||. ||  #. |#||. .|||||   ||    .|   |||||  #. |#|||||. ||  #. |#||. .|||||   ||    .|   |||||  #. |#|||||. ||  #. |#||. .|||||   ||
||   |....  #. ....|#.      |. ...|. ....||   ||    ||   |....  #. ....|#.      |. ...|. ....||   ||    ||   |....  #. ....|#.      |. ...|. ....||   ||
#.  .||||||##||||||##||####|||||||#||||||#|   .#    #.  .||||||##||||||##||####|||||||#||||||#|   .#    #.  .||||||##||||||##||####|||||||#||||||#|   .#
#    .||####|###########################|.     #    #    .||####|###########################|.     #    #    .||####|###########################|.     #
#      .#||||||.#.|| # |. ..# #| #|||||#|      #    #      .#||||||.#.|| # |. ..# #| #|||||#|      #    #      .#||||||.#.|| # |. ..# #| #|||||#|      #
#      .#|||||| ..  |# ## |#| ...#|#|||#|      #    #      .#|||||| ..  |# ## |#| ...#|#|||#|      #    #      .#|||||| ..  |# ## |#| ...#|#|||#|      #
#      .#|||#|# .# .#| #| ##|.#..#|||||#|      #    #      .#|||#|# .# .#| #| ##|.#..#|||||#|      #    #      .#|||#|# .# .#| #| ##|.#..#|||||#|      #
#      .#||||||############|######|||||#|      #    #      .#||||||############|######|||||#|      #    #      .#||||||############|######|||||#|      #
#   |...||#||||||#||||#|#||||||#|||||#||| |.|  #    #   |...||#||||||#||||#|#||||||#|||||#||| |.|  #    #   |...||#||||||#||||#|#||||||#|||||#||| |.|  #
#. .. ||||# .|||##|.  |#| .|| || .|||#. #|  # .#    #. .. ||||# .|||##|.  |#| .|| || .|||#. #|  # .#    #. .. ||||# .|||##|.  |#| .|| || .|||#. #|  # .#
|| |  ...||  ...##| |  #| .|. |. #####  .. .| ||    || |  ...||  ...##| |  #| .|. |. #####  .. .| ||    || |  ...||  ...##| |  #| .|. |. #####  .. .| ||
|| ||||| || ||||#|  .  |. |. |#. ||||| |#| || ||    || ||||| || ||||#|  .  |. |. |#. ||||| |#| || ||    || ||||| || ||||#|  .  |. |. |#. ||||| |#| || ||
.# |.....#|....|#.||||.|||##.|#|....||.#||.#. #.    .# |.....#|....|#.||||.|||##.|#|....||.#||.#. #.    .# |.....#|....|#.||||.|||##.|#|....||.#||.#. #.
 #.|||||||#############################| ||| .#      #.|||||||#############################| ||| .#      #.|||||||#############################| ||| .#
 ||       ##||#||#||||||#||#||#||#||##.      ||      ||       ##||#||#||||||#||#||#||#||##.      ||      ||       ##||#||#||||||#||#||#||#||##.      ||
  #       .#|||||||||#||#|||||||||||#|       #        #       .#|||||||||#||#|||||||||||#|       #        #       .#|||||||||#||#|||||||||||#|       #
  ||       |#||||||||||||||||||||||#|       ||        ||       |#||||||||||||||||||||||#|       ||        ||       |#||||||||||||||||||||||#|       ||
  .#        |#||||||||||||||||||||#|        #.        .#        |#||||||||||||||||||||#|        #.        .#        |#||||||||||||||||||||#|        #.
   ||        |#||||||||||||||||||#|        ||          ||        |#||||||||||||||||||#|        ||          ||        |#||||||||||||||||||#|        ||
    #.        .######|#|#########|        .#            #.        .######|#|#########|        .#            #.        .######|#|#########|        .#
    .#.         |#####||||#####|         .#.            .#.         |#####||||#####|         .#.            .#.         |#####||||#####|         .#.
     |#           ||########||           #.              |#           ||########||           #.              |#           ||########||           #.
      |#             ......             #|                |#             ......             #|                |#             ......             #|
       |#.                            .#|                  |#.                            .#|                  |#.                            .#|
        |#.                          .#.                    |#.                          .#.                    |#.                          .#.
         .#|                        |#.                      .#|                        |#.                      .#|                        |#.
           |#|                    |#|                          |#|                    |#|                          |#|                    |#|
            .|#|.              .|#|.                            .|#|.              .|#|.                            .|#|.              .|#|.
               |##||.      .||##|                                  |##||.      .||##|                                  |##||.      .||##|
                 .||########||.                                      .||########||.                                      .||########||.

Scale With Search  2026  [scalewithsearch.com](https://scalewithsearch.com)
```
