Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order 1,2,3 not 1, 10, 11, 12 in mySQL

The following code outputs in order of 1, 10, 11, 12 of id.

I want to make it 1,2,3,4...

Could anyone tell me what I should do please.

$Q = $this->db->query('SELECT P.*, C.Name AS CatName FROM products AS P LEFT JOIN categories C ON C.id = P.category_id'); 

Thanks in advance.

like image 610
shin Avatar asked Dec 02 '09 14:12

shin


People also ask

How do I sort numbers in MySQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you sequence numbers in SQL?

The syntax to create a sequence in SQL Server (Transact-SQL) is: CREATE SEQUENCE [schema.] sequence_name [ AS datatype ] [ START WITH value ] [ INCREMENT BY value ] [ MINVALUE value | NO MINVALUE ] [ MAXVALUE value | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE value | NO CACHE ]; AS datatype.


2 Answers

First, add an order by clause at the end:

ORDER BY category_id 

If category_id is a string, then you must treat it like an integer. There are a few ways to do this. I usually add a zero. You can also cast it.

ORDER BY category_id + 0 
like image 163
Scott Saunders Avatar answered Sep 26 '22 00:09

Scott Saunders


As previously mentioned MySQL doesn't support alphanumeric sorting. One common trick to solve this is to first order by length:

ORDER BY LENGTH(column_name), column_name 

As long as the non-numeric part of the value is the same length, this will sort 1 before 10, 10 before 100, etc.

like image 30
Andreas Bergström Avatar answered Sep 23 '22 00:09

Andreas Bergström