Search code examples
mysqlnode-mysql

fetching an entry from an INT column as a string?


In my MySQL table I have a column id which stores some very large integers. I have a query in my Node.js code which fetches records from this table. Recently I've noticed that some of the INTs fetched are wrong. For example, if the id in MySQL is 10152687447723705 then Node.js interprets it as 10152687447723704. I've learned that this is due to floating point arithmetic, as Javascript gets shaky on precision with numbers this big.

So I need a way to convert this number to a string before it reaches Node, that is, in the MySQL query itself.

One other option is to convert the column to VARCHAR, but that would be a bad idea here, as it is a unique index column and there are lots of searches that utilize that.

I've come across some suggestions for using CONCAT but haven't been able to understand what the syntax should be in this case, and whether it applies at all.


Solution

  • To convert your column result from an int to a string, use CONVERT

    SELECT CONVERT(id,char) as id_str FROM my_table WHERE ...