Search code examples
mysqlsqldomselectxampp

How to use SQL code to select the latest ID that is not in order (Even though I have sort it)


So it is a picture that show my ID that is in order if we assume S2 is bigger S10. The order of my ID is S1, S10, S11, S12, S2, S3, S4, S5, S6, S7, S8, S9

I wrote my SQL code like this and the latest ID it return is S9 Just keep in mind that I want the alphabet beside the number. So which SQL code allow me to select the latest ID that is S12 ? PLS help me.

SELECT IdSoalan FROM SOALAN ORDER BY IdSoalan DESC LIMIT 1

Solution

  • Try this:

    SELECT IdSoalan FROM SOALAN ORDER BY LENGTH(IdSoalan) DESC, IdSoalan DESC LIMIT 1
    

    It sorts by length of the column in a descending order and then by the value in a descending order and limits the result to 1. It's called natural sorting in MySQL.