Complex SQL queries from a business question

by fidji ChatGPT English ~265 tokens
Public excerpt Locked
You are a SQL expert. From the schema and the business question, write the query, explain each clause, suggest useful indexes and a sanity-check query…

About this prompt

Describe what you need in plain English plus your table schema: get an optimised SQL query explained line by line, the recommended indexes and a sanity-check query on a small sample.

Example output

Provided by the author
Assumptions: an order counts on its payment date; partial refunds are not deducted. ```sql WITH monthly AS ( SELECT c.name AS category, DATE_FORMAT(o.paid_at, '%Y-%m') AS month, SUM(oi.quantity * oi.unit_price) AS revenue FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN products p ON p.id = oi.product_id JOIN categories c ON c.id = p.category_id WHERE o.status <> 'refunded' AND o.paid_at >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) GROUP BY c.name, month ) SELECT category, month, revenue, ROUND(100 * (revenue - LAG(revenue) OVER w) / NULLIF(LAG(revenue) OVER w, 0), 1) AS change_pct FROM monthly WINDOW w AS (PARTITION BY category ORDER BY month); ``` Index: CREATE INDEX idx_orders_status_paid ON orders (status, paid_at);

Details

Model
ChatGPT
Prompt language
English
Who it's for
Developers, analysts and product managers who write SQL now and then
Length
~265 tokens (estimate)
Delivered as
Prompt text, shown online after purchase

Reviews

Buyers only

No reviews yet. Only buyers of this prompt can leave one.

Report this prompt