0

I have a field like this

    table A {text varchar(255) }

with entries like this

    text => A$123.34
    text => A$10.34
    text => $15.45

I want to sort those so they list as

    A$10.34
    $15.45
    A$123.34

I've tried many solutions posted here - cast to decimal, value * 1, value + 0, etc. but they all fail. I did find one that comes very close:

    select text as num from Table A order by substring(num,2) desc 

This gives

    A$10.34
    A$123.34
    $15.45

I know it is because the substring is looking past two characters and the last entry only has one but I can't see how to fix that. Does anyone know how to get this to sort as I want?

In most of the posts I've seen it said to just store the value as a number. That is not possible due to the amount of changes it would require in the project.

4
  • ORDER BY 0 + substring(num, 2) Commented Sep 30, 2021 at 16:09
  • I would save the A$ (or any other type of prefix) in another column, then sort by this new column+amount and then concatenate both for output Commented Sep 30, 2021 at 16:10
  • Thanks for the suggestion but, as mentioned, that is not an option. Commented Sep 30, 2021 at 16:29
  • I tried adding the 0 + suggestion but it makes the list less sorted. I do appreciate the suggestion. Commented Sep 30, 2021 at 17:31

1 Answer 1

2

Use SUBSTRING_INDEX():

mysql> select * from A order by 0 + substring_index(text, '$', -1);
+----------+
| text     |
+----------+
| A$10.34  |
| $15.45   |
| A$123.34 |
+----------+
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Bill. That mostly did it. There is one entry for $1,205.54 and that ends up either as the first result (ASC) or the last (DESC). Is there a simple fix for that? If not, it is fine as it is since I doubt there will be many entries over 999.
Maybe strip out the commas: substring_index(replace(text, ',', ''), '$', -1)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.