How to convert varchar to integer in MySQL
By FoxLearn 2/10/2025 7:20:35 AM 235
In MySQL, you can convert values to integers using the CAST() or CONVERT() functions.
How to cast from VARCHAR to INT in MySQL?
For example, how to convert a VARCHAR
to an INT
using the CAST()
or CONVERT()
functions.
1. Using CAST()
CAST(string_value AS SIGNED INTEGER)
For example, mysql varchar to int
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;
2. Using CONVERT()
CONVERT(string_value, SIGNED INTEGER)
For example, mysql string to int
// mysql varchar to int 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 VARCHAR
contains non-numeric values, the result will be 0
.