How to Use AI for Data Analysis (Without Trusting Made-Up Numbers)

How to use AI for data analysis: make the model write SQL or Python that runs on your real data, show its work, and check every number before it ships.

By Nov 26, 2026 8 min read

ai data analysisllmsqlpythonanalytics
SHOW THE QUERY

To use AI for data analysis, don't ask the model to read your data and tell you what it sees. Give it a tool that runs code, a short description of your tables, and a specific question. It writes SQL or Python, runs it on the real data, and hands back three things: the query, the result, and a plain-language answer. You check one number you already trust, then use the rest.

That's the whole method. The model is a fast analyst who writes code. It is not a calculator, and it is not a source of truth. Every number in the final answer should trace back to a query you can rerun.

This guide covers the setup I use for both one-off spreadsheets and recurring questions on live company data.

01TL;DR

  • Numbers come from code, never from the model's head. Give it a Python sandbox or a read-only SQL connection and require that every figure comes out of an executed query.
  • Write a data dictionary once. Table names, what each column means, units, time zone, and the traps (test accounts, refunds, duplicate rows). This one file fixes most wrong answers.
  • Define your metrics in writing. "Active user," "revenue," and "churn" mean whatever your team says they mean. The model can't guess that.
  • Make it show its work. Query, result table, and answer in every response, so a wrong number is visible in 10 seconds.
  • Check against a known total. Before you trust an analysis, compare one figure to your dashboard or invoice export.

02Why "just paste the data in" fails

The fastest way to get a wrong answer is to paste 2,000 rows into a chat and ask "what's our average order value?" Three things go wrong.

First, the model does arithmetic by predicting tokens. It's good at math-shaped text and unreliable at summing 2,000 numbers. You'll get a plausible figure that's off by a few percent, and nothing tells you it's off.

Second, long pasted tables eat the context window and get truncated or skimmed. The model may only really attend to the first and last few hundred rows. (More on this in what is a context window.)

Third, it guesses what columns mean. Is amount in cents or dollars? Does status = 'closed' mean won or lost? A guess becomes a confident sentence.

The fix for all three is the same: move the work out of the model and into code.

03Step 1: Give the model a tool that runs code

There are two setups, depending on where the data lives.

For a file (CSV, Excel, export). Use a chat app with file upload and code execution (ChatGPT's data analysis, Claude's analysis tool, or a local Jupyter setup with an agent). The model loads the file with pandas, inspects it, and computes answers in Python. Files up to tens of thousands of rows work well. Past that, load the file into a local database like DuckDB first and query it.

For live data (a warehouse or production database). Connect the model through a read-only role, either with a SQL tool you define or an MCP server for your database. The role should only see the schemas the analysis needs, have a statement timeout, and cap rows returned. How to connect an AI agent to your database walks through the permission setup in detail.

Either way, the rule is the same. If a number appears in the answer, it came out of code that ran.

A good first message in a file session looks like this:

Prompt
Load orders.csv. Before answering anything, print the column names, dtypes, row count, null counts per column, and 5 sample rows.
Do not compute any metric yet.

That forces a look at the actual shape of the data before any conclusions, and it surfaces the mess (nulls, mixed date formats, a column of strings that should be numbers) while it's cheap to fix.

04Step 2: Write a data dictionary and metric definitions

This is the step most people skip, and it's where most wrong answers come from.

Create one markdown file per dataset. Keep it short. Mine look like this:

Prompt
# orders (warehouse.analytics.orders)
- one row per order; order_id is unique
- amount_cents: integer, USD cents, BEFORE refunds
- created_at: UTC timestamp
- status: 'paid' | 'refunded' | 'failed' (failed = never charged)
- is_test: true for internal test orders, always exclude

# metric definitions
- revenue = sum(amount_cents)/100 where status = 'paid' and not is_test
- AOV = revenue / count(distinct order_id), same filters
- active customer = at least one paid order in the trailing 30 days
- weeks start Monday, reported in America/New_York

Pass this file in with every question (as a system prompt, a project file, or a skill). Now "what was revenue last week?" has exactly one right answer, and the model knows how to get it.

Two lines in that file matter more than they look: the units (cents, not dollars) and the exclusions (is_test). Those two cause more silent errors than anything else I see.

05Step 3: Ask specific questions and demand the work

Vague questions get vague analysis. "Find insights in our sales data" produces a list of generic observations. A specific question produces a number you can act on.

Compare:

  • Vague: "How are sales doing?"
  • Specific: "Weekly revenue for the last 12 weeks, with week-over-week percent change. Flag any week that moved more than 15%."

Then lock the response format. I add this to the system prompt:

Prompt
For every answer, return in this order:
1. The exact SQL or Python you ran
2. The result as a table (max 50 rows)
3. A 2-4 sentence answer that only cites numbers from the result
4. Any assumption you made that isn't in the data dictionary

Item 4 is the one that saves you. When the model writes "assumed refunds are excluded," you see it immediately instead of discovering it in a board deck.

For multi-step analysis (a cohort retention table, a funnel by acquisition channel), ask for a short plan first: which tables, which joins, which filters. Approve the plan, then let it run. Fixing a wrong join in a plan takes one sentence. Fixing it after five follow-up charts takes an hour.

06Step 4: Verify before you trust

Every analysis gets one cheap check before it leaves your screen. Pick whichever fits:

  • Known total. Compare last month's revenue from the query to your Stripe or accounting export. If they match within rounding, the filters are right.
  • Row count sanity. Ask for the row count at each step of a join. If 10,000 orders become 14,000 rows after joining customers, there's a fan-out from duplicate keys.
  • Recompute a different way. Ask for the same metric with a different method (SQL vs pandas, or count(distinct) vs a group-by). Two methods agreeing is strong evidence.
  • Spot-check one record. Pick one customer and trace their rows by hand. Ten seconds, and it catches timezone and date-boundary bugs.

If a check fails, don't ask the model to "fix the number." Ask it to explain the gap between the two figures. The explanation usually names the bug (refunds counted twice, test orders included, UTC vs local week boundaries).

How to reduce AI hallucinations covers the general version of this. For data work, the short rule is: the model can be wrong in the prose, but the query is the evidence.

07Step 5: Turn repeat questions into saved queries

Once a question gets asked twice, it shouldn't be generated fresh a third time. Save the approved query.

Keep a folder of named, reviewed queries (weekly_revenue.sql, trailing_30_active.sql) and tell the model to check that folder before writing new SQL. Now recurring questions return the same number every time, and new questions still get the flexibility of generated code.

This is also where analysis becomes automation. A scheduled job runs the saved queries Monday morning, the model writes a five-line summary of what moved and why, and it posts to Slack. If you want that pattern in more detail, the write loops, not prompts resource shows how I structure recurring AI jobs so they run without me.

08What AI is good at here (and what it isn't)

Good at:

  • Writing the first draft of a gnarly SQL query (window functions, cohort tables, date spines)
  • Cleaning messy exports: inconsistent date formats, split name fields, currency strings
  • Exploratory passes: "show me the distribution of order size by channel and point out anything odd"
  • Explaining a query someone else wrote
  • Turning a result table into a clear chart and a short written summary

Not good at:

  • Knowing your business definitions without being told
  • Arithmetic done in prose instead of code
  • Causal claims. It will happily say a price change "caused" a drop. Correlation in a table is not a cause, and you should cut that sentence.
  • Noticing that the data itself is wrong (a broken tracking event, a missing week of imports) unless you ask it to check for gaps

One prompt I add to exploratory sessions: "Before analyzing, check for missing dates, sudden zero values, and duplicate IDs, and report them." That catches pipeline problems before they turn into a fake trend.

09The bottom line

Using AI for data analysis works when you treat the model as an analyst who writes code, not an oracle who knows answers. Give it code execution or a read-only database connection, a one-page data dictionary with your metric definitions, and a response format that always includes the query. Verify one number against something you trust, then save the queries you reuse.

Set that up once and a question that used to take an afternoon of spreadsheet work takes two minutes, with a query you can rerun to prove it.

I share setups like this every week in the OpusJake newsletter, including the prompts and files I actually use.

FAQ

Frequently asked

How do I use AI for data analysis?

Give the model a tool that runs code (a Python sandbox or a read-only SQL connection) plus a short description of your data: table names, column meanings, units, and known quirks. Ask a specific question, have it write and run the query, and require it to return the query, the result table, and a plain-language answer together. Check the totals against a number you already trust before you use the output.

Can ChatGPT or Claude analyze a spreadsheet?

Yes. Both can take an uploaded CSV or Excel file and analyze it by writing and running Python in a sandbox. That works well for files up to tens of thousands of rows. For live business data, connect the model to your warehouse with a read-only role instead of exporting files, so the answer always reflects current numbers.

Is AI accurate for data analysis?

It is accurate when the numbers come from code that ran on your data, and unreliable when the model does math in its head or guesses column meanings. Most wrong answers come from ambiguous definitions, like what counts as an active user or whether revenue includes refunds. Write those definitions down and pass them in with every question.

What is the best AI tool for data analysis?

The tool matters less than the setup. Any frontier model with a code execution tool will do. For one-off files, use the chat app with file upload. For recurring questions on company data, use an agent connected to your warehouse through a read-only connection or MCP server, with a metric definitions file and a saved library of approved queries.

Build it yourself

Opus Lab is a way for leaders to become more AI fluent, for free. Bring what you just read and build it with the room.

Join Opus Lab

Newsletter

Get the next one first

New playbooks, prompts and skills go to the list the day they ship. One email, unsubscribe whenever.

More from the blog

All 77 articles