Some My Experiences

Header Ads

Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Monday 4 February 2019

MySQL Positioning Order NULL Row to The End

Order by sequence number in ascending, positioning NULL value at last (order by id ascending)

SELECT * FROM picrure ORDER BY -sequence DESC, id ASC;
Given example: picture table
id sequence name
1 NULL picture_one
2 1 picture_two
3 2 picture_three
4 NULL picture_four
5 3 picture_five

In the query above we use (-) minus sign to sequence field that will negate/inverse sequence number, positive value will be negative, a negative value will be positive, NULL values will remain.

Item picture_two with id=2 order sequence will be -1 from 1 and so on. This query will order picture in ascending sequence if not null, otherwise order in ascending id.

id sequence name
2 1 picture_two
3 2 picture_three
5 3 picture_five
1 NULL picture_one
4 NULL picture_four

This two query will also give same result:

SELECT * FROM fortest.picture ORDER BY sequence IS NULL ASC, sequence ASC, id ASC;
SELECT * FROM fortest.picture ORDER BY ISNULL(sequence) ASC, sequence ASC, id ASC;