0

What would be the best way to return an integer value as a string in MySQL? For example:

>select id from table;
>1

but return it as string rather than integer? There are references to cast as causing major headaches with different values even for integer to string conversion.

5
  • 1
    What would be unsafe? Commented Aug 24, 2014 at 16:27
  • I see online that a lot of people don't reccomend using cast() as it has unexpected results. Perhaps in such a trivial one as this is fine. Commented Aug 24, 2014 at 16:29
  • Can you show me an example? I don't see why CAST(id) is unsafe. You can also use CONCAT(id), but there's really no difference. Commented Aug 24, 2014 at 16:33
  • Please reference such problems. That would be a severe bug indeed. I've never encountered any problem with cast so far. Commented Aug 24, 2014 at 16:37
  • ok, probably not a problem then. I'll just use concat Commented Aug 24, 2014 at 16:38

2 Answers 2

1

The normal way is to use cast(). Do you have an issue with that?

select cast(id as varchar(255))
from table;

If there are issues with cast() with integers, I am not familiar with them, as long as the destination type is long enough to hold the value. You can always use format() instead.

Perhaps you are thinking of issues when converting floating point numbers to a string. Then you have a problem that 1.1 might end up looking like 1.09999999997 or whatever. That is an issue with inexact floating point representations, not integers.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't cast to VARCHAR but only to CHAR so try this :

select cast(id as char(10))
from table;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.