Framework: Weird issue with orderBy

Created on 18 Mar 2018  路  6Comments  路  Source: laravel/framework

  • Laravel Version: 5.6
  • PHP Version: 7.1.12
  • Database Driver & Version: MySQL 5.6.38

Description:

When using groupBy() it returns the wrong order!?!

E.g If we have a database with a column named address and then type in a lot of address

example:

someRoadName 5 
someRoadName 22 
someRoadName 2 
someStreetName 18 
someStreetName 16 
someStreetName 15 
someRoadName 13

Then it returns:

someStreetName 18 
someStreetName 16 
someStreetName 15 
someRoadName 5 
someRoadName 22 
someRoadName 2 
someRoadName 13

What happened to the numbers and why is orderBy not using those two?

Most helpful comment

The reason is that you are sorting strings and they are sorted character after character.

So "someRoadName 5" is higher than "someRoadName 22" because the database compares "someRoadName 5" with "someRoadName 2". Only then it looks at the second "2".

You could solve it by storing the number in a separate integer column (if they all are integers).

All 6 comments

What query are you using?

@staudenmeir
DB::table("myTable")->where('id', '=', $id)->orderBy('address', 'desc')->get();

In the title and in the question it says "groupBy()". You mean "orderBy()"?

@staudenmeir Oh! sorry my bad and yes i mean orderBy

The reason is that you are sorting strings and they are sorted character after character.

So "someRoadName 5" is higher than "someRoadName 22" because the database compares "someRoadName 5" with "someRoadName 2". Only then it looks at the second "2".

You could solve it by storing the number in a separate integer column (if they all are integers).

Recommend this one to be closed based on response from @staudenmeir

Was this page helpful?
0 / 5 - 0 ratings