views:

20

answers:

2

I have a table with a field value which is a varchar(255). The contents of the field can be quite varied:

  • $1.20
  • $2994
  • $56 + tax (This one can be ignored or truncated to $56 if necessary)

I have a query constructed:

SELECT value FROM unnamed_table ORDER BY value

However, this of course uses ASCII string comparison to order the results and does not use any numerical type of comparison.

Is there a way to truly order by value without changing the field type to DECIMAL or something else? In other words, can the value field be modified ('$' removed, value converted to decimal) on the fly before the results are sorted?

+1  A: 

Create a second column without the $-sign, sort on that one and use the data of the original column in your application.

In order to create the helper column and sort on it you would need something like this:

SELECT value, CAST(SUBSTR(value, 2) AS UNSIGNED) sort_col
  FROM unnamed_table ORDER BY sort_col
Veger
Is there an easy way to keep them synchronized?
George Edison
You cannot create a column, name it and use it as a field for another column. But, you could create a (stored) function to calculate the value and use it for both columns, one without modifications to sort on and one with the $-sign concatenated in front of the value to use in the application. (It might be more convenient to just add the $-sign to the value *in* your application)
Veger
I'm beginning to think that switching to DECIMAL or INT (and dividing by 100) is the only option.
George Edison
OH... I thought you had some calculations before reaching the `values` but it is directly stored in this format in your database? If so you can remove the $-sign and cast to (un)signed: `CAST(SUBSTR(value, 2) AS UNSIGNED)` and sorting on that column works. (But I would advice to convert your field to INT indeed, much more efficient storage and possibilities for calculations and sorting are better/easier)
Veger
Ya. Just finished doing the conversion. Had to rewrite some of the PHP front-end but it wasn't too bad.
George Edison
+1  A: 

You could sort on an expression made to "parse" the text into decimal

SELECT value FROM unnamed_table ORDER BY expression_returning_decimal(value)

Where your expression uses MySQL functions to extract the number from the string depending on what form you expect it to take (something like CAST(value AS DECIMAL(10,2)), but you'll probably need to deal with the extraneous non-numeric characters somehow as I'm not sure what the CAST will give if you don't strip them).

fd
I just ended up converting to `int` because it was going to get quite ugly otherwise. But your answer is the closest to what I was looking for.
George Edison