MySQL – Data Type Conversion

Sometimes we need to convert the selected data into other content type. Here is an example.

Assume we got a table with a VARCHAR column which stores number only.

mysql> SELECT * FROM demo;
+----------+
| a_string |
+----------+
| 1        |
| 2        |
| 3        |
| 4        |
| 5        |
| 6        |
| 7        |
| 8        |
| 9        |
| 10       |
| 11       |
| 12       |
| 13       |
+----------+
13 rows in set (0.00 sec)


 

When we sort the data, we will get

mysql> SELECT * FROM demo ORDER BY a_string DESC;
+----------+
| a_string |
+----------+
| 9        |
| 8        |
| 7        |
| 6        |
| 5        |
| 4        |
| 3        |
| 2        |
| 13       |
| 12       |
| 11       |
| 10       |
| 1        |
+----------+
13 rows in set (0.00 sec)

 

This is probably not what we want. Let’s convert the data type from string to int before sorting.

mysql> SELECT * FROM demo ORDER BY CONVERT(a_string, SIGNED) DESC;
+----------+
| a_string |
+----------+
| 13       |
| 12       |
| 11       |
| 10       |
| 9        |
| 8        |
| 7        |
| 6        |
| 5        |
| 4        |
| 3        |
| 2        |
| 1        |
+----------+
13 rows in set (0.00 sec)

 

You can find more examples in the reference below.

Done =)

Reference: How to Use MySQL Conversion Functions – CONVERT, CAST, BINARY

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.