Get beginning and end date from a specific year in MySQL

MySQLMySQLi Database

For this, use MySQL YEAR() function. Let us first create a table −

mysql> create table DemoTable1843
     (
     StartDate date,
     EndDate date
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1843 values('2019-01-21','2019-10-12');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1843 values('2018-10-12','2018-12-31');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1843 values('2016-04-01','2017-05-02');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1843;

This will produce the following output −

+------------+------------+
| StartDate  |    EndDate |
+------------+------------+
| 2019-01-21 | 2019-10-12 |
| 2018-10-12 | 2018-12-31 |
| 2016-04-01 | 2017-05-02 |
+------------+------------+
3 rows in set (0.00 sec)

Here is the query to get beginning and end dates from selected year −

mysql> select * from DemoTable1843
     where year(StartDate)='2018'
     or
     year(EndDate)='2018';

This will produce the following output −

+------------+------------+
| StartDate  |    EndDate |
+------------+------------+
| 2018-10-12 | 2018-12-31 |
+------------+------------+
1 row in set (0.00 sec)
raja
Published on 26-Dec-2019 10:41:02
Advertisements