Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL ORDER BY numeric value problem with negative numbers

Tags:

mysql

I am using a query which uses:

ORDER BY score DESC;

'score' just holds numeric values, which can also be negative. They don't seem to be displaying in the correct order. The negative numers can appear above positive numbers.

Does anyone know the query I should use to display them like this:

  • 10
  • 5
  • 1
  • -1
  • -5
  • -10

And also to stop them doing this:

* 1
* 10
* 11
* 123
* 1234
* 2
* 25
* 253
* 34

Thanks.

like image 754
Tom Avatar asked Feb 22 '11 22:02

Tom


People also ask

Can Numeric in SQL be negative?

Numeric value is negative. Returns the ones complement of the number. The + (Positive) and - (Negative) operators can be used on any expression of any one of the data types of the numeric data type category.

How do you avoid negative numbers in SQL?

First, change your query: UPDATE tblProducts SET qty = qty - @quantity where pName = @name AND qty >= @quantity; SELECT @@ROWCOUNT; Then, instead of using ExecuteNonQuery use ExecuteScalar and check if the number of records modified is 0 it means that the @quantity is bigger than the value of qty .

How do I stop negative values in MySQL?

You can create an int field and mark it as UNSIGNED . From MySQL 5.0 Reference Manual: INT[(M)] [UNSIGNED] [ZEROFILL] A normal-size integer. The signed range is -2147483648 to 2147483647.

What is a good way to keep a column with int data type from going negative within the database?

If your application will never use negative numbers for an integer column, always define it as unsigned. This prevents unwanted negative numbers from being stored in the column. In addition, unsigned integer is smaller in length than the corresponding signed integer.


2 Answers

order by cast(score as int) desc;

It appears that you are storing numeric data in a string data type. It would be better to make score a numeric data type, like int.

like image 90
mellamokb Avatar answered Nov 15 '22 10:11

mellamokb


It's possible to order by a cast varchar by casting the field using:

ORDER BY CAST(`table.field` AS SIGNED) DESC

Where SIGNED will turn the varchar to a integer (which can be a negative value).

A guide is available here: http://www.kreci.net/web-development/sort-varchar-as-int-in-mysql-query/

like image 31
Erik Avatar answered Nov 15 '22 11:11

Erik