How to Use Claude for SQL Queries: Plain English In, Checked SQL Out

Claude writes syntactically valid SQL almost every time. The risk is not a syntax error, it is a query that runs, returns a confident number and is wrong because Claude guessed how your tables join. Give it the schema, name the database and version, make it state its assumptions before it writes, and check the row count against what you expected. Do that and it becomes the fastest way to go from a question in English to a query you can trust.

What does Claude need to know before it writes a query?

Three things, in this order of importance:

0:15 · loop 同樣的 AI,同樣的問題。一個檔案讓它成為專家。
  • The schema. Table names, columns, types, primary and foreign keys. Not a description of it: the actual DDL. You can pull it in one query (below) and paste it once per conversation.
  • The dialect and version. PostgreSQL 16 and MySQL 8 disagree on date functions, string matching, upserts and more. Say which you run.
  • The grain of the answer. "Revenue by customer" can mean one row per customer, per order or per order line. Say what one row of the result represents.

To get the schema without hand-copying it, run this in PostgreSQL or MySQL and paste the output:

-- Works in PostgreSQL and MySQL (information_schema) SELECT table_name, column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = '[public OR your_database_name]' ORDER BY table_name, ordinal_position;

That lists columns but not relationships. Add your foreign keys by hand in one line each ("orders.customer_id -> customers.id") or paste the CREATE TABLE statements from your migrations. Relationships are where wrong answers come from, so this is the line not to skip.

The skill this guide is built on
AI SQL Query Generator for Claude and ChatGPT
AI SQL Query Generator $19 one-time · or in Library

Describe the data you want in plain English and get a readable query for PostgreSQL, MySQL, SQL Server, SQLite or BigQuery, with a line-by-line explanation, the indexes that make it fast and the mistakes that would have returned the wrong number.

Get the SQL Query Generator →

How do you turn a question into SQL that returns the right number?

Make Claude write its assumptions before the query. You will read three lines of assumptions faster than you will debug fifty lines of SQL, and a wrong assumption is visible immediately.

Database: [PostgreSQL 16] Schema: [PASTE information_schema OUTPUT OR CREATE TABLE STATEMENTS] Relationships: - [orders.customer_id -> customers.id] - [order_items.order_id -> orders.id] Question: [Revenue per customer for Q3 2026, only paid orders, top 20, include customers with one order] One row of the result = [one customer] Before writing SQL: 1. List every assumption you are making (what counts as revenue, which status means paid, how refunds are treated, which timezone the dates are in). 2. Name any join that could multiply rows, and how you will prevent it. Then write the query: - CTEs with readable names, no nested subqueries more than one level deep - explicit column list, never SELECT * - a comment above each CTE saying what one row of it represents Finally, give me a second query that returns only the row count and the total of the main metric, so I can sanity-check it against another report.

Point 2 is the one that saves you. Join orders to order_items and then sum an order-level column such as shipping, and every order with three items counts its shipping three times. Claude knows this pattern well; it just does not look for it unless asked.

How do you check a query before you trust it?

Run it, then hand the result back with what you expected. A model is a far better reviewer of a query when it can see the evidence.

I ran this query: [PASTE QUERY] It returned [1,284] rows. I expected roughly [about 900, one per active customer]. Total revenue came to [$412,880]. Finance reports [$377,150] for the same period. Do not rewrite the query yet. First: 1. List the likely reasons for the extra rows, most likely first. 2. For each, give me a small diagnostic query that would prove or rule it out (for example, a GROUP BY on the key with HAVING COUNT(*) > 1). 3. Tell me which difference in revenue each reason would explain. Only after I run the diagnostics, propose the fix.

This is the habit the AI SQL Tutor drills: when the result set is the wrong size, ask where the extra rows came from before touching the query. It is also the fastest way to learn why a LEFT JOIN quietly turned into an inner join because of a condition in the WHERE clause.

If you want to understand the query, not just get one
AI SQL Tutor for Claude and ChatGPT
AI SQL Tutor $19 one-time · or in Library

For when you can write a SELECT with a WHERE and not much more. It teaches the order the database actually runs your clauses, then joins, fan-out, NULLs, CTEs and window functions, and asks how many rows you expected instead of rewriting your query for you.

Get the SQL Tutor →

How do you make a slow query faster with Claude?

Give it the plan, not just the query. Without the plan, Claude can only list generic advice. With it, it can point at the step that costs the time.

This query takes [14 seconds] on [PostgreSQL 16], tables: orders [~8M rows], order_items [~30M rows]. [PASTE QUERY] EXPLAIN (ANALYZE, BUFFERS) output: [PASTE PLAN] -- MySQL 8: use EXPLAIN ANALYZE Existing indexes: [PASTE \d orders OUTPUT OR SHOW INDEX FROM orders] 1. Which node in the plan takes most of the time, and why (seq scan, bad row estimate, sort spilling to disk, nested loop over many rows)? 2. Suggest at most two indexes, with the exact CREATE INDEX statement, and explain which part of the plan each one changes. 3. If a rewrite helps more than an index, show it, and confirm it returns the same rows. 4. Tell me what to measure after the change.

