This directory contains examples demonstrating window functions (analytic functions) for advanced data analysis across MySQL, PostgreSQL, and SQLite.
Window functions perform calculations across a set of table rows that are related to the current row. Unlike aggregate functions, they don't collapse rows into a single output row - each row retains its identity while having access to aggregate information.
- MySQL 8.0+ (for window functions support)
- PostgreSQL 9.4+ (for window functions support)
- SQLite 3.25+ (for window functions support)
Comprehensive demonstration of all window function capabilities:
- ROW_NUMBER() - Assigns unique sequential numbers within partitions
- RANK() - Ranks rows with gaps for ties
- DENSE_RANK() - Ranks rows without gaps
- LAG() - Access previous row's data
- LEAD() - Access next row's data
- Running Totals - Calculate cumulative sums
- Moving Averages - Calculate rolling averages
- FIRST_VALUE() / LAST_VALUE() - Access first and last values in window
- NTILE() - Divide rows into buckets/quartiles
- Multiple Window Functions - Combine multiple window functions
Divides result set into groups/partitions:
Db::rowNumber()->partitionBy('region')Defines the order within each partition:
Db::rank()->partitionBy('region')->orderBy('amount', 'DESC')Defines the window frame (subset of partition):
Db::windowAggregate('SUM', 'amount')
->orderBy('date')
->rows('ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW')- Ranking: Product rankings, leaderboards, top N per category
- Running Totals: Cumulative sales, balance calculations
- Moving Averages: 7-day average, smoothing metrics
- Period-over-Period: Month-over-month, year-over-year comparisons
- Percentiles: Top 10%, quartile analysis
- Gap Analysis: Finding differences between consecutive rows
Run on all three database dialects:
# SQLite
PDODB_DRIVER=sqlite php 01-window-functions.php
# MySQL
PDODB_DRIVER=mysql php 01-window-functions.php
# PostgreSQL
PDODB_DRIVER=pgsql php 01-window-functions.php- Add indexes on columns used in PARTITION BY and ORDER BY
- Limit result sets when possible - window functions on large datasets can be expensive
- Use appropriate frame clauses - restrict window frames to only needed rows
- Consider materialized views for frequently-used window function queries