How to Find Records of the Week in MySQL?

In general, when we are going to show statistics, it may be necessary to show things like weekly sales or weekly income/expenses. In this case, it is necessary to find the weekly records first. For this, we use the YEARWEEK() function in mysql. It allows us to find the week of this year, its usage is as follows;

SELECT YEARWEEK('2022-09-20')

If we want to get based on the current date, we can use it with the CURDATE() function. For example;

SELECT YEARWEEK(CURDATE())

So, that means we can find the records for the week like this.

SELECT * FROM table_name
WHERE YEARWEEK(table_name.date_column) = YEARWEEK(CURDATE())

In this example, we got the weekly data based on the week of whatever the current date is. However, we could set a date instead of CURDATE() and get records that match its week.

Now we have only one problem, this way the weekly slices are from Sunday to Sunday. We need to set the beginning of this to Monday because our week start is Monday :) Then it is enough to change our codes like this.

SELECT * FROM table_name
WHERE YEARWEEK(table_name.date_column, 1) = YEARWEEK(CURDATE(), 1)
Comments

There are no comments, make the firs comment