SQL CORR function
Returns the Pearson correlation coefficient of two numeric columns in a group.
- Returns
numeric (-1 to 1)- In this category
- 25 of 52
語法
CORR(y, x) | CORR(y, x) OVER (...)
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Not built in | same formula with STDEVP, over complete pairs, cast to float first |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Not built in | compute manually: (AVG(y*x) - AVG(y)*AVG(x)) / (STDDEV_POP(y)*STDDEV_POP(x)) over complete pairs |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | 是 | Supported under this name. |
範例
PostgreSQL
SELECT corr(height, weight) FROM people;
Oracle
SELECT dept_id, CORR(salary, age) FROM employees GROUP BY dept_id;
小知識
- Only rows where both inputs are non-NULL count; a NULL in either column drops the whole pair.
- Fewer than two complete pairs returns NULL; a zero-variance column also yields NULL.
- The result is between -1 and 1; it measures linear correlation only.
- MySQL and SQL Server lack CORR and COVAR_*, so compute (AVG(y*x) - AVG(y)*AVG(x)) / (STDDEV_POP(y) * STDDEV_POP(x)), STDEVP on SQL Server. Filter to rows where both columns are non-NULL first, and on SQL Server cast integer columns to float, because AVG of an int column returns a truncated int.
Questions about CORR
What does CORR = 0 mean?
No linear relationship detected; a strong curve can still hide behind r near 0.
How does CORR treat NULLs?
Pairs with either value NULL are excluded entirely: it correlates complete pairs only.
How do I compute it in MySQL?
(AVG(y*x) - AVG(y)*AVG(x)) / (STDDEV_POP(y) * STDDEV_POP(x)), with WHERE y IS NOT NULL AND x IS NOT NULL so every term uses the same rows.
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, 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.