Kiran M R
Kiran M R

Reputation: 91

Order rows of Data Table based on non null values of different columns in SQL

I have a table like

id  colA  ColB  ColC  COlD 
1   10    Null  Null  100 
2   Null  2     Null  200 
3   Null  Null  7     500

and so on

what i need is if i select the values from the table like

select * from Table where ColC = 7 or ColB = 2 or ColA = 10

i will get the resul as

10    Null   Null 100
Null  2      Null 200
Null  Null   7    500

but i want the result as

Null  Null  7    500
Null  2     Null 200
10    Null  Null 100 

So i could select value of ColD from top row only if the ColC is not null else if ColB is not null else ColA is not null

Upvotes: 1

Views: 159

Answers (1)

Igor Borisenko
Igor Borisenko

Reputation: 3866

Try this

select * 
from Table 
where ColC = 7 or ColB = 2 or ColA = 10
ORDER BY ColC DESC, ColB DESC, ColA DESC

Upvotes: 2

Related Questions