1

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
1
  • There needs to exist a column which describes which ID comes first or last. SQL tables themselves have no notion of "order." Commented Nov 23, 2020 at 2:41

2 Answers 2

1

The reason why order by cause this is because your IdSoalan is a alphanumeric data. You shouldn't use this type of data as typical ID but try this :

ORDER BY LENGTH(IdSoalan), IdSoalan

this should make your data order like this : S1 - S9 then S10 - S12 and go on. for descending form just put desc on both.

ORDER BY LENGTH(IdSoalan) DESC, IdSoalan DESC
5
  • use the same query you got and just change the order by clause.
    – T. Peter
    Commented Nov 23, 2020 at 2:55
  • i try to add DESC LIMIT 1 at the back of your code but still return S9
    – Sze Yu Sim
    Commented Nov 23, 2020 at 2:56
  • SELECT IdSoalan FROM SOALAN ORDER BY LENGTH(IdSoalan) DESC, IdSoalan DESC LIMIT 1
    – T. Peter
    Commented Nov 23, 2020 at 2:56
  • make sure you got both desc
    – T. Peter
    Commented Nov 23, 2020 at 2:57
  • @SzeYuSim kinda bruh for me cause this two answer is exactly same but glad OP solve it anyways.
    – T. Peter
    Commented Nov 23, 2020 at 3:03
0

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.