I have a table that is to be sorted based on two columns of numbers (call them Column X and Column Y). In each row, the two columns can either both have numeric values (in which case X<=Y), or one of the columns can be NULL.
Example data:
X Y
----- -----
... NULL 26
... 31 NULL
... 1 7
... 39 46
... NULL 36
... 15 16
... NULL 14
... 23 29
I would like to sort this data so that the columns interleave “correctly”. Specifically:
1) If the X value is present in both rows, order based on X.
2) Else, if the Y value is present in both rows, order based on Y.
3) Else, compare the available X value and the available Y value.
The “correct” sorting of the example data would be:
X Y
----- -----
... 1 7
... NULL 14
... 15 16
... NULL 26
... 23 29
... 31 NULL
... NULL 36
... 39 46
Is there any simple way to perform this sorting, in an ORDER BY clause?
You can’t. The order is not well defined
The simple set
can be sorted
and
depending on where you start sorting.
If possible I would change the sort criteria to “
Xif available, otherwiseY“. Then you could use the COALSECE operator as suggested by “mu is too short”. (order by coalesce(x, y))