Window Functions
Overview
Window functions perform calculations across a set of related rows while returning one result per input row. Unlike aggregate functions, window functions don't collapse rows into a single output.
Key characteristics:
- Operate on a "window" of rows related to the current row
- Return one value per input row (no grouping/collapsing)
- Can access values from other rows in the window
- Support partitioning and ordering for flexible calculations
Note on SQL examples in this documentation:
- ✅ Complete SQL statements have been validated against TiDB Cloud Lake
- ⚠️ Syntax examples show window frame patterns (not complete statements)
- 📋 All examples use standard SQL syntax supported by TiDB Cloud Lake
- 🔍 Examples marked as "Complete example" are fully executable
Window Function Categories
TiDB Cloud Lake supports two main categories of window functions:
1. Dedicated Window Functions
These functions are specifically designed for window operations.
Ranking Functions:
Distribution Functions:
Value Access Functions:
Aliases:
2. Aggregate Functions Used as Window Functions
These are standard aggregate functions that can be used with the OVER clause to perform window operations.
Conditional Variants
Basic Syntax
All window functions follow this pattern:
FUNCTION() OVER (
[ PARTITION BY column ]
[ ORDER BY column ]
[ window_frame ]
)
- PARTITION BY: Divides data into groups
- ORDER BY: Sorts rows within each partition
- window_frame: Defines which rows to include (optional)
Window Frame Specification
The window frame defines which rows are included in the calculation for each row. TiDB Cloud Lake supports two types of window frames:
1. ROWS BETWEEN
Defines a window frame using physical row counts.
Syntax:
ROWS BETWEEN frame_start AND frame_end
Examples:
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW- Running totalROWS BETWEEN 2 PRECEDING AND CURRENT ROW- 3-day moving averageROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING- Centered window
For detailed examples and usage, see ROWS BETWEEN.
2. RANGE BETWEEN
Defines a window frame using logical value ranges.
Syntax:
RANGE BETWEEN frame_start AND frame_end
Examples:
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW- Cumulative by valueRANGE BETWEEN INTERVAL '7' DAY PRECEDING AND CURRENT ROW- 7-day window
For detailed examples and usage, see RANGE BETWEEN.
Common Use Cases
- Ranking: Create leaderboards and top-N lists
- Analytics: Calculate running totals, moving averages, percentiles
- Comparison: Compare current vs previous/next values
- Grouping: Divide data into buckets without losing detail
For detailed syntax and examples, see individual function documentation above.