Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know CAST failed in MySQL

Tags:

casting

mysql

Could somebody tell me how I can detect if a cast failed in MySQL using CAST() function?

These two lines return the same value: 0.

SELECT CAST('Banana' AS UNSIGNED INTEGER) AS 'CAST1';
SELECT CAST('0' AS UNSIGNED INTEGER) AS 'CAST2';
like image 487
Raphael Avatar asked Sep 30 '22 06:09

Raphael


1 Answers

You can use regular expressions to validate the data before the conversion:

select (case when val regexp '^[0-9]+$' then cast(val as unsigned integer) end)
like image 136
Gordon Linoff Avatar answered Oct 02 '22 15:10

Gordon Linoff