Learn SQL/Intermediate/Set Operations/SQL Combining Query Results

SQL Combining Query Results

A quick summary of all four set operations side by side — the same two source queries, four different outcomes.

What & Why

Every operation in this series answers a different question about the same two queries. Seeing all four outcomes listed together, from the exact same source data, makes the differences concrete.

See How It Works

BUSINESS QUESTION

Growth wants signups and activations in one chronological activity feed.

idcreated_atcountrychannelplanactivated_atchurned_at
1012024-01-15 09:10:00+00USorganicpro2024-01-16 14:25:00+00NULL
1022024-02-10 11:05:00+00CApaidfreeNULL2024-03-20 10:00:00+00
1032024-03-12 16:35:00+00GBreferralpro2024-03-13 08:15:00+00NULL
1042024-04-01 13:20:00+00USorganicfree2024-04-03 12:00:00+00NULL
EXAMPLE QUERY
SELECT
  id AS user_id,
  created_at AS occurred_at,
  'signup' AS activity_type
FROM growth.users
UNION ALL
SELECT
  id AS user_id,
  activated_at AS occurred_at,
  'activation' AS activity_type
FROM growth.users
WHERE activated_at IS NOT NULL
ORDER BY occurred_at, user_id, activity_type;
RESULT — exact output from the displayed Queryflo rows
user_idoccurred_atactivity_type
1012024-01-15 09:10:00+00signup
1012024-01-16 14:25:00+00activation
1022024-02-10 11:05:00+00signup
1032024-03-12 16:35:00+00signup
1032024-03-13 08:15:00+00activation
1042024-04-01 13:20:00+00signup
1042024-04-03 12:00:00+00activation

UNION ALL keeps four signups and the three non-null activation timestamps.

Now You Try

Practice this concept

Growth wants signups and activations in one chronological activity feed.

Available schema
growth

Prefix tables with growth.table_name.

user_idoccurred_atactivity_type
growth.users
ColumnType
idinteger
created_attimestamp with time zone
countrytext
channeltext
plantext
activated_attimestamp with time zone
churned_attimestamp with time zone
legacy_user_codetext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario