sorting numbers stored in text field in MYSQL database - mysql

i have a mySQL database with a text field in which is stored a number.
i need to produce a recordset sorted in descending numerical order.
this works fine until we get to numbers greater than 10 ie
9
8
7
6
5
4
3
2
10
1
is there a simple way of sorting this 'correctly' ?
(yes, i know i should have numbers in a numerical field, but i'm working with what i have :))
i'm using the results on an asp/vbscript/jquery page so maybe even a client-side solution is viable...
any suggestions?

ORDER BY ABS(text_column) DESC
Or, if you also have to deal with negative values:
ORDER BY CAST(text_column AS SIGNED) DESC

You need to type cast it to INTEGER using CAST function in MySQL:
ORDER BY CAST(text_column AS UNSIGNED INTEGER)

Try this one -
... ORDER BY text_column * 1

Related

Order number and strings putting strings last

I am trying to make a SQL statement that selects and orders numbers in DESC but put all strings last
so mysql is:
"SELECT * FROM posts ORDER BY price DESC"
and that gives me something like
test
best offer
6000
100
10
what I want is:
6000
100
10
test
best offer
or (doesnt matter)
6000
100
10
best offer
test
SELECT * FROM posts
ORDER BY price * 1 DESC
SQLFiddle demo
I think want you actually want is:
SELECT * FROM t ORDER BY value ASC;
which returns:
10
100
6000
best offer
test
SQL Fiddle
If you generally do not care about performance, you can do something like this:
SELECT * FROM posts
ORDER BY
CASE CAST(price AS int) WHEN 0 THEN ' ' ELSE price END DESC,
price ASC;
You might need the casts to int depending on your database.
You can also fiddle with the first expression to get the results you want. The point is that you have to sort first by whether it's a number or not and then the actual content.
The problem is that this you can't use any indexes this way. If you are allowed to change the database structure, it would be better to split the data into two columns. An int column with the price and a varchar column with the price description (in which case the first column is NULL). Then you can do faster queries.

mysql sort alphabetical and number

I have an array that I want to sort alphabetically but also by the number at the end.
"SELECT DISTINCT Number FROM database WHERE 1 Order By Number ASC";
Here is how it currently sorts:
Number 1
Number 10
Number 11
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
The End
This is how I want it to sort:
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 8
Number 9
Number 10
Number 11
The End
Add another sort condition:
Order By LENGTH(Number), Number;
This works because a longer number is also a bigger number; for numbers of the same length, you can make a textual comparison, because '0' < '1' .... < '9'
Try this :-
SELECT distinct numberr FROM tablename Order By cast(substring(numberr,7) as unsigned int) ASC ;
Its working fine.
Out put :-
Number 1
Number 2
Number 3
Number 4
Number 5
Number 6
Number 7
Number 10
Number 11
sql has functions to cast a string to an integer while it's sorting.
If you are using mysql, this is what you'd use to do what you want:
SELECT DISTINCT Number FROM database Order By CAST(Number AS UNSIGNED) ASC
If you are using a different database, you will need to google how to cast a column to an integer for your database.
Note: some of the other solutions work... but are kind of hacky - ie they look cool, but might not work in future. The above does exactly what you want and is how you are "supposed" to do it ;)
"SELECT DISTINCT Number FROM database WHERE 1 Order By substring_index(Number,'Number',1),cast(substring_index(Number,'Number ',-1) as unsigned int) ASC";
I'm much late but I faced the same issue. My answer could help those who are facing.
You can use SUBSTRING_INDEX function to solve this issue. Like your number is at the end of the string. Your query should be.
SELECT DISTINCT Number
FROM database
WHERE 1 Order By 0+SUBSTRING_INDEX(Number,' ',-1)
ASC;
what this will do is it will take the last chunk of the text separated by space. and the 0+ will force to convert it to integer.
try adding "+0" to the sort field:
SELECT DISTINCT Number FROM database WHERE 1 Order By Number+0 ASC

Is there a possibility to change the order of a string with numeric value

I have some strings in my database. Some of them have numeric values (but in string format of course). I am displaying those values ordered ascending.
So we know, for string values, 10 is greater than 2 for example, which is normal. I am asking if there is any solution to display 10 after 2, without changing the code or the database structure, only the data.
If for example I have to display values from 1 to 10, I will have:
1
10
2
3
4
5
6
7
8
9
What I would like to have is
1
2
3
4
5
6
7
8
9
10
Is there a possibility to ad an "invisible character or string which will be interpreted as greater than 9". If i put a10 instead of 10, the a10 will be at the end but is there any invisible or less visible character for that.
So, I repeat, I am not looking for a programming or database structure solution, but for a simple workaround.
You could try to cast the value as an number to then order by it:
select col
from yourtable
order by cast(col AS UNSIGNED)
See SQL Fiddle with demo
You could try appending the correct number of zeroes to the front of the data:
01
02
03
..
10
11
..
99
Since you have a mixture of numbers and letters in this column - even if not in a single row - what you're really trying to do is a Natural Sort. This is not something MySQL can do natively. There are some work arounds, however. The best I've come across are:
Sort by length then value.
SELECT
mixedColumn
FROM
tableName
ORDER BY
LENGTH(mixedColumn), mixedColumn;
For more examples see: http://www.copterlabs.com/blog/natural-sorting-in-mysql/
Use a secondary column to use as a sort key that would contain some sort of normalized data (i.e. only numbers or only letters).
CREATE TABLE tableName (mixedColumn varchar, sortColumn int);
INSERT INTO tableName VALUES ('1',1), ('2',2), ('10',3),
('a',4),('a1',5),('a2',6),('b1',7);
SELECT
mixedColumn
FROM
tableName
ORDER BY
sortColumn;
This could get difficult to maintain unless you can figure out a good way to handle the ordering.
Of course if you were able to go outside of the database you'd be able to use natural sort functions from various programming languages.

mysql pdo get range of rows

i have a table with about 100 rows , and i want every time to get rows between number and number , like this
if `i=1` i want to get the rows `0 1 2 3 4`
if `i=2` i want to get the rows `5 6 7 8 9`
if `i=3` i want to get the rows `10 11 12 13 14`
and maybe the last value of i will just take 3 or 4 rows not 5
i think the solution will be something like this
select * from question limit (i-1)*5 , i*5-1
but doesn't work , cos i don't know how to use variable in a query , and when i tried it for i=1 it doesn't work and i got a syntax error
The first parameter to LIMIT is the zero-based starting row index. The second one is the number of rows. So, if you're always looking for five rows:
SELECT * FROM question LIMIT (i-1)*5 , 5
(You'll have to calculate (i-1)*5 with whatever language you're using to build the query, and pass an actual number to MySQL).

MySQL ordering is lying to me

Right, this is a very odd issue that I'm wondering how i am going to explain it succinctly.
I have a WP plugin that records rows in a mysql table like so:
meta_id post_id meta_key meta_value
65387 605 _likes 9
Then on one of my pages I was running a query to select the most liked posts, ie. ORDER by meta_value DESC. Now i noticed on my site that whenever a post reached 10 it would not appear as top anymore and disappear from the query results. Odd.
I went to the database and (in PHPMyAdmin) ordered by meta_value and it did return 9 as the top results, none of the 10's appeared!?
One thing I thought it might be is the type of field (meta_value), these are the settings:
# Column Type Collation Attributes Null Default
4 meta_value longtext latin1_swedish_ci Yes NULL
Can anyone think of anything that might mean the ORDER BY is not working when the value is 10 or above!?
Thanks
If you can't change column datatype don't worry ... No need to do that
you need to just cast it's values in integers in ORDER BY clause.
user trick :
ORDER BY meta_value+0;
OR
ORDER BY CAST(meta_value as SIGNED);
Text fields don't order like number fields do. 9 is a higher value than 10 when descending (In text terms) as 10 starts with 1, and it's the 1 that it's working off, not the whole number, so 9 appears before 10.