![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Is there a built-in function for week of the month in MySQL?
There is no standard function to get week of month in MySQL. You need to use the following syntax −
SELECT WEEK(yourDateColumnName, 5) - WEEK(DATE_SUB(yourDateColumnName, INTERVAL DAYOFMONTH(yourDateColumnName) - 1 DAY), 5) + 1 AS anyAliasName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table FirstWeekOfMonth -> ( -> Id int NOT NULL AUTO_INCREMENT primary key, -> yourdate date -> ); Query OK, 0 rows affected (2.50 sec)
Now you can insert some records in the table using INSERT command. The query is as follows −
mysql> insert into FirstWeekOfMonth(yourdate) values('2019-01-18'); Query OK, 1 row affected (0.20 sec) mysql> insert into FirstWeekOfMonth(yourdate) values('2019-04-19'); Query OK, 1 row affected (0.19 sec) mysql> insert into FirstWeekOfMonth(yourdate) values('2019-05-20'); Query OK, 1 row affected (0.10 sec) mysql> insert into FirstWeekOfMonth(yourdate) values('2019-12-31'); Query OK, 1 row affected (0.19 sec) mysql> insert into FirstWeekOfMonth(yourdate) values('2019-10-05'); Query OK, 1 row affected (0.12 sec) mysql> insert into FirstWeekOfMonth(yourdate) values('2019-08-25'); Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from FirstWeekOfMonth;
The following is the output −
+----+------------+ | Id | yourdate | +----+------------+ | 1 | 2019-01-18 | | 2 | 2019-04-19 | | 3 | 2019-05-20 | | 4 | 2019-12-31 | | 5 | 2019-10-05 | | 6 | 2019-08-25 | +----+------------+ 6 rows in set (0.00 sec)
Here is the query to get the week of the month −
mysql> SELECT WEEK(yourdate, 5) - -> WEEK(DATE_SUB(yourdate, INTERVAL DAYOFMONTH(yourdate) - 1 DAY), 5) + 1 as FirstWeekDemo from FirstWeekOfMonth;
The following is the output −
+---------------+ | FirstWeekDemo | +---------------+ | 3 | | 3 | | 4 | | 6 | | 1 | | 4 | +---------------+ 6 rows in set (0.00 sec)
Advertisements