SQL window frame EXCLUDE clause
Appended to a frame spec, EXCLUDE removes the current row and/or its peers from the frame: leave-one-out averages without subtracting the row by hand.
- Categoría
- Ventana
- Returns
per-frame aggregate- In this category
- 62 of 79
Sintaxis
AVG(x) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND 6 FOLLOWING EXCLUDE CURRENT ROW)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Not built in | not supported, including SQL Server 2025 |
| PostgreSQL | Sí | PostgreSQL 11+ |
| MySQL | Not built in | not supported in MySQL 8.x |
| SQLite | Sí | SQLite 3.28+ |
| Oracle | Sí | Oracle 21c+ |
Ejemplos
PostgreSQL
-- average of the neighbours only
SELECT day, price,
AVG(price) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND 6 FOLLOWING
EXCLUDE CURRENT ROW) AS neighbourhood_avg
FROM prices;
Conviene saberlo
- The four options: NO OTHERS (default), CURRENT ROW (drop this row), TIES (drop the peers, keep this row), GROUP (drop row and peers). Peers are defined by the ORDER BY values, so TIES and GROUP work in ROWS frames too.
- The main use is leave-one-out statistics: the average of a row's neighbours without the row itself, for spotting outliers.
- SQL Server and MySQL reject EXCLUDE. The rewrite for EXCLUDE CURRENT ROW is (SUM(x) OVER w - x) / (COUNT(x) OVER w - 1), with care when x is NULL; EXCLUDE GROUP needs the peers' sum subtracted too.
Questions about EXCLUDE Clause
How do I compute 'everything except this row' in a window?
EXCLUDE CURRENT ROW where supported; elsewhere subtract the current value from the frame total: SUM(x) OVER w - x. For AVG divide that by COUNT(x) OVER w - 1, guarded with NULLIF against single-row frames.
What is the difference between EXCLUDE TIES and EXCLUDE GROUP?
TIES removes the current row's peers but keeps the row itself; GROUP removes both the row and all its peers. NO OTHERS keeps the frame as the boundaries define it.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.