BBampaa

Lessons › SQL › Deep Dive: Business Analytics Patterns

SQL lesson

Correlation with CORR()

CORR(y, x) gives one number from -1 to 1 that says how closely two columns move together.

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

Example

Do two numbers move together?

SELECT CORR(units_sold, price) AS correlation
FROM products

Result:

correlation
-0.863459396947833

Step by step

  1. units_sold is what you want to explain, price is what might explain it.
    SELECT units_sold, price
    FROM products;
  2. CORR(units_sold, price) returns one number for the whole table.
    SELECT CORR(units_sold, price)
    FROM products;
  3. AS gives the number a clear name in the report.
    SELECT CORR(units_sold, price) AS correlation
    FROM products;

Practice

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

1. Show the correlation between units_sold and price, as correlation.
SELECT CORR(units_sold, price) AS correlation FROM products
2. Show the correlation between units_sold and rating, as correlation.
SELECT CORR(units_sold, rating) AS correlation FROM products
3. Show the correlation between units_sold and price, rounded to 2 decimal places, as correlation.
SELECT ROUND(CORR(units_sold, price)::numeric, 2) AS correlation FROM products
4. Show two correlations: units_sold with price as price_link, and units_sold with rating as rating_link.
SELECT CORR(units_sold, price) AS price_link, CORR(units_sold, rating) AS rating_link FROM products
5. Show the correlation between price and rating, as correlation.
SELECT CORR(price, rating) AS correlation 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