How to convert varchar to integer in MySQL

By FoxLearn 9/19/2024 1:43:02 AM   2
In MySQL, you can convert values to integers using the CAST() or CONVERT() functions.

How to cast from VARCHAR to INT in MySQL?

Using CAST()

CAST(string_value AS SIGNED INTEGER)

For example:

SELECT CAST('1233' AS SIGNED INTEGER);

This query also returns 1233 as an integer.

If you have a column called price in a table products and you want to convert it to an integer

SELECT CAST(price AS UNSIGNED INTEGER) AS converted_price
FROM products;

Using CONVERT()

CONVERT(string_value, SIGNED INTEGER)

For example:

SELECT CONVERT('123456', SIGNED INTEGER);

This query also returns 123456 as an integer.

or

SELECT CONVERT(price, UNSIGNED INTEGER) AS converted_price
FROM products;

Use UNSIGNED if you expect only non-negative integers; use SIGNED if you expect both negative and positive integers.

If the value cannot be converted, MySQL will return 0 for non-numeric strings.