SQL VARIANCE as a window function
Variance over the window frame or partition; it is STDDEV squared and shares its sampling semantics, frame behaviour and NULL handling.
- Kategorie
- Fenster
- Returns
double precision / float- In this category
- 27 of 79
Syntax
VAR_SAMP(x) OVER (PARTITION BY g) | VAR_POP(x) OVER (ORDER BY d ROWS BETWEEN n PRECEDING AND CURRENT ROW)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | Supported under this name. |
| PostgreSQL | Ja | Supported under this name. |
| MySQL | Ja | Supported under this name. |
| SQLite | Not built in | no VARIANCE built-in; same workaround as STDDEV |
| Oracle | Ja | Supported under this name. |
Beispiele
PostgreSQL
SELECT region, revenue,
VAR_POP(revenue) OVER (PARTITION BY region) AS var_all,
VAR_SAMP(revenue) OVER (PARTITION BY region) AS var_sample
FROM sales;
Gut zu wissen
- Spelling splits again: VAR_SAMP/VAR_POP on Oracle, PostgreSQL and MySQL; SQL Server says VAR (sample) and VARP (population). Plain VARIANCE is sample variance on PostgreSQL and Oracle but population variance on MySQL.
- VAR_SAMP of one row is NULL and VAR_POP of one row is 0. Oracle's plain VARIANCE also returns 0 for one row, unlike its VAR_SAMP.
- Windowed aggregates evaluate after WHERE and GROUP BY but before ORDER BY, so you can ORDER BY the variance in the same SELECT.
Questions about VARIANCE with OVER
VARIANCE or STDDEV: which belongs in a report?
Variance is in squared units (dollars squared), so it feeds further math such as ANOVA or portfolio risk. For a spread people can read, report STDDEV, which is in the same units as the data.
Why is my variance NULL then 0 across rows?
You are using VAR_SAMP in a rolling frame that sometimes has one row (NULL) and sometimes more; VAR_POP would give 0 instead. Either pad the window or pick the population form.
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: SQL Server, PostgreSQL, MySQL, 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.