Gediminas Šukys
Gediminas Šukys

Reputation: 7391

Order by own `position` using sql

I have few hundreds items in table with position is null, I want to do an order by position and set position to 1,2,3,4 and etc, but also live the other results with same position is null

the problem is, if I'm ordering by order by position asc, first results come where position is null and only after them comes results I want to be first. I what that these results with null would go in the end.

Is it possible to solve this only with sql?

Upvotes: 0

Views: 42

Answers (2)

DanteTw
DanteTw

Reputation: 60

select position
from YourTable
order by case 
when position is null 
then 1 else 0 end, position

Upvotes: 1

DZDomi
DZDomi

Reputation: 1679

You can use:

Select position --Your other columns
from yourtable
where position is not null
order by position asc
UNION
Select position --Your other columns
from yourtable
where position is null

But be sure to have the same number and names of columns for each select

Upvotes: 2

Related Questions