Claude Prompts for SQL and Database Queries
A junior analyst once ran a Claude-generated DELETE query straight into production. Here's how claude prompts for sql should be written so that never happens to you.
I have a table called [table_name] with these columns: [column_name: type, one per line] Write a SELECT query that [specific goal]. This is a read-only request — do not suggest or generate any INSERT, UPDATE, or DELETE statement even if it seems more efficient.
A junior analyst at a startup once ran a Claude-generated DELETE query straight into a production database, because the prompt never mentioned it was production, and Claude had no way to know. Nothing catastrophic happened — they had backups — but it's the clearest example I've seen of why claude prompts for sql need explicit safety context, not just a table name.
Quick-Start (Copy This Right Now)
I have a table called [table_name] with these columns:
[column_name: type, one per line]
Write a SELECT query that [specific goal]. This is a read-only
request — do not suggest or generate any INSERT, UPDATE, or DELETE
statement even if it seems more efficient.What this does: Explicitly stating "read-only" and banning write operations isn't paranoia — it's a cheap safeguard against Claude "helpfully" suggesting a cleanup DELETE alongside the SELECT you actually asked for, which is exactly the kind of suggestion someone in a hurry might copy-paste without reading closely.
Understanding the Variables
Schema context is non-negotiable. Claude can write syntactically perfect SQL against a schema it's guessing at, and that SQL will run — against the wrong columns, with the wrong join logic, silently returning incorrect results rather than throwing an error. Always paste your actual column names and types.
Dialect matters more than people expect. PostgreSQL, MySQL, and SQL Server all handle date functions, string concatenation, and window functions differently. State your dialect every time, even if it feels repetitive.
⚠️ Common mistake: Not specifying whether NULL values should be included or excluded from a calculation. This is the single most common source of subtly wrong query results — a COUNT or AVG that quietly excludes NULLs when you needed them included, or vice versa.
Step-by-Step: Writing a Safe, Correct Query
Step 1 — Provide full schema context, including relationships.
Tables:
orders (id, customer_id, order_date, total_amount, status)
customers (id, name, signup_date, region)
Dialect: PostgreSQL. Relationship: orders.customer_id -> customers.id
Write a query showing total revenue by region for orders with
status = 'completed', for the last 90 days. Include regions with
zero completed orders as $0, not excluded from the results.What this does: The "include regions with zero orders" instruction is what separates a technically correct query from a business-correct one — a plain INNER JOIN would silently drop those regions, understating how many regions actually exist.
Step 2 — Ask Claude to explain the query back to you in plain English before you run it.
Explain what this query does, step by step, in plain English,
as if to someone who doesn't read SQL. Flag anything that might
behave differently than a first read suggests.⚡ Pro tip: Always do this step, especially with joins and subqueries. Reading a plain-English explanation surfaces logic errors — like an accidental many-to-many join inflating your totals — much faster than reading the SQL itself.
Step 3 — For debugging an existing query, provide the query, the expected result, and the actual result.
This query [paste query] is returning [actual result] but I expected
[expected result] based on [your reasoning]. Walk through the query
logic step by step and identify where it diverges from what I intended.Pro-Level Variations
For query optimization:
Here's a query that's taking [X seconds] to run against a table with
[approximate row count] rows: [paste query]. Suggest indexing or
rewrite strategies to improve performance, and explain the tradeoff
of each suggestion (write speed, storage, maintenance).Scenario: Data analyst building a recurring revenue report A data analyst at a subscription business used the schema-context pattern to build a monthly recurring revenue query, catching a modeling assumption Claude flagged during the plain-English explanation step — that cancelled-and-resubscribed customers were being double-counted in a naive version of the query.
Scenario: Backend engineer debugging a slow dashboard query A backend engineer used the optimization prompt on a dashboard query that was timing out under load, and Claude's suggested composite index cut query time meaningfully — though the engineer still tested it against a staging copy of the database before touching production, which is the right call every time.
Scenario: Marketing analyst building a customer segment for a campaign A marketing analyst with limited SQL background used the step-by-step approach to build a segment query for a re-engagement campaign, relying heavily on the plain-English explanation step to verify the query matched what she actually meant by "customers who haven't ordered in 60 days."
Troubleshooting Common Issues
If a generated query returns unexpected duplicate rows, it's almost always a join — ask Claude specifically "could this join be creating a one-to-many relationship that's duplicating rows? Walk through it."
If performance suggestions feel generic, share your actual EXPLAIN output rather than just the query — Claude reasons much more precisely with the query planner's actual output than a guess based on table size alone.
Your Turn
Never run a Claude-generated query against production without the plain-English explanation step first, and never let Claude anywhere near a write statement without saying so explicitly. Once you've got a schema-and-safety prompt template that works for your database, save it in PromptABCD — reusing it beats retyping your schema every single time you need a new report.
Continue Reading
Save the prompts from this post
PromptABCD is a free prompt manager. Paste, organize, and reuse your best AI prompts — no more hunting through chat history.
