Learn SQL/Intermediate/Date & Time/SQL Time Between Events

SQL Time Between Events

The TIMESTAMP version of the same idea — subtracting two event timestamps gives an INTERVAL, precise down to the second.

What & Why

When both sides are TIMESTAMP rather than plain DATE, subtraction gives an INTERVAL — precise to the second, not just whole days. This is the right tool for questions like "how long between login and first click."

See How It Works

BUSINESS QUESTION

Growth wants the duration of every completed user session.

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
EXAMPLE QUERY
SELECT
  id AS session_id,
  user_id,
  ended_at - started_at AS session_duration
FROM growth.sessions
WHERE ended_at IS NOT NULL
ORDER BY session_duration DESC, session_id;
RESULT — exact output from the displayed Queryflo rows
session_iduser_idsession_duration
500310300:54:00
500710700:33:00
500110100:32:00
500610600:27:00
500510500:21:00
500210200:08:00

The open session is excluded and completed sessions sort by duration.

Now You Try

Practice this concept

Growth wants the elapsed duration of every completed user session.

Available schema
growth

Prefix tables with growth.table_name.

session_iduser_idsession_duration
growth.sessions
ColumnType
idbigint
user_idinteger
started_attimestamp with time zone
ended_attimestamp with time zone
page_viewsinteger
devicetext
internal_session_scoreinteger
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario