SQL EXCEPT

Keeps rows from the FIRST query that do NOT appear in the second — order matters here, unlike every other set operation in this series.

What & Why

EXCEPT returns rows from the first query that don't show up anywhere in the second. This is the one set operation in this series where order matters — A EXCEPT B and B EXCEPT A generally produce completely different results, not just a differently-ordered version of the same rows.

See How It Works

BUSINESS QUESTION

Growth wants desktop users who are not in the 5-to-8 page-view cohort.

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 2
Desktop session users
user_id
101
103
107
A EXCEPT B
Sessions with 5–8 page views
user_id
101
105
106
Result set · 2 rows
user_id
103
107

Users 103 and 107 have desktop sessions but no session in the 5–8 page-view set.

EXAMPLE QUERY
SELECT DISTINCT
  user_id
FROM growth.sessions
WHERE device = 'desktop'
EXCEPT
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 desktop users who are not in the 5-to-8 page-view cohort.

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