'How to sort a MySQL table with null column values
I have a table with following schema. I need to sort table by points, and if rows wiith img_link present (not null) come first also. Simply need to do is - sort by int column, then by varchar column.
+-----+--------+-----------+-----------+
| id | name | img_link | points |
+-----+--------+-----------+-----------+
| 11 | smpl | path.jpg | 10 |
+-----+--------+-----------+-----------+
| 12 | main | null | 20 |
+-----+--------+-----------+-----------+
| 13 | abcd | null | 10 |
+-----+--------+-----------+-----------+
| 14 | xyls | img_.png | 10 |
+-----+--------+-----------+-----------+
Need a result like
+-----+
| id |
+-----+
| 12 |
+-----+
| 11 |
+-----+
| 14 |
+-----+
| 13 |
+-----+
Solution 1:[1]
You basically wrote out in words exactly what you need to do.
SELECT id FROM someTable ORDER BY points DESC, img_link DESC;
Solution 2:[2]
Try This
SELECT * FROM table_name ORDER BY points DESC ,ISNULL(img_link), img_link
Solution 3:[3]
Another way is
select *
from table
order by `points` desc,
if(img_link = '' or img_link is null,1,0)
Solution 4:[4]
try this:
select * from tabalename where img_link is not null order by point desc union select * from tabalename where img_link is null order by point desc
Solution 5:[5]
SELECT * FROM my_table ORDER BY points DESC, img_link IS NULL, img_link DESC;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Patrick Q |
| Solution 2 | |
| Solution 3 | Abhik Chakraborty |
| Solution 4 | Ronak Shah |
| Solution 5 | Strawberry |
