Best ChatGPT Prompt for SQL Queries
Write, debug, and optimize SQL queries — for any database (PostgreSQL, MySQL, SQL Server, SQLite, BigQuery).
The Prompt
You are a SQL expert and database administrator. Help me write or fix a SQL query. Database: [PostgreSQL / MySQL / SQL Server / SQLite / BigQuery / Snowflake] What I'm trying to do: [DESCRIBE THE RESULT YOU WANT IN PLAIN ENGLISH] My tables: ``` [TABLE 1]: columns (column1 type, column2 type, ...) [TABLE 2]: columns (column1 type, column2 type, ...) ``` Sample data (3-5 rows per table): [PASTE SAMPLE] My current query (if any): ```sql [PASTE QUERY] ``` The problem: [wrong result / error message / too slow] Requirements: - Write the correct query with proper formatting - Explain what each JOIN, WHERE, and aggregate does - Warn about NULL handling if relevant - Suggest indexes if the query would be slow on large tables - If my approach is off, suggest a better structure - Show the expected output given my sample data
How to Use This Prompt
- Paste your actual table structure with data types — guessing leads to wrong queries
- Include 3-5 sample rows so the AI knows what the data actually looks like
- For slow queries, paste EXPLAIN output if you have it
- Specify your database engine — syntax differs across PostgreSQL, MySQL, and SQL Server
Example Output
Task: Find customers who bought in January but not February
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date >= '2026-01-01'
AND o.order_date < '2026-02-01'
)
AND NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date >= '2026-02-01'
AND o.order_date < '2026-03-01'
);
Explanation: The EXISTS clause is typically faster than LEFT JOIN + NULL check for 'has X but not Y' queries on large tables.
Tips to Get Better Results
- Use CTEs for clarity. Ask 'Rewrite with CTEs to make this readable.'
- Optimize by stages. For slow queries, ask 'What indexes would speed this up?' then 'Can the query itself be rewritten to avoid the slow part?'
- Test with LIMIT. Always add LIMIT 10 when testing. Ask the AI to remove it once correct.
- Understand the plan. Ask 'Explain the query execution plan' for queries hitting production.