Let’s assume following data:
id | parent_id |
---|---|
1 | null |
2 | null |
3 | 1 |
4 | 1 |
5 | 1 |
I’d like to return all records where parent_id
is either null or "distinctized":
id | parent_id |
---|---|
1 | null |
2 | null |
3 | 1 |
Thanks!
Let’s assume following data:
id | parent_id |
---|---|
1 | null |
2 | null |
3 | 1 |
4 | 1 |
5 | 1 |
I’d like to return all records where parent_id
is either null or "distinctized":
id | parent_id |
---|---|
1 | null |
2 | null |
3 | 1 |
Thanks!
3
Answers
You can use
UNION ALL
:Result :
Demo here
You can use a ranking function like
ROW_NUMBER
+ filtering:Output:
Check the demo here.
Try using
distinct on
as the following (supposing no negative values in the id, parent_id columns):To get the results sorted by id, we can wrap this query in a subquery and then order it as the following:
demo