I’m trying to order columns by empty string last. For example.
NAME
--------------------------
Apple
''
Orange
Avocado
Banana
Cauliflower
Broccoli
''
Potato
Cabbage
The order should be like this without alphabetical order
NAME
--------------------------
Apple
Orange
Avocado
Banana
Cauliflower
Broccoli
Potato
Cabbage
''
''
but what I’m getting is
NAME
--------------------------
Apple
Avocado
Banana
Broccoli
Cauliflower
Cabbage
Orange
Potato
''
''
I tried many queries with if, case .etc but all of them were ordered alphabetically
some of the solutions I tried
SELECT * FROM `comments` order by NULLIF(NULLIF(comment ,'0'),''),comment desc;
SELECT * FROM `comments` ORDER BY IF(comment IS NULL, 1,0), comment desc;
SELECT * FROM `comments` ORDER BY case when comment is null then 1 else 0 end,
comment desc
2
Answers
Update:
You can simply use
(name ='')
as order by clause which will return 1 if name is empty other wise 0.If you have
null
as well then you can use:Here
NULLIF(name,'')
will convert empty string into nullYou can select rows without empty strings first without any order. Then you can select the rows with empty strings. You can combine both the results with
union all
Query:
select * from comments where name <>”
union all
select * from comments where name =”
Output:
fiddle
Better approach would be to use conditional order clause like below:
Query:
select * from comments order by (case when name =” then 1 else 0 end)
Output:
fiddle
Have you tried checking if
comment
column is empty string in conjunction with checking fornull
?or using trim method
Also I noticed in the table, you showed the column name is
NAME
instead ofcomment
, just want to clarify if the column name is eitherNAME
orcomment
? If it’sNAME
, the query should reflect that