I currently have this SQL:
select ROW_NUMBER()OVER(order by priority DESC NULLS LAST
, created_at DESC) as index
, id
, title
, ago(created_at)
, priority
, user_id
from post
order by priority DESC NULLS LAST
, created_at DESC;
As you can see, I need to have ROW_NUMBER()
and that needs the order by priority DESC NULLS LAST, created_at DESC) as index, id, title, ago(created_at
.
This is causing me to repeat the same long order by priority DESC NULLS LAST, created_at DESC
twice.
If I need to have even more columns in the order by, that will make it even longer.
Is there a way to prevent this repetition? I tried using an alias after the ORDER BY
but that doesn’t seem to be supported.
3
Answers
Just order by the first column:
See also the manual
If you’re looking to re-use the window definition, you can define it separately using
window w1 as (order by..)
, thenrow_number() over (..)
becomesrow_number()over w1
and you can reference the same window definition from any other window function. You can also base new window definitions on the one you already have.demo at db<>fiddle