- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a MySQL table column value by part of its value?
You can use ORDER BY RIGHT() for this. Let us first create a table −
mysql> create table DemoTable ( UserId varchar(100) ); Query OK, 0 rows affected (0.33 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('User1234'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable values('User9874'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable values('User9994'); Query OK, 1 row affected (0.04 sec) mysql> insert into DemoTable values('User1211'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('User1012'); Query OK, 1 row affected (0.79 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output -
+----------+ | UserId | +----------+ | User1234 | | User9874 | | User9994 | | User1211 | | User1012 | +----------+ 5 rows in set (0.00 sec)
Case 1 − If you want the result in ascending order.
Following is the query to sort a MySQL table column value by part of its value.
mysql> select *from DemoTable ORDER BY RIGHT(UserId, 4);
This will produce the following output −
+----------+ | UserId | +----------+ | User1012 | | User1211 | | User1234 | | User9874 | | User9994 | +----------+ 5 rows in set (0.00 sec)
Case 2 − If you want the result in descending order.
Following is the query to sort a MySQL table column value by part of its value -
mysql> select *from DemoTable ORDER BY RIGHT(UserId, 4) DESC;
This will produce the following output −
+----------+ | UserId | +----------+ | User9994 | | User9874 | | User1234 | | User1211 | | User1012 | +----------+ 5 rows in set (0.00 sec)
Advertisements