Advanced SQL for Analytics: Window Functions, CTEs, Subqueries, and Performance
What You'll Learn
- 1Use window functions for ranking, running totals, and period comparisons
- 2Structure complex logic with readable CTE chains
- 3Rewrite correlated subqueries efficiently
- 4Diagnose and improve slow analytical queries
Advanced SQL lets analysts solve ranking, cohort, and period comparison problems in a single declarative statement. Common table expressions make pipelines of logic readable, while window functions compute across related rows without self joins. Performance comes from reducing scanned data and letting the planner do its job.
Window Functions
Window functions compute over a partition of rows while keeping row level detail, unlike group by which collapses rows. Rank, dense rank, and row number order within partitions for top n lists; lag and lead fetch prior or next period values for growth and sessionization; sum over produces running totals. Frames such as rows between unbounded preceding and current row control the window boundary.
Always choose between row number, rank, and dense rank deliberately when ties matter to the business rule. Partition by the correct dimensions, such as user within product, or results will silently mix entities.
CTEs, Subqueries, and Query Structure
Common table expressions named with with clauses stage intermediate results with clear names, improving readability and reuse within one query. Nested subqueries can express the same logic but often become hard to scan; flattening them into a CTE chain usually helps reviewers. Recursive CTEs handle hierarchies such as org charts or category trees when needed.
Filter early in the earliest CTE to cut volume, and project only required columns before heavy joins. Materialized versus ephemeral CTE behavior differs by engine, so understand whether your warehouse re evaluates CTEs multiple times.
Performance and Warehouse Awareness
Start with the execution plan: look for full table scans, skewed joins, and unexpected sorts. Partition pruning, cluster keys, and selective filters reduce bytes scanned, which dominates cost in cloud warehouses. Avoid wrapping indexed or partition keys in functions, and prefer set based logic over correlated subqueries that run per row.
Test with realistic data volumes and compare timings before and after changes. Small dev tables hide skew and cache effects that explode in production, so validate with production scale samples when possible.
Window Function Patterns
| Pattern | Function | Use Case |
|---|---|---|
| Ranking | row_number, rank | Top products per category |
| Prior value | lag, lead | Month over month change |
| Running total | sum over | Cumulative revenue to date |
| Average context | avg over | Rolling seven day mean |
| First and last | first_value, last_value | Session start and end events |
| Delta vs peer | rank minus baseline | Percentile movement reports |
Real-World Examples
- Top n per group â Row number partitioned by category ordered by revenue desc keeps the top three products in each category.
- Month over month â Lag of revenue partitioned by product ordered by month computes absolute and percent change per product.
- Running total â Sum over ordered by date with frame bounds produces cumulative bookings within the fiscal year window.
- Cohort retention â A CTE builds first active month, another joins activity months, and the final select counts distinct users by lifecycle month.
âĄCut Bytes Before Tweaking Syntax
Common Mistakes
Row number without a deterministic order
Fix: Add a stable tie breaker or rankings flip run to run and stakeholders see changing top lists.
Correlated subquery per row
Fix: Rewrite as a join or exists with set based logic so the engine scans once instead of querying repeatedly.
Ignoring data skew
Fix: A few hot keys can stragglers slow joins; check key distribution and pre aggregate or salt extreme skew when needed.
Key Takeaways
- Window functions preserve row detail while computing rankings and period deltas.
- CTE chains turn complex logic into named, reviewable steps.
- Execution plans and bytes scanned explain most warehouse performance issues.
- Deterministic ordering and stable grain keep metrics reproducible.
Frequently Asked Questions
When is a CTE better than a subquery?
When you need readable staging steps, reuse within one query, or clearer review. Some engines inline CTEs, so measure performance rather than assuming.
How do I optimize a slow dashboard query?
Aggregate to the needed grain, add partition or cluster filters, materialize intermediate results as tables if reused, and remove unnecessary columns and joins.
Rank versus dense rank versus row number?
Row number gives unique sequential numbers, rank allows ties with gaps, and dense rank allows ties without gaps. Choose based on the business definition of top or worst.
Interview Questions
Q1: Explain how you would compute a seven day rolling average of daily orders in SQL.
Use avg of daily orders over a window ordered by date with a frame of six preceding rows to current row, partitioned by any site dimension if multiple series exist.
Q2: How do you approach tuning a warehouse query that reads too much data?
Profile the plan, confirm partition and cluster pruning, push filters earlier, narrow the column set, pre aggregate reusable facts, and retest with production like volumes.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions