BBampaa

Lessons › SQL › Deep Dive: Business Analytics Patterns

SQL lesson

Trend lines with REGR_SLOPE() and REGR_INTERCEPT()

REGR_SLOPE(y, x) says how much y changes for each 1 more of x. REGR_INTERCEPT(y, x) is where that straight line starts. Together they draw the trend line.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

How much do sales change per dollar?

SELECT REGR_SLOPE(units_sold, price) AS slope,
       REGR_INTERCEPT(units_sold, price) AS intercept
FROM products

Result:

slopeintercept
-0.355029585798817132.248520710059

Step by step

  1. How many units sales change for each $1 of price. Negative: higher price, fewer sales.
    SELECT REGR_SLOPE(units_sold, price) AS slope
    FROM products;
  2. Where the line starts: the trend's units sold at a price of 0.
    SELECT REGR_SLOPE(units_sold, price) AS slope,
           REGR_INTERCEPT(units_sold, price) AS intercept
    FROM products;
  3. Predicted units = intercept + slope × price. Use it to test a price change before you make it.
    SELECT REGR_SLOPE(units_sold, price) AS slope,
           REGR_INTERCEPT(units_sold, price) AS intercept
    FROM products;

Practice

Try each one in your head first, then open the answer.

1. Show the slope of units_sold against price, as slope.
SELECT REGR_SLOPE(units_sold, price) AS slope FROM products
2. Show the intercept of units_sold against price, as intercept.
SELECT REGR_INTERCEPT(units_sold, price) AS intercept FROM products
3. Show the slope and intercept of units_sold against price, as slope and intercept.
SELECT REGR_SLOPE(units_sold, price) AS slope, REGR_INTERCEPT(units_sold, price) AS intercept FROM products
4. Show the slope of units_sold against rating, as slope.
SELECT REGR_SLOPE(units_sold, rating) AS slope FROM products
5. Predict units sold at a price of 100: the intercept plus the slope × 100, as predicted_units.
SELECT REGR_INTERCEPT(units_sold, price) + REGR_SLOPE(units_sold, price) * 100 AS predicted_units FROM products

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed