Learn SQL/Intermediate/Joins/SQL Many-to-Many Relationships

SQL Many-to-Many Relationships

Many rows on BOTH sides can relate to many rows on the other — this pattern always needs a third, 'junction' table in between to actually work.

What & Why

A many-to-many relationship lets each row on both sides relate to several rows on the other side. product.feature_usage acts as a bridge: one feature can be used by many users, and one user can use many features.

See How It Works

BUSINESS QUESTION

Product wants the unique user-feature pairs recorded by feature usage.

idnamedescriptionteamreleased_atdeprecated_at
1Activation ChecklistGuides new users through setupgrowth2024-01-20NULL
2CSV ExportExports report dataplatform2024-02-14NULL
3Invite NudgesPrompts workspace collaborationgrowth2024-03-05NULL
4Legacy DashboardOriginal reporting surfaceanalytics2023-08-102024-06-01
idfeature_iduser_idused_atsession_id
700111012024-01-25 12:20:00+00sess_101a
700221022024-02-20 15:45:00+00sess_102a
700311032024-03-18 09:10:00+00sess_103a
700431042024-04-08 17:35:00+00sess_104a
EXAMPLE QUERY
SELECT DISTINCT
  f.name AS feature_name,
  u.user_id
FROM product.features f
JOIN product.feature_usage u ON u.feature_id = f.id
ORDER BY feature_name, user_id;
RESULT — exact output from the displayed Queryflo rows
feature_nameuser_id
Activation Checklist101
Activation Checklist103
CSV Export102
Invite Nudges104

product.feature_usage supplies the four real feature-to-user bridge rows.

Now You Try

Practice this concept

Product wants the first 100 unique user-feature pairs represented by feature usage.

Available schema
product

Prefix tables with product.table_name.

feature_nameuser_id
product.feature_usage
ColumnType
idbigint
feature_idinteger
user_idinteger
used_attimestamp with time zone
session_idtext
deprecated_usage_sourcetext
product.features
ColumnType
idinteger
nametext
descriptiontext
teamtext
released_attimestamp with time zone
deprecated_attimestamp with time zone
internal_priorityinteger
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario