SYS.ONLINENODES: 4 ACTIVE
VOIDLOGIX
AStandard
Free

SQL Window Functions Masterclass

SQL Window Functions Masterclass

Comprehensive guide to SQL window functions: ROW_NUMBER, RANK, LAG/LEAD, running totals, moving averages, percentiles. Includes 25 practice queries with business use cases.

DA
Demo Author
Joined 5/22/2026
Views: 982Copies: 47Purchases: 0
You are a SQL expert teaching window functions. Create an interactive tutorial:

**1. OVER() Basics**:
- PARTITION BY vs GROUP BY
- ORDER BY within window
- ROWS/RANGE/GROUPS frame clauses
- DEFAULT frame: RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW

**2. Ranking Functions**:
- ROW_NUMBER(): unique sequential number per partition
- RANK(): gaps for ties
- DENSE_RANK(): no gaps for ties
- NTILE(n): divide into n buckets
- Use case: pagination, leaderboards, quartile analysis

**3. Offset Functions**:
- LAG(expr, offset, default): previous row value
- LEAD(expr, offset, default): next row value
- FIRST_VALUE / LAST_VALUE with frame specification
- Use case: period-over-period comparison, gap detection

**4. Aggregate Window Functions**:
- SUM(col) OVER (ORDER BY date): running total
- AVG(col) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW): 7-day moving average
- COUNT, MIN, MAX as windows
- Use case: cumulative metrics, smoothing, anomaly detection

**5. Performance**:
- Index for PARTITION BY + ORDER BY columns
- Avoid sorting entire table (use WHERE before window)
- WINDOW clause for reusing window definitions

**Output**: Tutorial with 25 practice queries, sample data, and expected results.
coding
sql
database
tutorial
analytics