Order VARCHAR records with string and numbers in MySQL

MySQLMySQLi Database

For this, use ORDER BY clause. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> StudentCode varchar(20)
   -> );
Query OK, 0 rows affected (0.57 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('101J');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('100A');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('100B');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('101S');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('103M');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+-------------+
| StudentCode |
+-------------+
| 101J        |
| 100A        |
| 100B        |
| 101S        |
| 103M        |
+-------------+
5 rows in set (0.00 sec)

Following is the query to order VARCHAR records with string and numbers−

mysql> select * from DemoTable order by StudentCode+0,StudentCode;

This will produce the following output −

+-------------+
| StudentCode |
+-------------+
| 100A        |
| 100B        |
| 101J        |
| 101S        |
| 103M        |
+-------------+
5 rows in set, 5 warnings (0.00 sec)
raja
Published on 18-Dec-2019 09:38:15
Advertisements