sql - Finding if current row is last row to be selected from database -


i selecting list of periods database. if current row first row period starts date , can find interval between period start this:

select ... case when row_number() over(order r.created_at asc) = 1 r.created_at - r.created_at::date else null end period ... mytable r 

how can same last row? find time between r.created_at of last row , midnight of date.

i aware of first , last functions in postgresql (https://wiki.postgresql.org/wiki/first/last_(aggregate)), aggregate functions , not in case.

edit: question has 2 great answers. neither of them in case, single line presented part of question part of bigger query, put programmatically , using solutions offered force me alter alot of code, not willing @ point. should scaling problems hit - reconsider.

this might faster window functions:

with r (     select         min(created_at) min_created_at,         max(created_at) max_created_at     mytable ) select     case when (select min_created_at r) = created_at     created_at - created_at::date else null     end period_min,     case when (select max_created_at r) = created_at     created_at - created_at::date else null     end period_max mytable 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -