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

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)

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)

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)
Updated on: 2020-06-20T13:53:46+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements