Home >Database >Mysql Tutorial >How to Correctly Cast VARCHAR to INT in MySQL?

How to Correctly Cast VARCHAR to INT in MySQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-17 05:41:08637browse

How to Correctly Cast VARCHAR to INT in MySQL?

Correctly Converting VARCHAR to INT in MySQL

Encountering MySQL errors while converting VARCHAR to INT? This guide provides the proper syntax.

The CAST function is your solution for transforming VARCHAR data into integers. Here's the correct approach:

<code class="language-sql">SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT;</code>

MySQL offers a variety of data type conversion options within the CAST function. Suitable target types include:

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

For converting VARCHAR to an integer, UNSIGNED is the recommended type, guaranteeing a non-negative integer output.

To retrieve product codes as integers, use this query:

<code class="language-sql">
SELECT CAST(PROD_CODE AS UNSIGNED) AS INT_PROD_CODE FROM PRODUCT;
```  This assigns the alias `INT_PROD_CODE` to the resulting integer column.</code>

The above is the detailed content of How to Correctly Cast VARCHAR to INT in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn