Home/Prompt Templates/Write a SQL Query
CodingClaude

AI Prompt to Write a SQL Query

Most people ask AI to “Write a SQL query for my database”—and wonder why the output is mediocre. Here's how to write a prompt that actually gets you what you want on the first try.

Last updated · By the Prompt Orange team

Before

Write a SQL query for my database

Too vague—AI has to guess what you want

After

Write a SQL query for a PostgreSQL database. Tables: orders (order_id, customer_id, order_date, total_value), customers (customer_id, name, country, signup_date). Goal: find the top 10 customers by total spend in the last 12 months, showing name, country, total spend, and number of orders. Exclude customers who signed up less than 30 days ago. Add a comment explaining each clause.

Specific, clear, ready to use

What makes the strong prompt better?

Database type specified ensures correct syntax (PostgreSQL vs MySQL differs)

Full schema provided means the query will actually run

Commented clauses make the query maintainable and educational

Related prompt templates

Frequently asked questions

What is the best AI prompt to write a sql query?

+
A great prompt to write a sql query is specific about the output you want. Use this template as a starting point: "Write a SQL query for a PostgreSQL database. Tables: orders (order_id, customer_id, order_date, total_value), customers (customer_id, name, country, signup_date). Goal: find the top 10 customers by total spend in the last 12 months, showing name, country, total spend, and numb..." Adjust the specifics — audience, tone, length — to match your situation.

Which AI tool works best to write a sql query?

+
Claude handles this prompt well, but the same structure works in Claude, Gemini, and other modern LLMs. The reason it works isn't the tool — it's the level of context and constraint in the prompt itself.

Why does my AI a sql query come out generic?

+
Generic output almost always traces back to a vague prompt like "Write a SQL query for my database". To fix it: add audience, tone, length, examples to follow, and things to avoid. The strong prompt above shows each of those in action.

Can I use this prompt commercially?

+
Yes — these are templates, not protected content. Adapt them freely for client work, internal use, or production tools. Output rights depend on the AI tool's terms (ChatGPT, Claude etc each set their own).

Ready to build your perfect prompt?

Try Prompt Orange free—get a scored, refined prompt in under 2 minutes. No signup required.

Build my prompt now
Get started free