SQL REGR_SLOPE function
Returns the slope of the least-squares line fitted to the complete (y, x) pairs of a group.
- Category
- Aggregates
- Returns
numeric- In this category
- 28 of 52
Syntax
REGR_SLOPE(y, x) | REGR_SLOPE(y, x) OVER (...)
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Not built in | same manual formula; cast integers to float |
| PostgreSQL | Yes | Supported under this name. |
| MySQL | Not built in | manual: (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)) over complete pairs |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Yes | Supported under this name. |
Examples
PostgreSQL
SELECT regr_slope(sales, ad_spend) FROM monthly;
Oracle
SELECT REGR_SLOPE(sales, ad_spend) OVER (PARTITION BY region) FROM monthly;
Good to know
- Only complete pairs count: a NULL in y or x drops the row.
- The result is NULL when there are fewer than two pairs or when every x is the same (VAR_POP(x) = 0).
- The companion intercept is REGR_INTERCEPT(y, x) = AVG(y) - REGR_SLOPE(y, x) * AVG(x).
- MySQL and SQL Server have no REGR_ functions; slope = (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)).
Questions about REGR_SLOPE
What is REGR_SLOPE mathematically?
COVAR_POP(y, x) / VAR_POP(x), the least-squares estimate of dy/dx.
Why is my result NULL?
Fewer than two complete pairs, or every x value identical, leaves the slope undefined.
Does MySQL have REGR_SLOPE?
No; compute (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)) over complete pairs.
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.