Prompt Library coding intermediate

ChatGPT Prompts for SQL Queries: Write and Optimize Complex Queries

ChatGPT prompts for SQL query writing and optimization. Complex JOINs, window functions, CTEs, and query performance tuning for PostgreSQL, MySQL, and BigQuery.

Tested on: GPT-4oClaude 4Gemini 2.5

The Prompt

Act as a senior database engineer who has optimized queries running on billion-row tables.
Write or optimize the following SQL:
Request: {describe what you want the query to do — in plain English}
Schema: {paste the relevant CREATE TABLE statements or describe the tables and columns}
Sample data: {optional — 3-5 rows of sample data that shows the edge cases}
Database: {PostgreSQL / MySQL / BigQuery / Snowflake / SQLite}
Performance requirements: {no constraints / must be fast / explain plan analysis needed}
Current query (if optimizing): [PASTE EXISTING QUERY — or "new query"]

Output:
1. The query (fully formatted, with comments explaining complex logic)
2. Query explanation (plain English: what this query does step by step — for non-SQL experts)
3. Execution plan notes: indexes that should exist for this query to perform well
4. Edge cases handled: what happens with NULLs, empty sets, or duplicate rows
5. Alternative approach (if there's a meaningfully different way to write this — trade-offs explained)
6. Test cases: 3 sample inputs and expected outputs to validate the query

Constraints:
- Use CTEs instead of nested subqueries for readability
- Name all aliases clearly (not a, b, c — use descriptive aliases)
- Handle NULL values explicitly — don't assume fields are always populated
- For aggregations: always specify GROUP BY correctly — flag any potential grouping errors

Variables to fill in

  • {request} What you want the query to do — plain English description
  • {schema} CREATE TABLE statements or table/column descriptions
  • {database} PostgreSQL, MySQL, BigQuery, Snowflake, or SQLite
  • {performance requirements} Whether the query needs to be optimized for speed
  • {current query} The existing query if optimizing, or 'new query'

How to use this prompt

  1. Describe what you want in plain English first — let the AI produce the SQL structure
  2. Paste your schema to get column names and data types right without manual lookup
  3. Use the execution plan notes to add indexes before running on production data
  4. Test with the generated test cases before running against your real database
SQL query editor on screen with database schema diagram beside it
Photo by Jan Antonin Kolar on Unsplash

Plain English descriptions produce better SQL than describing SQL

Describing what you want in plain English (‘find all customers who made more than 3 purchases in the last 30 days but haven’t purchased in the last 7’) produces better AI output than saying ‘write a query with a COUNT and a date filter.’ The AI translates intent to SQL more accurately than it translates pseudo-SQL to real SQL.

CTEs make complex queries maintainable

A query with 3 nested subqueries is difficult to debug, modify, and explain to teammates. The same logic written as a sequence of CTEs — each with a descriptive name — reads like documentation. The prompt enforces CTEs over subqueries for exactly this reason.

NULL handling is where SQL queries fail silently

A query that returns ‘correct’ results but silently drops NULL rows is one of the hardest bugs to catch. The prompt’s constraint — ‘handle NULL values explicitly’ — forces the AI to add COALESCE, IS NULL checks, or explicit NULL handling for every field that might be empty in real data.