T
T
TorchTT2013-11-25 19:04:18
SQL
TorchTT, 2013-11-25 19:04:18

Algorithm for sorting Order by by Case in SQL

Table:

first_column  second_column
1	      11
1	      12
2	      21
1	      13
2	      22
3	      31
3	      32
4	      23

Inside order by , the use of case is allowed, for example:
select * from TableTemp order by case when first_column = 1 then second_column 
else first_column end

Sort result:
first_column  second_colum
2	      22
2	      21
3	      31
3	      32
4	      23
1	      11
1	      12
1	      13

Can you please tell me how this sorting works?
The reason for the question is that in the first_column column, in addition to the value "1", there are "2", "3" and "4".
Looking ahead, did I understand correctly that all rows in which first_column = 1 are sorted by second_column, and all rows in which first_column !=1 are sorted by first_column?
Another way to work - if the table has at least one first_column value equal to "1", then the table should be sorted by the second_column column, otherwise - by the first column. However, there is no such sorting in the last column.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Guketlev, 2013-11-25
@TorchTT

The case value for each row is calculated and sorted by that value. For convenience, I showed what case will be equal to in each line, and it will be sorted by this number.

first_column  second_colum  Case_Value
2	      22	      2
2	      21	      2
3	      31	      3
3	      32	      3
4	      23	      4
1	      11	      11
1	      12	      12
1	      13	      13

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question