How to sort time in AM/ PM in MySQL?

MySQLMySQLi Database

To sort time in AM/PM in MySQL, you can use ORDER BY STR_TO_DATE().

 Following is the syntax −

select yourColumnName from yourTableName ORDER BY STR_TO_DATE(yourColumnName , '%l:%i %p');

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserLogoutTime varchar(200)
);
Query OK, 0 rows affected (0.97 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable(UserLogoutTime) values('09:45 PM');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(UserLogoutTime) values('11:56 AM');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(UserLogoutTime) values('01:01 AM');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(UserLogoutTime) values('02:01 PM');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(UserLogoutTime) values('04:10 PM');
Query OK, 1 row affected (0.15 sec)

Display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output −

+----+----------------+
| Id | UserLogoutTime |
+----+----------------+
| 1  | 09:45 PM       |
| 2  | 11:56 AM       |
| 3  | 01:01 AM       |
| 4  | 02:01 PM       |
| 5  | 04:10 PM       |
+----+----------------+
5 rows in set (0.00 sec)

Here is the query to sort time In AM/ PM in MySQL −

mysql> select UserLogoutTime from DemoTable ORDER BY STR_TO_DATE(UserLogoutTime, '%l:%i %p');

This will produce the following output −

+----------------+
| UserLogoutTime |
+----------------+
| 01:01 AM       |
| 11:56 AM       |
| 02:01 PM       |
| 04:10 PM       |
| 09:45 PM       |
+----------------+
5 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 11:49:45
Advertisements