Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast from VARCHAR to INT - MySQL

Tags:

sql

mysql

My Current Data for

SELECT PROD_CODE FROM `PRODUCT` 

is

PROD_CODE 2 5 7 8 22 10 9 11 

I have tried all the four queries and none work. (Ref)

SELECT CAST(PROD_CODE) AS INT FROM PRODUCT;  SELECT CAST(PROD_CODE AS INT) FROM PRODUCT;  SELECT CAST(PROD_CODE) AS INTEGER FROM PRODUCT;  SELECT CAST(PROD_CODE AS INTEGER) FROM PRODUCT; 

All throw syntax errors such as below:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AS INT FROM PRODUCT LIMIT 0, 30' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTEGER) FROM PRODUCT LIMIT 0, 30' at line 1

What is the right syntax to cast varchar to integer in MySQL?

MySQL Version: 5.5.16

like image 915
Lenin Raj Rajasekaran Avatar asked Aug 26 '12 01:08

Lenin Raj Rajasekaran


People also ask

Can a varchar be CAST to an int?

SQL Server's CAST() and CONVERT() methods can be used to convert VARCHAR to INT.

How do I CAST a string in MySQL?

MySQL CAST() FunctionThe CAST() function converts a value (of any type) into the specified datatype. Tip: See also the CONVERT() function.

Can you convert varchar to numeric in SQL?

To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.

What is varchar and int in MySQL?

Length bytes. A fixed-length field from 0 to 255 characters long. VARCHAR(Length) String length + 1 bytes. A fixed-length field from 0 to 255 characters long.


1 Answers

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT 
like image 114
eggyal Avatar answered Sep 30 '22 18:09

eggyal