SQL UNION ALL

Combines two queries' results and keeps every row, duplicates included — faster than UNION, since there's no deduplication work to do.

What & Why

UNION ALL stacks the rows from two queries together exactly like UNION, but skips the deduplication step entirely. Every row from both queries survives into the result, even if the exact same row appears in both.

See How It Works

BUSINESS QUESTION

Growth wants every membership in the desktop and 5-to-8 page-view cohorts, including users who belong to both.

iduser_idstarted_atended_atpage_viewsdevice
50011012024-01-16 14:20:00+002024-01-16 14:52:00+008desktop
50021022024-02-10 11:10:00+002024-02-10 11:18:00+003mobile
50031032024-03-13 08:10:00+002024-03-13 09:04:00+0012desktop
50041042024-04-03 12:00:00+00NULL1tablet
50051052024-04-04 09:00:00+002024-04-04 09:21:00+007mobile
50061062024-04-05 10:15:00+002024-04-05 10:42:00+005tablet
50071072024-04-06 13:05:00+002024-04-06 13:38:00+0010desktop
Watch compatible tables produce a set resultStep 1 of 3
Desktop session users
user_id
101
103
107
UNION ALL
Sessions with 5–8 page views
user_id
101
105
106
Result set · 0 rows
user_id

Read the first compatible one-column result from growth.sessions.

EXAMPLE QUERY
SELECT DISTINCT
  user_id
FROM growth.sessions
WHERE device = 'desktop'
UNION ALL
SELECT DISTINCT
  user_id
FROM growth.sessions
WHERE page_views BETWEEN 5 AND 8
ORDER BY user_id;
Now You Try

Practice this concept

Growth wants every membership in the desktop and 5-to-8 page-view cohorts, including users who belong to both.

Available schema
growth

Prefix tables with growth.table_name.

user_id
growth.sessions
ColumnType
idbigint
user_idinteger
started_attimestamp with time zone
ended_attimestamp with time zone
page_viewsinteger
devicetext
internal_session_scoreinteger
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