Two cautions. Indexes speed up reads and slow down writes, so on a busy table ask Claude what each index costs, not only what it saves. And treat "add an index" as a proposal to test on a copy, not something to run on production because a chat said so.

Where do PostgreSQL and MySQL differ in ways Claude gets wrong?

If you do not name the dialect, Claude mixes them. The usual suspects:

Task PostgreSQL MySQL 8
Case-insensitive match ILIKE LIKE (case-insensitive with the default collations)
Upsert INSERT ... ON CONFLICT (...) DO UPDATE INSERT ... ON DUPLICATE KEY UPDATE
Truncate a date to month date_trunc('month', created_at) DATE_FORMAT(created_at, '%Y-%m-01')
String concatenation a || b CONCAT(a, b)
Returning changed rows RETURNING * Not supported; select again

If you only need a single-table SELECT with filters and a sort, our free SQL query builder assembles it from a form without a chat at all.

Where should you not let Claude near your database?

  • Write access. Run its queries with a read-only user. Anything with UPDATE or DELETE gets read by a person, run inside a transaction, and checked with a SELECT of the same WHERE clause first.
  • Real customer data in the prompt. It needs the schema and, at most, a few anonymised sample rows. It does not need your customers' emails.
  • Business definitions. What counts as an active user or recognised revenue is your company's decision. Claude will pick a reasonable one silently unless you make it list its assumptions.
  • Columns it has not seen. Ask about a table you did not paste and it may invent a plausible column name. If a query references a column you do not recognise, that is the reason.
One file, or the whole library
Every skill in this guide, loaded inside your AI for $9 a month

Buying a file is the right call if you need one specialist once. If you work with data every week and also need a database engineer, an Excel formula writer or a Python analyst, the KissMySkills Library is cheaper: one connector puts all 2,500+ skills, prompt packs and agents inside Claude, ChatGPT, Claude Code or Cursor, and the skill loads when you ask for it by name. Library is $9 a month or $59 a year, starts with a free trial, no card needed, and you can cancel anytime.

Start your free trial Why a subscription beats buying files · See plans

How do you load a skill into Claude?

Two ways. With a one-time file, add it in the Claude app under Customize → Skills (code execution has to be on, under Settings → Capabilities), or paste its contents into a Claude Project's instructions, a ChatGPT custom GPT or a Gemini Gem. Our step-by-step install guide covers each app. With Library, you connect KissMySkills to Claude, ChatGPT or Cursor once, then ask for the specialist by name in the chat you already use.

For schema design, migrations and query plans across a whole system, Oleg - Database Engineer is the specialist to load next.

In summary:

Paste the schema and relationships, name the database, make Claude list its assumptions and the joins that could multiply rows, then check the row count and the total against something you already trust. For writing queries from plain English: AI SQL Query Generator ($19). For learning to write them yourself: AI SQL Tutor ($19). Both are also in Library at $9 a month.

AI Skill · Works with Claude & ChatGPTAI SQL Query Generator for Claude and ChatGPT

AI SQL Query Generator

Plain English in, a query for your database out, with the explanation, the index advice and the row-count checks that catch a wrong answer before it reaches a report.

$19
Get the SQL Query Generator →

Or get it with every other skill in Library, $9 a month. Free trial, no card needed.

KissMySkills is a marketplace of 2,500+ AI skills, agents, prompt packs & free tools for Claude, ChatGPT & any AI chat.

Frequently asked questions

Can Claude write SQL queries from plain English?

Yes, and the syntax is usually right. Accuracy depends on context: paste the schema with relationships, name the database and version, and say what one row of the result represents. Ask it to list its assumptions before writing the query.

Should I give Claude access to my database?

Not with write access. Paste the schema and a few anonymised sample rows instead, run the queries yourself with a read-only user, and review anything containing UPDATE or DELETE inside a transaction before committing.

Why does a Claude query return too many rows?

Usually a join that multiplies rows, such as joining orders to order items and then summing an order-level column. Ask Claude to name the joins that could fan out and give you a diagnostic query with GROUP BY and HAVING COUNT(*) greater than 1.

Does Claude know the difference between PostgreSQL and MySQL?

It knows both well but mixes them when you do not specify. Name the database and version in every prompt, especially for date functions, upserts, case-insensitive matching and string concatenation.

Can Claude optimise a slow SQL query?

Yes, if you give it the EXPLAIN ANALYZE output and the existing indexes. Without the plan it can only offer generic advice. Test any suggested index on a copy first, because indexes also slow down writes.

Related guides

實踐這一點

Or get every skill with Library See plans →

~/get-started

實用的 Skills。不說空話。

瀏覽商店中的每個技能、prompt 套件和 agent。

瀏覽所有技能 →或試試免費工具