Coding
AI Prompt for Writing SQL Queries
Turn plain English into correct SQL with this AI prompt: schema-aware queries for your dialect, explained line by line, with edge cases handled.
The prompt
Role: You are a SQL expert who writes correct, readable queries in [DIALECT: PostgreSQL / MySQL / SQL Server / SQLite / etc.]. Context: I need a query that does this in plain English: [PLAIN_ENGLISH_REQUEST]. Schema: [SCHEMA: tables, key columns, and relationships] Task: 1) Write the SQL query for [DIALECT]. 2) Explain each clause in plain English (what the JOIN does, what the WHERE filters, what the GROUP BY aggregates). 3) Handle edge cases: NULLs, duplicates, empty result sets, division by zero where relevant. 4) Note any [DIALECT]-specific syntax you used and its equivalent in other dialects if it matters. Format: Query in a code block first, then the clause-by-clause explanation, then edge-case notes. Ask the AI to show the intermediate result after each clause using two or three sample rows, so you can watch the JOIN, filter, and aggregation shape the data step by step. This makes the query's logic transparent. Constraints: Use explicit JOIN syntax, never comma joins. Qualify all column names with table aliases. Do not use SELECT * — list the columns the request actually needs.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[DIALECT] [PLAIN_ENGLISH_REQUEST] [SCHEMA]
Example input
DIALECT=PostgreSQL, REQUEST=top 10 customers by total order value in 2026, excluding refunded orders, TABLES=customers(id,name), orders(id,customer_id,total,status,created_at)
How to use this prompt
Describe tables with key columns and relationships — the query is only as correct as the schema you provide. State the plain-English request first, exactly as a stakeholder would say it.
Tips for the best results
- Ask it to show the query's logic in plain English BEFORE the SQL when learning.
- Provide sample rows and ask it to trace the query's result manually.
- For reports, ask for the column aliases to match your stakeholder's terminology.
Frequently asked questions
Can I skip describing the schema?
No. Give it the real schema and it will qualify columns correctly and avoid guessing.
How do I describe my schema effectively?
List tables with key columns and the relationships between them — one line per table is enough. Include which columns are nullable if your query filters on them.