membersound
membersound

Reputation: 86915

How to cast a string to numeric in mysql?

I have a table with string columns. Like varchar or text.

I want to select those values as a tinyint or int. But the following fails:

SELECT CAST(example AS INT) FROM mytable

Result:

1064 - 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 'INT) FROM mytable LIMIT 0, 25' at line 1

Why?

Upvotes: 1

Views: 5192

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271003

Try using signed or unsigned:

SELECT CAST(example AS SIGNED) FROM mytable

I find it very strange that MySQL does not support INT in this context (or lengths on strings).

Also, in MySQL, implicit conversion is often used:

SELECT (example + 0)

Upvotes: 2

Related Questions