Use SQL Window Functions for Advanced Analytics
Generate advanced SQL window function queries with explanations and performance notes.
This prompt writes a window-function query for a specific analytical question against your stated database, with inline comments explaining each clause and notes on what the result set looks like and how it performs. Reach for it when a question needs running totals, rankings, period-over-period comparisons, or 'top N per group' — the cases where GROUP BY alone falls short. Providing your schema is what makes the output runnable rather than a generic template, since window functions hinge on the exact partition and order columns.
You are a SQL expert. I need to use window functions to answer: '[ANALYTICAL QUESTION]' using [DATABASE: Postgres / BigQuery / Snowflake]. Write a query using appropriate window functions (ROW_NUMBER, RANK, LAG, LEAD, SUM OVER, etc.). Include: (1) the full query, (2) a comment explaining each window function clause, (3) an explanation of what the result set looks like. Note any performance considerations. SCHEMA: [PASTE TABLE DEFINITIONS]
What you can expect back
-- (1) Full query
SELECT
customer_id,
order_date,
amount,
SUM(amount) OVER (
PARTITION BY customer_id -- (2) restart the running total per customer
ORDER BY order_date -- accumulate in date order
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM orders
ORDER BY customer_id, order_date;
-- (3) Result set
One row per order, with a running_total column that grows as each
customer places more orders. The first order for a customer equals
its own amount; each later row adds the current amount to the prior total.
-- Performance
- The PARTITION BY/ORDER BY drives a sort; an index or clustering on
(customer_id, order_date) helps. In BigQuery, cluster the table on
customer_id to limit data scanned.Illustrative example — your results will vary by tool and inputs.
Get sharper results
- 01Always paste real column names and types — a window query built on guessed columns won't run, and the partition/order columns are the whole point.
- 02If two orders share a timestamp, tell the model so it can choose a deterministic tiebreaker in the ORDER BY (e.g. add order id) — otherwise running totals and ranks can be non-deterministic.
- 03Ask it to compare ROW_NUMBER vs. RANK vs. DENSE_RANK for your case; picking the wrong one is the most common 'top N per group' bug.
- 04Request both the window-function version and a self-join or subquery alternative so you can sanity-check the result and compare performance.
- 05For big tables, ask explicitly about frame clauses — RANGE vs. ROWS behaves differently with duplicate order keys and can change your numbers.
Adapt it for your case
Phrase the question around LAG/LEAD ('compare each month to the prior month') to get growth and delta columns.
Ask for a ranked result wrapped in a subquery filtered to rank <= N, e.g. top 3 products per category.
Describe a streak or session-detection problem and ask it to solve it with window functions and a grouping trick.
Common questions
Why does the prompt ask for my database dialect?
Window-function syntax, frame defaults, and available functions vary between Postgres, BigQuery, and Snowflake. Naming the dialect prevents queries that fail to run.
The query runs but the numbers look off — what's wrong?
Most often it's the ORDER BY within the window or a RANGE-vs-ROWS frame issue with duplicate keys. Give the model a few sample rows and the wrong output and ask it to diagnose.
Are window functions slow?
They require a sort and can be expensive on large tables. Good indexing or clustering on the partition and order columns helps a lot; ask the model for the specific optimization for your engine.
You may also need
Write a SQL Query From a Business Question
Translate a business question into a clean, commented SQL query against your schema.
Analyze a Dataset With Pandas Step-by-Step
Generate step-by-step Pandas EDA code covering nulls, outliers, and a business question.
Write a Data Cleaning Script for Messy Data
Generate a step-by-step Pandas data cleaning script with issue detection and before/after summaries.
Turn a Plain-English Question Into a SQL Query
Converts a natural-language business question into a correct, commented SQL query grounded in your real schema.