MySQL: Query String to Int

by Darren Johannsen

MySQL stores data differently depending on what it is. For instance, a string of text characters is stored differently than an integer or a floating-point number. Sometimes you may need to convert data from a MySQL query from one data type to another. To help you do so, MySQL provides the CAST and CONVERT functions.

MySQL Data Types

MySQL stores data in several data types, such as CHAR and VARCHAR for storing strings of characters, INT for storing integer data and DATETIME for storing dates.

MySQL Data Type Casting

When you change data from one data type to another, this is called "casting." At times you may need to cast data to compare it to other data or to store it in another table or column.


CAST and CONVERT are two functions used to cast data types. Both generally fulfill the same purpose, although they each have a slightly different syntax. CAST syntax: CAST(value AS type) CONVERT syntax: CONVERT(value, type)

Casting Strings

It's common to take in user-supplied data as a string, and then cast it into a data type that's easier to manage before storing it in your database. For instance, if you have a string of numbers, you can cast the string as a signed integer before inserting the value as a row in a table. CAST example: INSERT INTO my_table (my_column) VALUES (CAST('123' AS INTEGER)) CONVERT example: INSERT INTO my_table (my_column) VALUES (CONVERT('123', INTEGER))

About the Author

Darren Johannsen has been writing computer-related articles since 2006. He has contributed to various websites, including the Slashdot blog. He holds a Bachelor of Science in computer science from the University of Idaho.

Photo Credits

  • photo_camera Jupiterimages/ Images