Example 1
Find the slope and intercept of the study-hours vs test-score relationship
The three data points (1,3), (2,5), (3,7) lie perfectly on the line score = 2 × hours + 1, so the slope is 2.0, the intercept is 1.0, and R² = 1.0 (perfect fit — no residual variance). In practice, real data is noisy and R² will be less than 1. The slope 2.0 means each additional hour of study predicts an increase of 2 points. To predict a score for a new hours value, multiply slope by hours and add intercept: 4 hours → 2 × 4 + 1 = 9. To compute slope manually in engines without REGR_SLOPE: (n·Σxy − Σx·Σy) / (n·Σx² − (Σx)²) where n = COUNT(*), which for this data gives (3×34 − 6×15) / (3×14 − 36) = 12/6 = 2.0.
CREATE TABLE study_data (hours_studied INT, test_score INT);
INSERT INTO
study_data
VALUES
(1, 3),
(2, 5),
(3, 7);SELECT
REGR_SLOPE(test_score, hours_studied) AS slope,
REGR_INTERCEPT(test_score, hours_studied) AS intercept,
REGR_R2(test_score, hours_studied) AS r_squared
FROM
study_data;| slope | intercept | r_squared |
|---|---|---|
| 2 | 1 | 1 |
Only PostgreSQL supports REGR_SLOPE, REGR_INTERCEPT, and REGR_R2 as built-in aggregates.