MySQL order by ABS if numeric

mysql, sql-order-by

Solution

This code is the MySql way of your question:

SELECT * FROM table 
ORDER BY
CASE WHEN LEFT(name, 1)>='0' AND LEFT(name, 1)<='9' THEN ABS(name) 
     ELSE name 
     END ASC

(Edit) But according to comments, is better for you:

ORDER BY ABS(name), name

That works in this way: If ABS() can be applied to 'name' the numeric resulting value will be ordered, but in the opposite case, if ABS(name) evaluates to null (because a non numeric has no abs value) then the second field (name) on order by, is which is relevant to the sort.

Problem

I need to order some information with order by in a MySQL query. Is there a possibility to use the ABS function only if the first char is numeric? Pseudo example: ``` SELECT * FROM table ORDER BY (( name[0] = numeric ) ? ABS(name) : name) ASC ``` Thanks for the answers so far, tried a lot with your answers but I don't get the result I want. The current code: ``` <?php $filters = $this->db->query(" SELECT tb_spec_feature.feature_id, tb_spec_feature.name FROM tb_spec_feature WHERE filter=1 "); $filters = $filters->result_array(); foreach($filters as $key=>$filter) { $filters_sub = $this->db->query(" SELECT DISTINCT tb_spec_value.value_id, tb_spec_value.name as value_name, tb_spec_sign.name as sign_name FROM tb_spec_fk INNER JOIN tb_spec_value ON tb_spec_value.value_id = tb_spec_fk.value LEFT JOIN tb_spec_sign ON tb_spec_sign.sign_id = tb_spec_fk.sign WHERE feature=".$this->db->escape($filter['feature_id'])." ORDER BY ABS(tb_spec_value.name) ASC "); $filters[$key]['values'] = $filters_sub->result_array(); } ?> ``` This will output (tb_spec_feature.name and then the tb_spec_value.name): Screen inches - 7 - 7.7 - 7.9 - 8.9 - 9.7 - 10 - 10.1 - 12.1 Resolution - 800 x 480 - 1024 x 600 - 1024 x 768 - 1280 x 800 - 1280 x 768 - 1920 x 1200 - 2048 x 1536 Operating system - Android 3.1 - Android - BlackBerry Tablet OS - Android 3.2 - Android 2.3 - Android 4.0 - iOS 5 - Android 4.0.3 - iOS 4 - Android 2.2 - Windows 7 Professional - Windows 8 - Windows 8 Pro - iOS 6 As you can see the inches and resolutions are okay, but the operating systems aren't ordered well. If I remove the ABS the result will be: Screen inches - 10 - 10.1 - 12.1 - 7 - 7.7 - 7.9 - 8.9 - 9.7 Resolution - 1024 x 600 - 1024 x 768 - 1280 x 768 - 1280 x 800 - 1366 x 768 - 1920 x 1200 - 2048 x 1536 - 800 x 480 Operating system - Android - Android 2.2 - Android 2.3 - Android 3.1 - Android 3.2 - Android 4.0 - Android 4.0.3 - BlackBerry Tablet OS - iOS 4 - iOS 5 - iOS 6 - Windows 7 Professional - Windows 8 - Windows 8 Pro As you can see now, the operating systems are ordered well but the inches and resolutions not.. I hope somebody can help me out :)

Original source