"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort String Numbers in MySQL?

How to Sort String Numbers in MySQL?

Published on 2024-11-26
Browse:551

How to Sort String Numbers in MySQL?

Sorting String Numbers in MySQL

Question:

How can I sort a column of type VARCHAR that stores numeric values as strings in MySQL? For example, I have a column containing "17.95", "199.95", and "139.95" and need to sort them as numbers.

Answer:

The most efficient and straightforward method to achieve this is by using multiplication by 1:

SELECT *
FROM tbl
ORDER BY number_as_char * 1

This method has several advantages:

  • It avoids potential precision issues caused by casting.
  • It can handle non-numeric data gracefully, ignoring it during sorting.
  • It extracts the numeric part from alphanumeric strings, allowing for accurate sorting.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3