0

I have a table A as foolows:

id name      nextid    orderset
19  done               4
21  init       27      1
24  sent-req   19      3
27  offer-req  24      2

the orderset column gives me the order of the status: init -> offer-req -> sent-req -> done

I need to write a query that for a given id, it gives the id of the next status.

That should be easy:

select id
from A
where orderset= (select orderset+1 from A where id=Any_Given_ID)

That works in all cases except the last id... as there is no next to id=19, In the case of the last one I want the query to return 0.

I thought of doing a check with Max(orderset) and select order+1 from A where id=Any_Given_ID but I just can't seem to make it work.

Is it doable in a query or do I have to write a function for this operation?

1 Answer 1

2

Assuming the orders are consecutive, just use lead():

select id
from (select coalesce(lead(id) over (order by orderset), 0) as id
      from A
     ) a
where id = Any_Given_ID;

You can also use your method with aggregation. That guarantees that one row is returned:

select coalesce(max(id), 0)
from A
where orderset = (select orderset + 1 from A where id = Any_Given_ID);
Sign up to request clarification or add additional context in comments.

4 Comments

I'm confused... The reason I didn't though of using coalesce(something, 0), is because if first argument exists it always return him. So why would it return 0? max(id) exists.
@John . . . If the where clause has no matches, then the max() returns NULL.
thx. Can you also explain the lead example? The postgresql manual says: "returns value evaluated at the row that is offset rows after the current row within the partition" it's not very clear.
@John . . . There is no partition, so the entire data set is used. It gets the next value based on orderset.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.