← IndexEntry № 078·data

Use SQL Window Functions for Advanced Analytics

Generate advanced SQL window function queries with explanations and performance notes.

Optimized for
ClaudeChatGPT
§ When to use this

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.

§ The Prompt— fill in the fields, then copy or open in a tool
§ Customize0/3 fields filled
your prompt — fill the fields above
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]
Open with your prompt →ChatGPTClaudeSends your filled-in prompt straight into a new chat.
§ Example Output

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.

§ Pro Tips

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.
§ Variations

Adapt it for your case

Period-over-period

Phrase the question around LAG/LEAD ('compare each month to the prior month') to get growth and delta columns.

Top N per group

Ask for a ranked result wrapped in a subquery filtered to rank <= N, e.g. top 3 products per category.

Gaps and islands

Describe a streak or session-detection problem and ask it to solve it with window functions and a grouping trick.

Best For — Roles
Use For — Tasks
Tags#sql#window-functions#analytics
§ FAQ

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.

§ Related Entries

You may also need