How can we use ORDER BY clause while calculating the Date?

MySQLMySQLi Database

It would be more convenient to find a record if we will use ORDER BY clause while calculating the date. To understand it, we have the data from table ‘Collegedetail’ as follows −

mysql> Select * from Collegedetail;
+------+---------+------------+
| ID   | Country | Estb       |
+------+---------+------------+
| 111  | INDIA   | 2010-05-01 |
| 130  | INDIA   | 1995-10-25 |
| 139  | USA     | 1994-09-25 |
| 1539 | UK      | 2001-07-23 |
| 1545 | Russia  | 2010-07-30 |
+------+---------+------------+
5 rows in set (0.00 sec)

Now, suppose if we want to calculate the number of years a college is old then it can be done as follows −

mysql> Select ID, estb, CURDATE(),((YEAR(CURDATE())-YEAR(estb))-(RIGHT(CURDATE(),5)<RIGHT(estb,5))) AS 'YEARS_OLD' from collegedetail;
+------+------------+------------+-----------+
| ID   | estb       | CURDATE()  | YEARS_OLD |
+------+------------+------------+-----------+
| 111  | 2010-05-01 | 2017-11-30 |         7 |
| 130  | 1995-10-25 | 2017-11-30 |        22 |
| 139  | 1994-09-25 | 2017-11-30 |        23 |
| 1539 | 2001-07-23 | 2017-11-30 |        16 |
| 1545 | 2010-07-30 | 2017-11-30 |         7 |
+------+------------+------------+-----------+
5 rows in set (0.00 sec)

Our search can be more convenient if we use ORDER BY clause as follows while calculating the number of years a college is old −

mysql> Select ID, estb, CURDATE(),((YEAR(CURDATE())-YEAR(estb))-(RIGHT(CURDATE(),5)<RIGHT(estb,5))) AS 'YEARS_OLD' from collegedetail ORDER BY YEARS_OLD;
+------+------------+------------+-----------+
| ID   | estb       | CURDATE()  | YEARS_OLD |
+------+------------+------------+-----------+
| 111  | 2010-05-01 | 2017-11-30 |         7 |
| 1545 | 2010-07-30 | 2017-11-30 |         7 |
| 1539 | 2001-07-23 | 2017-11-30 |        16 |
| 130  | 1995-10-25 | 2017-11-30 |        22 |
| 139  | 1994-09-25 | 2017-11-30 |        23 |
+------+------------+------------+-----------+
5 rows in set (0.01 sec)

The above result set shows that we can search the oldest college very easily by using ORER BY clause with ‘YEARS_OLD’. We can also use DESC keyword with ORDER BY clause which returns the oldest college in the top row as follows −

mysql> Select ID, estb, CURDATE(),((YEAR(CURDATE())-YEAR(estb))-(RIGHT(CURDATE(),5)<RIGHT(estb,5))) AS 'YEARS_OLD' from collegedetail ORDER BY YEARS_O
LD DESC;
+------+------------+------------+-----------+
| ID   | estb       | CURDATE()  | YEARS_OLD |
+------+------------+------------+-----------+
| 139  | 1994-09-25 | 2017-11-30 |        23 |
| 130  | 1995-10-25 | 2017-11-30 |        22 |
| 1539 | 2001-07-23 | 2017-11-30 |        16 |
| 111  | 2010-05-01 | 2017-11-30 |         7 |
| 1545 | 2010-07-30 | 2017-11-30 |         7 |
+------+------------+------------+-----------+
5 rows in set (0.00 sec)
raja
Published on 21-Feb-2018 11:24:09
Advertisements