SweetNGX
SweetNGX

Reputation: 163

MYSQL ORDER BY Number in string

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

Upvotes: 2

Views: 280

Answers (2)

Nhut Pham
Nhut Pham

Reputation: 185

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

Upvotes: 3

ProDec
ProDec

Reputation: 5410

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');

Upvotes: 4

Related Questions