Home > Enterprise >  MYSQL ORDER BY Number in string
MYSQL ORDER BY Number in string

Time:12-01

I have data in my table as follows. But I can't sort because the numbers are at the end of the string.

Only 4-digit year information is available at the end of users

I want to sort by the years at the end of the articles, is it possible?

Users column

USER-A-2021
USER-B-2018
USER-C-2019
USER-D-2017
USER-E-2020
USER-F-2016

CodePudding user response:

Something like this using RIGHT(str,len)

RIGHT - Returns the rightmost len characters from the string str, or NULL if any argument is NULL.

SELECT *
FROM data
ORDER BY RIGHT(info, 4)

CREATE TABLE data (
 info varchar(20)
);

INSERT INTO data VALUES
('USER-A-2021'),
('USER-B-2018'),
('USER-C-2019'),
('USER-D-2017'),
('USER-E-2020'),
('USER-F-2016');

CodePudding user response:

select *from Users order by right(UserId,4) asc;
  • Related