Learn SQL/Intermediate/Joins/SQL JOINs on Multiple Keys

SQL JOINs on Multiple Keys

Require MORE than one column to match at once — genuinely useful when a single column alone isn't enough to guarantee a correct match.

What & Why

Some relationships are correct only when several conditions match together. Comparing growth.cohort_retention periods requires the same cohort_month and a period_number offset of one; either condition alone can pair unrelated rows.

See How It Works

BUSINESS QUESTION

Growth matches each cohort period to its immediately previous period using cohort month and period number together.

cohort_monthperiod_numberusersretained
2024-01-010420420
2024-01-011420268
2024-01-012420214
2024-02-010510510
EXAMPLE QUERY
SELECT
  current.cohort_month,
  current.period_number,
  previous.retained AS previous_retained,
  current.retained AS current_retained
FROM growth.cohort_retention current
JOIN growth.cohort_retention previous
  ON previous.cohort_month = current.cohort_month
 AND previous.period_number = current.period_number - 1
ORDER BY current.cohort_month, current.period_number;
RESULT — exact output from the displayed Queryflo rows
cohort_monthperiod_numberprevious_retainedcurrent_retained
2024-01-011420268
2024-01-012268214

Both cohort_month and the one-period offset must match.

Now You Try

Practice this concept

Growth wants each cohort period beside the immediately previous period from the same cohort month.

Available schema
growth

Prefix tables with growth.table_name.

cohort_monthperiod_numberprevious_retainedcurrent_retained
growth.cohort_retention
ColumnType
cohort_monthdate
period_numberinteger
usersinteger
retainedinteger
legacy_cohort_idtext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario