Skip to content
Advertisement

How to ORDER BY the amount of a given character in a string using SQL?

The column OTI in traits_general comprises of string values. What I am attempting to do here is to select, in descending order by the amount of zeros in each string, each OTI value. For example:

SELECT *
FROM traits_general
ORDER BY traits_general.OTI.amountOfZerosInString() DESC;

In this instance, if we had the strings, 03001, 22321, 00002, 30203, and 11102, then I would want for it to be ordered like such: 00002, 03001, 30203, 11102, 22321.

Is this possible to achieve? Thank you in advance!

Advertisement

Answer

One method to count the number of characters in a string is to replace the zeros with an empty string and compare the length of the original string and the one without the zeros:

order by length(oti) - length(replace(oti, '0', '')) desc
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement