Skip to content

SQL

Write and Optimise a SQL Query

AI Tool: ChatGPTCategory: Coding

Turn a reporting question into correct SQL, then optimise it with indexes and an execution plan review.

The Prompt

Act as a database engineer fluent in {{database}}.

Schema (tables, columns, keys, approximate row counts):
{{schema}}
Question to answer with data: {{question}}
Performance constraints: {{constraints}}

Provide:
1. The query, formatted and commented
2. A plain-language explanation of how it produces the answer
3. Edge cases: nulls, duplicates, time zones, soft deletes
4. Expected execution plan shape and where the cost sits
5. Index recommendations, with the trade-off on writes
6. An alternative formulation (CTE vs subquery vs window function) and when it would be faster
7. How to verify correctness with a small sanity-check query

Use only tables and columns present in the schema. If something is missing, ask instead of assuming.

Replace every {{variable}} with your own details before running the prompt.

Variables to fill in

4 variables

{{database}}required
PostgreSQL, MySQL, SQLite, BigQuery, etc.
{{schema}}required
Relevant tables and columns.
{{question}}required
The business question to answer.
{{constraints}}
Latency or data size constraints.

Best for

  • Developers
  • Data analysts
  • Engineers