Is there any way to modify a column before it is ordered in MySQL? - mysql

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?

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).

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

Related

Expression in query treated as string

I am having a hell of a time trying to add two calculated fields in a query together. My first record has field1= 1, and field2= 5, and the field that is trying to add them as 15!
So it’s treating them as a string.
When I try to use the function of SUM() I get an error of some of the other fields not being used in expressions, which I don’t understand.
Subtracting the two fields works as does multiplication.
I am unable to change the format of either fields in the properties as the drop down menu is blank.
Please help!
Aggregate functions act on rows not fields. Sum(field1) adds the values of field1 for group of records. Use aggregate functions in an aggregate (GROUP BY) query.
Plus (+) character will concatenate text values but add numeric. Apparently, your two fields are providing text values. Either correct the field data type or use function to convert values to number. Convert at least one field and Access will perform arithmetic instead of concatenation on all terms of expression.
Val(field1) + field2
This assumes no fields are Null. Number conversion functions will error with Null. Also, arithmetic with Null returns Null. If Null is possibility, handle with Nz().
Val(Nz(field1,0)) + Nz(field2,0)

What is a preferred way to sort strings numerically in MySQL, using string's numeric component?

I have a column of strings like so:
ABC-10
ABC-20
ABC-40
...
ABC-130
ABC-410
I wish to sort them via number.
I know of two ways:
SELECT * from table
ORDER BY SUBSTRING_INDEX(model, '-', -1) + 0;
and
SELECT * from table
ORDER BY CAST(RIGHT(model, LENGTH(model) - 4) as unsigned);
Both appear to give the same results. Is one more preferred than another?
When the numeric string is short, it is preferred to use the first method. The cast will take a lot longer than ordering a 4 digit string
When the numeric string is long (it has to be very long), then the first method is preferred, because the cast won't take as long as ordering strings with so many caharcters. Numbers are very easy to order in comparison to strings

MYSQL - Short money values (example $2.50) column from low to high, where filed type = VARCHAR

i use phpmyadmin.
I have a table "Prices" with a column "price_usd". The column field type = VARCHAR, reason is that sometimes i add values like "Pending"
The question:
Is there any way, to ORDER BY FIELD price_usd DESC
and not have results like:
$10.55
$15.20
$55.00
$9.20
BUT:
$9.20
$10.55
$15.20
$55.00
*Might be a way to query the column AS DECIMAL? I mean just view it as DECIMAL and not actually change the field type.
Yes, you can convert the values to numbers, by getting rid of the leading dollar sign. In MySQL, you can do the conversion just by treating the result as a number. I often add zero:
order by replace(price, '$', '') + 0
Note that strings such as 'PENDING' will be converted to 0.
It's not a good practice. The info "Pending" should be done not in the database value, but in your application. Set your "price_usd" to allow NULL value. Then in your application, when you read this data, if price_usd is NULL, then you display it as "Pending".
That's how it should work best.
Hope this helps.

How to use alphanumeric fields with BETWEEN clause in Mysql?

I have a table that contain a field names as mgrs, the value that stored in mgrs fields is like '42SWC227821555' may contain more charachters, and may contain lower case letters. So now i want to search records between two mgrs, so how can i do that? can i convert mgrs value to integer first and then use in between clause?
Instead of BETWEEN clause use STRCMP(expr1, expr2) function for string comparison operations:
WHERE STRCMP(mgrs, '42SWC227821555') >= 0 AND STRCMP(mgrs, '42SWC227821570') <= 0
You can use string expressions with BETWEEN comparison.
SELECT '42SWC2278215551' BETWEEN '42SWC227821555' AND '42SWd227821555'
-> 1
I will list some steps, instead of complete answer.
Remove all alphabets from you value, means you can have 1 more customized column using function listed on this link
Apply your filter on this column.

Simple select issue with -(dash) in where clause

I need to search for a value like 1234-abc. The database doesn't have this particular value, but has another value 1234. Now the problem is when I write my query like
SELECT * FROM words WHERE tval='1234-abc'
instead of fetching an empty recordset, it fetches the 1234 value, it seems to ignore anything after the -, any idea what's going on?
http://sqlfiddle.com/#!2/9de62/3
You can use the BINARY keyword for the exact match
SELECT tval FROM words WHERE BINARY tval='1223-abc';
Binary is a built-in keyword that after your WHERE clause that forces a comparison for an exact case-sensitive match
Fiddle
The existing expression is implicitly converting the string expression to a number - you need to explicitly convert the number to a character strng, like so:
SELECT tval FROM words WHERE convert(tval,char(20))='1223-1ABCDE';
SQLFiddle here.