1

I have this column in a talbe which for historical reason is a string but nowdays new values are put in are numbers.

I have to find the biggest value from an interval of numbers but the values are string in the DB :(

If op_calcul would have been a number it would have been trivial sql:

Select MAX(op_calcul) FROM nom_prod where op_calcul  >=500 and op_calcul < 5000

but having them as varchar put me into some trouble.

Tried different scenarios but did not come with a solution yet.

Any hint ?

Thanks

3 Answers 3

1
SELECT MAX(CAST(op_calcul as SIGNED)) FROM nom_prod...

Should do the trick. You might need to cast the WHERE clauses as well.

Ideally though, for performance reasons on both the MAX and the WHERE, you should use an integer column. Is there non-numeric or out of range data in it or something? It should be fairly trivial to change the column type if not.

Sign up to request clarification or add additional context in comments.

4 Comments

the column has historical data as varchar like "code 12ac" etc
Ah... In that case, you know those rows might not be casted correctly, right? Anything that's not a correctly formed integer will likely be cast to 0. Edit: Was that edit really necessary? Seems kind of superfluous.
yes but in the range of op_calcul >=500 and op_calcul < 5000 there is no conflictual data...harcoded stuff but is a must
The comparison with integers does an implicit cast, though I suppose it will not cause any problems.
1

use mysql cast to convert data into required datatypes.

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast

Note however that it does affect query performance.

Comments

1
SELECT MAX(CAST(`op_calcul` AS SIGNED))
FROM `nom_prod`
WHERE `op_calcul`  >= 500
AND `op_calcul` < 5000;

1 Comment

Mostly opinion, but backticks should typically not be used unless reserved words are being used as entity names (which shouldn't be done). They kill SQL portability (though there really is very little to begin with) and offer no advantage.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.