Home >Database >Mysql Tutorial >How to Find the First Day of a Week Using its Week Number in MySQL?

How to Find the First Day of a Week Using its Week Number in MySQL?

Linda Hamilton
Linda HamiltonOriginal
2025-01-01 14:26:16817browse

How to Find the First Day of a Week Using its Week Number in MySQL?

Identifying the First Day of the Week Using Week Number in MySQL

Introduction

Database queries often require the efficient retrieval of specific dates. One common scenario is determining the first day of a particular week given its week number. This article explores how to achieve this using MySQL's powerful date manipulation functions.

MySQL Query

To obtain the first day of a given week, you can utilize the following MySQL query:

SELECT DATE_SUB(DATE_ADD(DATE('2022-07-18'), INTERVAL 1 - DAYOFWEEK(DATE('2022-07-18')) DAY), INTERVAL WEEKDAY(DATE('2022-07-18')) - 1 DAY) AS Start_Day;

In this query:

  • DATE('2022-07-18'): Represents the date you want to use as the reference for the week.
  • DAYOFWEEK(DATE('2022-07-18')) - 1: Calculates the difference between the day of the week (starting with Monday as 1) and 1. This gives you the number of days to subtract to get the first day of the week.
  • DATE_ADD(...): Adds the calculated days to the reference date to obtain the start of the week.
  • WEEKDAY(DATE('2022-07-18')) - 1: Determines the day of the week (starting with Monday as 1) for the reference date. Subtracting 1 from this value gives you the required offset to reach the start of the week.
  • DATE_SUB(...): Subtracts the calculated offset from the start of the week to get the first day of the week.

Sample Output

Using the provided sample date of '2022-07-18' (Tuesday), the query would return the following output:

Start_Day
----------
2022-07-18

This result confirms that the first day of the week for the given week number (29) is indeed Sunday, July 18, 2022.

The above is the detailed content of How to Find the First Day of a Week Using its Week Number in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn