Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HOW select min from cast varchar to int in mysql

Tags:

sql

mysql

How to convert varchar into double value in mysql

See, i have table column in varchar but it has only numbers. In that i want to select min max of the value.

Please check the below query, in which I'm getting a syntax error.

select 
    MAX(CAST(ch1 as INT)) as max_ch1,
    MIN(CAST(ch1 as INT)) as min_ch1 
from t9;

Please refer to below sqlfiddle

like image 436
G Jay Avatar asked Dec 16 '22 05:12

G Jay


2 Answers

I think this is what you are looking for:

SELECT
  MIN(CAST(CH1 AS SIGNED)),
  MAX(CAST(CH1 AS SIGNED))
FROM t9

Working SQLFiddle here.

You have to CAST the value as SIGNED, which corresponds to INTEGER in MySQL. More information about this, here.

like image 111
Radu Gheorghiu Avatar answered Jan 07 '23 08:01

Radu Gheorghiu


You can force an automatic numeric cast when using an operation like adding

select MAX(ch1+0) as max_ch1,
       MIN(ch1+0) as min_ch1 
from t9
like image 45
juergen d Avatar answered Jan 07 '23 08:01

juergen d