1

Example:

If I have a database table named products and a column within named product_title

contents under product_title

zyx
cba
defabc

What I require?

`zyx` should be changed `xyz`
`cba` should be changed `abc`
`defabc` should be changed `abcdef`

All values in alphabetical order.

What I tried?

I tried searching for the requirement, but I couldn't find any solution for it. I just want to know "is this possible"?

if this is not possible, how can i sort my records with most matched substring?

19
  • Not sure I'm understanding. Are you wanting to update the data -- update table set field = 'xyz' where field = 'zyx'? Commented Mar 4, 2016 at 19:38
  • Try this function - Reverse() dev.mysql.com/doc/refman/5.7/en/string-functions.html Commented Mar 4, 2016 at 19:40
  • not exactly @sgeddes, can't we cast the field temporarily to sort in alphabetical order? Commented Mar 4, 2016 at 19:40
  • 1
    I believe the OP is asking if MySQL is able to sort the values string literal alphabetically after selection. @ameenulla0007 please confirm that is what you want. Commented Mar 4, 2016 at 19:40
  • 1
    Why do you need to sort the contents of the columns alphabetically? You wouldn't be storing more than one piece of data in a column, would you? Commented Mar 4, 2016 at 19:42

1 Answer 1

1

there is no build-in function to sort symbols in string in mysql.

anyway you can create your own stored procedure:

CREATE FUNCTION sv(
    x VARCHAR(255)
)
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
    declare r varchar(255);
    declare maxlen int;
    declare pos int;
    declare sym char(1);
    declare npos int;

    set r = "";

    set maxlen = length(x);
    set pos = 1;
    while (pos <= maxlen) do
        set sym = substr(x, pos, 1);

        set npos = 1;
        while ((npos <= length(r)) and (substr(r, npos, 1) < sym)) do
            set npos = npos + 1;
        end while;
        set r = concat(substr(r, 1, npos-1), sym, substr(r, npos));

        set pos = pos + 1;
    END while;

    return r;
END

fiddle

it works quite slow, to speed up process I suggest you to create new column product_title_sorted, run update products set product_title_sorted=sv(product_title) where product_title_sorted is null

and then use product_title_sorted in your queries

Sign up to request clarification or add additional context in comments.

3 Comments

This is great, but I would I like to know, is this performance oriented?
No, it is slow approach
Oh! But thanks for the response and help @lashane. Thank you.. :)

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.