Get better SQL from AI
Describe the result you expect, including rules that the schema cannot explain. A column name alone does not tell the AI what counts as revenue or an active customer.
Get better SQL from AI
Section titled “Get better SQL from AI”Include these details when they affect the answer:
| Detail | Example |
|---|---|
| One result row | One row per customer, identified by customer ID. |
| Business rule | Revenue means paid order totals after refunds. |
| Dates | Use the payment date, with calendar months in UTC. |
| Included records | Exclude cancelled orders; include customers with no purchases. |
| Joins | Match orders to customers by customer ID. |
| Missing values | Treat a missing discount as zero. |
| Output | Return customer ID, name and revenue, sorted by revenue. |
Name the relevant tables when you know them. Use chat context settings to supply their definitions or the query you want to change.
Write a complete request
Section titled “Write a complete request”For example:
Write a query for monthly revenue in 2025, using calendar months in UTC. Use completed orders and subtract refunds. Return one row per month, including months with no sales, ordered by month. Ask which date and amount columns to use if their meaning is unclear.
Replace these requirements with your own rules. For a correction, describe the difference between the answer and the expected result:
The join counts each order once per line item. Calculate the order total once, then group those totals by month.
Include the database’s error message when SQL fails, after removing private values. See wrong SQL for a full troubleshooting sequence.
Review the SQL
Section titled “Review the SQL”Check the answer against a known example before using it for a decision or database change. SQL can execute successfully and still answer a different question.
- Confirm the active database and SQL dialect.
- Compare table names, columns and join keys with the schema.
- Check that grouping produces one row per intended result.
- Inspect date boundaries, time zones, filters and
NULLrules. - Compare totals with a small example whose answer you know.
- Choose Apply to SQL Editor on the SQL block to edit it before execution.
Apply to SQL Editor inserts the SQL without running it. Follow write and run SQL when the statement is ready. For a write, check the target rows and your recovery procedure before approving execution.
If you need database evidence to check an assumption, use Agent mode. If you need to inspect a query’s execution plan, use Explain with AI.