- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to select month and year from dates in MySQL?
To select month and year in MySQL, you can use MONTH() and YEAR() method. Let us first create a table −
mysql> create table DemoTable -> ( -> DueDate datetime -> ); Query OK, 0 rows affected (0.90 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2019-01-21'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('2019-06-15'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2018-12-01'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2015-04-01'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2016-08-14'); Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql− select *from DemoTable;
Output
This will produce the following output −
+---------------------+ | DueDate | +---------------------+ | 2019-01-21 00:00:00 | | 2019-06-15 00:00:00 | | 2018-12-01 00:00:00 | | 2015-04-01 00:00:00 | | 2016-08-14 00:00:00 | +---------------------+ 5 rows in set (0.00 sec)
Following is the query to select month and year from MySQL −
mysql> select MONTH(DueDate) AS MONTH, YEAR(DueDate) AS YEAR from DemoTable;
Output
This will produce the following output −
+-------+------+ | MONTH | YEAR | +-------+------+ | 1 | 2019 | | 6 | 2019 | | 12 | 2018 | | 4 | 2015 | | 8 | 2016 | +-------+------+ 5 rows in set (0.00 sec)
Advertisements