Learn SQL/Advanced/Window Functions/SQL ORDER BY in a Window Function

SQL ORDER BY in a Window Function

Define analytic row sequence independently from final result sorting.

What & Why

ORDER BY inside OVER controls window order for ranking, offsets, and frames; the query's outer ORDER BY controls display order. An explicit analytic sequence is required for meaningful ranks and offsets, even when the result is displayed in a different order.

See How It Works

BUSINESS QUESTION

Growth numbers user signups chronologically but displays the newest signup first.

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,
  ROW_NUMBER() OVER (ORDER BY created_at, id) AS signup_sequence
FROM growth.users
ORDER BY created_at DESC, user_id DESC;
RESULT — sequence calculated, newest displayed first
user_idcreated_atsignup_sequence
1042024-04-01 13:20:00+004
1032024-03-12 16:35:00+003
1022024-02-10 11:05:00+002
1012024-01-15 09:10:00+001

The window order assigns the sequence independently of the final descending display order.

Advanced business practice

Sign up free to try it on a real business scenario