SQL: How to sort rows on two columns but using conditions on those columns
I have a table with two columns. We'll call the table Table1 and the columns Col1 and Col2 which are both text columns.
Some rows will have data in Col1 while Col2 will be null. Then there are some rows where Col1 will be null and Col2 will have data. And finally, some rows will have data in both. No rows exist where both columns are null.
I want to read all the rows but the sorting needs to be as follows: If Col1 has data, then that column is used, regardless what is in Col2. If Col1 is null, it uses Col2.
I'm not even sure if generating this by sorting is even possi开发者_Python百科ble. Thanks for any help.
There are several ways to do it. Here's one:
order by coalesce(col1, col2)
....
order by
case when Col1 is not null then Col1
when Col1 is null then Col2
end
精彩评论