Prompt for Writing a SQL Query
Describe your data in plain English and get a correct, efficient SQL query for your database.
Copy-ready prompt
You are a senior data engineer. Write a SQL query for [database: MySQL/PostgreSQL/etc]. Goal: [what the query should return]. Schema: [list tables and columns, or paste CREATE TABLE statements] Requirements: - Correct syntax for the stated dialect. - Use explicit JOINs and clear aliases. - Handle NULLs and edge cases safely. - Avoid SELECT *; list needed columns. - Add a one-line explanation and note any assumptions.
Want a version tailored to you?
Answer a few quick questions and the SQL Query Generator builds a custom prompt from your exact details.
ποΈ Open the SQL Query GeneratorWhy AI-generated SQL usually breaks on the first run
An AI can write syntactically perfect SQL and still hand you a query that fails or, worse, returns quietly wrong numbers. The reason is almost always context, not competence. When you ask for a query without describing your tables, the model invents a plausible schema β it guesses that your users table has an id and created_at, that orders link back with user_id, and that a status column exists. Sometimes it guesses right. Often the column is actually customer_id, or the date is stored as text, or there is no status column at all. The prompt above fixes this at the source by requiring you to paste your real schema or CREATE TABLE statements. Once the model can see the actual column names and types, it stops guessing and starts mapping the query to your database.
Dialect is not a detail
SQL is a family of languages, not one language. A query that runs on PostgreSQL can fail on MySQL because the functions differ. String concatenation uses || in Postgres but CONCAT() in MySQL. Date math, LIMIT versus TOP, window function support, and ILIKE for case-insensitive matching all vary by engine. This is why the prompt asks you to state the dialect up front. Telling the model "this is BigQuery" or "this is SQL Server" changes which functions it reaches for and prevents the frustrating loop of pasting an error, getting a fix, and hitting the next dialect-specific problem. If you are unsure of your engine, it is worth checking before you generate anything, because it shapes every function choice in the result.
Explicit JOINs and NULL handling separate correct from plausible
The instruction to use explicit JOINs with clear aliases is about correctness and readability at once. Comma-style joins with a giant WHERE clause hide the join logic and make it easy to accidentally produce a cartesian product. Explicit INNER JOIN and LEFT JOIN keywords force the relationship to be stated clearly, and choosing between them matters: an inner join silently drops rows that have no match, so a report of "customers and their orders" written with the wrong join type will quietly exclude customers who never ordered. The requirement to handle NULLs safely catches the other classic trap β comparisons and aggregates behave unexpectedly around NULL. A filter like WHERE status != 'closed' will exclude rows where status is NULL, which is rarely what you intend. Naming these concerns in the prompt makes the model reason about them instead of defaulting to the happy path.
The assumptions note is your safety net
The final requirement β a one-line explanation plus any assumptions β is what turns a black-box answer into something you can trust. When the model writes "assuming each order belongs to exactly one customer and refunds are excluded," you can immediately confirm or correct that logic before running anything. Ambiguity is where wrong reports come from, and surfacing it in plain English is far cheaper than debugging a query that ran successfully but counted the wrong thing. Always read that note, and always test the query on a small sample before you point it at production data.
Why this prompt works
SQL from AI fails when it guesses your schema or dialect. This prompt supplies both plus the exact goal, so the query maps to your real tables and runs on your engine β and the assumptions note catches ambiguities before they cause wrong results.
How to customize it
- Paste your real schema so column names are correct.
- State the dialect; functions differ across databases.
- Test on a sample before running on production data.
Example output
Sample onlyGoal: Total revenue per customer in 2024, including customers who placed no orders (PostgreSQL).
Query:
SELECT c.id, c.name, COALESCE(SUM(o.total), 0) AS revenue_2024 FROM customers c LEFT JOIN orders o ON o.customer_id = c.id AND o.order_date >= '2024-01-01' AND o.order_date < '2025-01-01' GROUP BY c.id, c.name ORDER BY revenue_2024 DESC;
Explanation: Sums each customer's 2024 order totals, using a LEFT JOIN so customers with no orders still appear, and COALESCE to show them as 0 rather than NULL.
Assumptions: The date filter is placed in the JOIN condition (not WHERE) so it does not turn the LEFT JOIN into an inner join; orders.total is already net of tax; refunds are not stored in this table.
Prompt variations to try
Optimize an existing slow query
You are a senior database performance engineer. Here is a slow SQL query on [database: PostgreSQL/MySQL/etc]: [paste query] Schema and approximate row counts: [paste tables, columns, indexes, and row counts] Rewrite it to run faster. Explain what was slow (e.g. missing index, function on an indexed column, unnecessary subquery), suggest any indexes to add, and confirm the rewrite returns identical results. Keep the dialect correct.
Explain what a query does
You are a SQL tutor. Explain this [database dialect] query in plain English, step by step: [paste query] Describe what each JOIN, filter, and aggregate does, what the result set looks like, and call out any edge cases or bugs you notice (such as NULL handling or a join that might drop rows). Assume I am comfortable with basic SQL but not this query.
Convert a query between dialects
Convert this SQL query from [source dialect] to [target dialect]: [paste query] Replace any dialect-specific functions, date handling, string operations, and syntax (such as LIMIT vs TOP) with the correct equivalents. List each change you made and why, and flag anything that has no direct equivalent and needs a workaround.
Common mistakes to avoid
- Not pasting the real schema. Without your actual table and column names, the AI invents them and the query fails or references columns that do not exist. Always paste CREATE TABLE statements or a column list.
- Skipping the dialect. Functions differ across engines, so a query for one database may error on another. State
MySQL,PostgreSQL,SQL Server, or whatever you actually run. - Using an INNER JOIN when you meant to keep unmatched rows. An inner join silently drops records with no match β use a
LEFT JOINandCOALESCEwhen you need every row from the primary table. - Ignoring NULLs in filters. A condition like
status != 'closed'excludes rows where status is NULL. Decide explicitly withIS NULL/IS NOT NULLorCOALESCE. - Trusting the query without testing. Even correct-looking SQL can count the wrong thing. Read the assumptions note, then run it on a small sample before touching production data.
Frequently asked questions
Do I really need to paste my whole schema?
You need enough for the model to reference real columns β the relevant tables, their key columns, and how they relate. You do not have to paste every table in the database, just the ones the query touches plus any join keys. Accurate column names are what prevent the query from breaking on the first run.
Why does the same query fail on MySQL but work on PostgreSQL?
Because they are different SQL dialects. Functions for strings, dates, and pagination differ, and features like some window functions or ILIKE are not available everywhere. Always tell the AI which engine you use so it picks the correct functions instead of guessing.
Is it safe to run AI-generated SQL on production?
Not without checking first. Read the explanation and assumptions, then test on a sample or a read replica. Be especially careful with any query that writes or deletes data β review the WHERE clause closely, and consider wrapping changes in a transaction so you can roll back if the result is wrong.
Can AI help me speed up a slow query?
Yes, if you give it what it needs: the query, the schema, existing indexes, and rough row counts. It can spot missing indexes, functions applied to indexed columns, and needless subqueries, then suggest a rewrite. Confirm the rewrite returns identical results before adopting it.
Tip: replace the parts in [square brackets] with your own details before you send. The more specific you are β audience, tone, goal, constraints β the better the AI output.