// window reference

SQL STDDEV as a window function

Standard deviation computed over the window frame or partition, keeping every row: group dispersion, rolling volatility and z-scores in one pass.

카테고리
창
Returns
double precision / float
In this category
26 of 79

구문

STDDEV_SAMP(x) OVER (PARTITION BY g) | STDDEV_SAMP(x) OVER (ORDER BY d ROWS BETWEEN 29 PRECEDING AND CURRENT ROW)

엔진 지원

엔진Support메모
SQL Server 예 Supported under this name.
PostgreSQL 예 Supported under this name.
MySQL 예 Supported under this name.
SQLite Not built in no STDDEV built-in; register a custom aggregate or compute via AVG of squared differences in a CTE
Oracle 예 Supported under this name.

예시

PostgreSQL

SELECT symbol, day, close,
       (close - AVG(close) OVER w) / NULLIF(STDDEV_SAMP(close) OVER w, 0) AS z
FROM quotes
WINDOW w AS (PARTITION BY symbol ORDER BY day ROWS BETWEEN 29 PRECEDING AND CURRENT ROW);

SQL Server

SELECT region, revenue,
       STDEV(revenue) OVER (PARTITION BY region) AS revenue_stddev
FROM sales;

알아 두면 좋은 정보

  • Plain STDDEV does not mean the same thing everywhere: PostgreSQL and Oracle treat it as the sample version, MySQL treats STDDEV and STD as population (same as STDDEV_POP). SQL Server spells them STDEV (sample) and STDEVP (population). Write STDDEV_SAMP or STDDEV_POP where they exist.
  • STDDEV_SAMP (and SQL Server STDEV) over a single row is NULL; STDDEV_POP returns 0. Oracle's plain STDDEV is the exception: it returns 0 for one row where STDDEV_SAMP returns NULL.
  • Z-scores in one pass: (x - AVG(x) OVER ()) / NULLIF(STDDEV_SAMP(x) OVER (), 0); the NULLIF guards single-row partitions.

Questions about STDDEV with OVER

Does STDDEV work as a window function in SQLite?

No built-in stddev exists at all, window or not. Register a custom aggregate via sqlite3_create_window_function, or compute population stddev as SQRT(AVG(x*x) OVER w - AVG(x) OVER w * AVG(x) OVER w). SQRT needs the math functions (built into the sqlite3 shell since 3.35), and the formula loses precision when the mean is large relative to the spread.

STDEV or STDDEV: which spelling does my engine take?

PostgreSQL, Oracle and MySQL accept STDDEV, but MySQL's is the population figure while the other two return the sample one. SQL Server only knows STDEV (sample) and STDEVP (population). STDDEV_SAMP and STDDEV_POP work everywhere except SQL Server and SQLite.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, Oracle.

// fewer lookups

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.