SQL window functions: 10 patterns for real analysis
Window functions keep your rows while you calculate across them. Learn ten patterns: ranking, deduplication, running totals, LAG, cohorts and streaks.
Short answer: Give the model your real schema, your metric definitions and two or three worked examples, ask it to explain its joins, and then check the result against a number you already know. The most common failures are queries that run fine but answer a different question, so testing matters more than clever wording.
AI can write a query in seconds, and it will look right almost every time. That is the problem. A wrong query and a right one look identical until you check, and the model will present both with the same calm confidence. The fix is not a magic prompt. It is a better brief, plus a few checks you run every time.
This is where having in mind the top metrics of the business helps: number of active customers, revenue, volumes and other drivers, share of countries… having a “feel” for what is correct - or not, is how it helped me in first place understand that the output was not correct.
The research and practitioner write-ups agree on the pattern. Without context, a model tends to produce SQL that is syntactically correct but semantically wrong: wrong joins, hallucinated columns, and mismatched aggregations. A practical guide from PuppyGraph notes that a single prompt with the question and schema tends to be brittle on ambiguous questions and large schemas, and offers no way to recover when the first query is wrong.
So the goal of prompting is to remove ambiguity before the model writes anything.
Think of it as briefing a smart new colleague who has never seen your database.
1. The schema, trimmed to what matters. Table names, column names and types, and the keys that join them. Don’t paste 300 tables. Include the three that matter. For large schemas, retrieval approaches narrow the prompt to the relevant tables and columns, as covered in Arize’s guide.
2. Business definitions. Say what “active customer” or “revenue” means, in words and, ideally, as a formula. This is the semantic-layer idea in miniature; see what a semantic layer is.
3. The dialect. “PostgreSQL 16”, “BigQuery”, “DuckDB”. Date functions and quoting differ, as I showed in SQL date functions.
4. Two or three examples. Show a question with the correct SQL. Guides on prompting for text-to-SQL, including this one, recommend a handful of question-and-answer pairs so the model learns your schema’s patterns. Treat claims of a specific percentage improvement as rough, since they depend on the setup.
5. Constraints. “Read-only. Use CTEs, not subqueries. Return no more than 100 rows. Never use SELECT *.”
Here is a template I reuse. The names are illustrative.
You are helping me write PostgreSQL 16 SQL.
Schema:
- orders(order_id, customer_id, order_date, amount_eur, status)
- customers(customer_id, country, is_test)
Definitions:
- Revenue = SUM(amount_eur) where status = 'paid' and customers.is_test = false.
- "Last month" = the previous calendar month in Europe/Berlin time.
Example:
Q: Revenue by country in January 2026.
SQL: <your verified query>
Task: Revenue by country for last month, top 10.
Rules: read-only, use a CTE, explain each join in one sentence before the query,
and list any assumption you had to make.
The last line is the important one. Asking for assumptions makes the model show you where it guessed, which is exactly where mistakes hide.
Never run generated SQL on the trust of how it looks. My checklist:
LIMIT first, and on a copy or read-only connection when the data is sensitive.I go deeper on this in how to validate AI-generated analysis.
AI is good at the boring parts: boilerplate, translating between dialects, writing a first draft of a window function, explaining a query someone else wrote. It is weaker on ambiguity and on knowing your business. That is why the context above matters.
My take: treat the model like a fast junior analyst who never gets tired and never says “I’m not sure”. Give it good briefs, and check its work every time. If a query is a one-off on data you know well, you may be faster writing it yourself.
For a wider view of the tasks that suit AI, see which analyst tasks to hand to AI. If you are choosing a tool rather than writing prompts, see text-to-SQL tools compared.
Sources: PuppyGraph: Text-to-SQL LLM, A Practical Guide, Arize: How to Prompt LLMs for Text-to-SQL, The Neural Base: few-shot example queries, DIN-SQL (arXiv). The prompt template and table names are illustrative.
Part of: SQL & Local Analytics, AI for Analysts