Skip to main content
← Prompt library

write-sql-query · claude-3-5-sonnet · data · 90% confidence

Write a SQL query with Claude 3.5 Sonnet — optimized prompt

A Claude 3.5 Sonnet SQL prompt with <schema> and <question> tags and a forced reasoning pass over join grain and NULL handling before the query is written.

90% confidenceUpdated 9/7/2026write-sql-query · claude-3-5-sonnet · data
Original prompt
Can you write a SQL query for the top customers by revenue this year? Here's my schema: [SCHEMA]
Optimized prompt
You are writing one SQL query. Correctness on join grain and NULLs matters more than cleverness.

<dialect>[Postgres / MySQL / BigQuery / ...]</dialect>

<schema>
[PASTE CREATE TABLE STATEMENTS or annotated column lists]
</schema>

<question>
[the result set and its grain — one row per what — plus every filter]
</question>

<instructions>
First, in <thinking>: name the tables to touch, the join keys and their cardinality, the grain of the final result, and how NULLs / duplicates could distort the aggregate.
Then output:
- The query, as a formatted ```sql block.
- Edge cases handled: bullets (empty ranges, ties, missing dimension rows).
Do not invent columns; if one is missing, say which and stop.
</instructions>

Why this Claude 3.5 Sonnet prompt works

Tuned for Claude 3.5 Sonnet: <schema> and <question> tags plus a forced <thinking> pass over join cardinality, result grain and NULL handling before the query. That reasoning step is where Claude catches the fan-out and double-count bugs a one-shot prompt misses.

What to check in the output

  • The 'optimized_prompt' clearly states the goal of generating an SQL query.
  • The 'optimized_prompt' uses a chain-of-thought to guide the model's reasoning.
  • The 'optimized_prompt' specifies the target customer ID (123) and table ('orders').

Slugd1ed67bf-2dca-48e6-aed8-89757fa62ba5

ModelClaude 3.5 Sonnet