Order VARCHAR records with string and numbers in MySQL



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)
Updated on: 2020-02-26T05:52:01+05:30

548 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements