Create intermediate Works with: Any AI

SQL Query Writer With Explanation

Few shot Has example

Write and explain queries from business questions.

The Open buttons send the prompt text as currently shown below to that site only when you click. Fill in the placeholders first.

Write and explain SQL for my business question. Database and version: [DATABASE_AND_VERSION]. Table definitions (names, columns, types, keys): [PASTE_SCHEMA]. Business question: [BUSINESS_QUESTION]. Sample data or expected result shape: [SAMPLE_DATA].

Follow the format in this example.
Question: Which customers placed more than 3 orders last month, and what is their total spend?
Query:
SELECT c.id, c.name, COUNT(o.id) AS orders, SUM(o.total) AS total_spend
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= DATE '2025-03-01' AND o.created_at < DATE '2025-04-01'
GROUP BY c.id, c.name
HAVING COUNT(o.id) > 3
ORDER BY total_spend DESC;
Explanation: join links each order to its customer; the date range uses a half-open interval so no day is missed or double counted; HAVING filters after grouping; ORDER BY shows the biggest spenders first.
Assumptions: orders.total includes tax; cancelled orders are included (add a status filter if not).

For my question, provide: the query, a line-by-line explanation in plain language, the assumptions you made and how to check them, edge cases (nulls, duplicates, time zones), an index suggestion if relevant, and a version that is easier to read using common table expressions. Include a test query to validate totals. If my schema is unclear, ask before guessing.

Fill in before use

Optional: type your details and the prompt above updates. Nothing is saved or sent.

Replace each bracketed placeholder with your own details, then paste into Any AI or another assistant.

See an example result (fictional data)
Question: Which customers placed more than 3 orders last month?
SELECT c.id, c.name, COUNT(o.id) AS orders, SUM(o.total) AS spend
FROM customers c JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= DATE '2026-09-01' AND o.created_at < DATE '2026-10-01'
GROUP BY c.id, c.name HAVING COUNT(o.id) > 3 ORDER BY spend DESC;
Explanation: the half-open date range avoids missing the last day; HAVING filters after grouping.
Assumptions: totals include tax; cancelled orders are included. Check: add AND o.status <> 'cancelled' if not.
Edge cases: time zones on created_at; customers with duplicate accounts. Validation: SUM of spend equals the total from a separate monthly report query.

Illustrative only, made-up data. Your results will differ and must be reviewed.

Related prompts