MySQL date format DD/MM/YYYY select query?

MySQLMySQLi Database

Format the date DD/MM/YYYY using select and order by in descending order. The syntax is as follows −

SELECT *FROM yourTableName
where yourDatetimeColumnName order by
STR_TO_DATE(yourDatetimeColumnName,’%d/%m%Y’) desc;

The above syntax will give the date in descending order. To understand the above syntax, let us first create a table. The query to create a table is as follows −

mysql> create table DateFormatWithSelect
   -> (
   -> UserId int,
   -> UserName varchar(100),
   -> UserLoginDatetime varchar(100)
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into DateFormatWithSelect values(101,'John','20/10/2016');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DateFormatWithSelect values(102,'David','21/09/2015');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DateFormatWithSelect values(103,'Carol','21/12/2018');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DateFormatWithSelect values(104,'Mike','2/8/2014');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DateFormatWithSelect values(105,'Sam','21/11/2017');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DateFormatWithSelect values(106,'Bob','21/12/2013');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select command. The query is as follows −

mysql> select *from DateFormatWithSelect;

The following is the outpu −

+--------+----------+-------------------+
| UserId | UserName | UserLoginDatetime |
+--------+----------+-------------------+
|    101 | John     | 20/10/2016        |
|    102 | David    | 21/09/2015        |
|    103 | Carol    | 21/12/2018        |
|    104 | Mike     | 2/8/2014          |
|    105 | Sam      | 21/11/2017        |
|    106 | Bob      | 21/12/2013        |
+--------+----------+-------------------+
6 rows in set (0.00 sec)

Here is the SELECT that formats the date in DD/MM/YYYY format −

mysql> select *from DateFormatWithSelect
   -> where UserLoginDatetime order by str_to_date(UserLoginDatetime,'%d/%m/%Y') desc;

Output

+--------+----------+-------------------+
| UserId | UserName | UserLoginDatetime |
+--------+----------+-------------------+
|    103 | Carol    | 21/12/2018        |
|    105 | Sam      | 21/11/2017        |
|    101 | John     | 20/10/2016        |
|    102 | David    | 21/09/2015        |
|    104 | Mike     | 2/8/2014          |
|    106 | Bob      | 21/12/2013        |
+--------+----------+-------------------+
6 rows in set, 6 warnings (0.00 sec)
raja
Published on 10-Jan-2019 11:09:12
Advertisements