MySQL Order by beginning letter?

MySQLMySQLi Database

To order by the first letter, use ORDER BY CASE statement. Let us first create a table −

mysql> create table DemoTable1535
   -> (
   -> Value varchar(100)
   -> );
Query OK, 0 rows affected (2.26 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1535 values('MySQL is good relational database.');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1535 values('is MySQL easy to lean');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable1535 values('You need to start basic SQL');
Query OK, 1 row affected (0.35 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1535;

This will produce the following output −

+------------------------------------+
| Value                              |
+------------------------------------+
| MySQL is good relational database. |
| is MySQL easy to lean              |
| You need to start basic SQL        |
+------------------------------------+
3 rows in set (0.00 sec)

Following is the query to order by the first letter −

mysql> select * from DemoTable1535
    -> order by case when left(Value, 1) = 'i' then 1 else 2 end,Value;

This will produce the following output −

+------------------------------------+
| Value                              |
+------------------------------------+
| is MySQL easy to lean              |
| MySQL is good relational database. |
| You need to start basic SQL        |
+------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 05:41:31
Advertisements