How to convert varchar to integer in MySQL
By Tan Lee Published on Sep 19, 2024 324
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
-- mysql cast 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
.
Categories
Popular Posts
Horizon MUI Admin Dashboard Template
Nov 18, 2024
Elegent Material UI React Admin Dashboard Template
Nov 19, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024
Material Lite Admin Template
Nov 14, 2024