
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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)
- Related Questions & Answers
- Update a column value, replacing part of a string in MySQL?
- How to Sort object of objects by its key value JavaScript
- Replace part of string in MySQL table column?
- How to sort by value with MySQL ORDER BY?
- How to substring value in a MySQL table column?
- Add some value to an int type column value in a table without knowing its current value in SQL?
- Updating a MySQL table row column by appending a value from user defined variable?
- Setting similar value for a column in a MySQL table?
- How to SELECT min and max value from the part of a table in MySQL?
- Sort MongoDB Collection by Array value?
- Check if a value exists in a column in a MySQL table?
- Sort data column to retrieve max textual value in MySQL
- How to sort a Python dictionary by value?
- How to perform custom sort by field value in MySQL?
- Filter column value by the first character in MySQL
Advertisements