A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.mysqltutorial.org/mysql-date-functions/mysql-week/ below:

MySQL WEEK() Function

Summary: in this tutorial, you will learn how to use the MySQL WEEK() function to get the week number for a date.

Introduction to MySQL WEEK() function

Typically, a year has 365 days for a normal year and 366 days for a leap year. A year is then divided into weeks with each week having exactly 7 days. So for a year we often has 365 / 7 = 52 weeks that range from 1 to 52.

The WEEK() function allows you to get the week number of a specific date:

WEEK(date, mode);Code language: SQL (Structured Query Language) (sql)

In this syntax:

The WEEK() function returns a week number based on ISO 8601:1988.

If you ignore the mode argument, the WEEK() function will use the value of the default_week_format system variable by default.

To get the current value of default_week_format variable, you use the SHOW VARIABLES statement as follows:

SHOW VARIABLES LIKE 'default_week_format';Code language: JavaScript (javascript)

Output:

+
| Variable_name       | Value |
+
| default_week_format | 0     |
+
1 row in set (0.01 sec)Code language: SQL (Structured Query Language) (sql)

The output shows that the default value of  default_week_format is 0.

The following table illustrates how the mode argument influences the WEEK function:

Mode First day of week Range Week 1 is the first week … 0 Sunday 0-53 with a Sunday in this year 1 Monday 0-53 with 4 or more days this year 2 Sunday 1-53 with a Sunday in this year 3 Monday 1-53 with 4 or more days this year 4 Sunday 0-53 with 4 or more days this year 5 Monday 0-53 with a Monday in this year 6 Sunday 1-53 with 4 or more days this year 7 Monday 1-53 with a Monday in this year

The ” with 4 or more days this year” in the above table means:

MySQL WEEK() function example

Let’s take some examples of using the WEEK() function.

1) Simple MySQL WEEK() function example

The following example uses the WEEK() function to get the week number of the date '2023-10-16':

SELECT WEEK('2023-10-16') as week_no;Code language: JavaScript (javascript)

Output:

+---------+
| week_no |
+---------+
|      42 |
+---------+
1 row in set (0.01 sec)Code language: JavaScript (javascript)
2) Using WEEK() function with table data

We’ll use the orders table in the sample database:

The following statement uses the WEEK() function to get the number of orders per week in 2003:

SELECT 
  WEEK(orderDate) week_no, 
  COUNT(*) 
FROM 
  orders 
WHERE 
  YEAR(orderDate) = 2003 
GROUP BY 
  WEEK(orderDate);Code language: SQL (Structured Query Language) (sql)

Output:

Summary

Was this tutorial helpful?


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4