Sling Academy
Home/MySQL/Extracting date/time parts in MySQL 8 with built-in functions

Extracting date/time parts in MySQL 8 with built-in functions

Last updated: January 26, 2024

Introduction

Working with date and time values is a common, yet intricate part of SQL query development. While handling date and time data seems simple at a glance, it quickly grows into a complex task as you engage in real-world applications. MySQL 8 has made significant advancements over its predecessors, providing an arsenal of built-in functions that can help you extract and manipulate date/time components effectively.

In this tutorial, we’ll journey through the functionalities available in MySQL 8, concentrating on various methods to extract the parts of a date/time value. Starting from the basics and moving to advanced examples, we will discuss how to utilize the robust date/time handling functions provided in MySQL 8.

Understanding Date/Time Datatypes

Before diving into the functions, it’s essential to understand the various date and time data types available in MySQL:

  • DATE: Stores a date value in YYYY-MM-DD format.
  • TIME: Stores time in HH:MM:SS format, or HH:MM:SS.ssssss with fractions of a second.
  • DATETIME: Combines date and time, stored as YYYY-MM-DD HH:MM:SS.
  • TIMESTAMP: Similar to the DATETIME type, but with timezone support and usually associated with a period relative to the Unix epoch (1970-01-01).
  • YEAR: Only for storing a year in a 2-digit or 4-digit format.

Extracting Date and Time Parts

MySQL provides a range of functions to extract specific parts from date/time values. Starting out with the basics:

Extract the Year, Month, and Day

To extract the year, month, and day from a DATE or DATETIME object, we use the YEAR(), MONTH(), and DAY() functions, respectively. Here’s how these functions can be used:

SELECT YEAR('2023-03-15') AS year;
-- Output: 2023

SELECT MONTH('2023-03-15') AS month;
-- Output: 3

SELECT DAY('2023-03-15') AS day;
-- Output: 15

Extracting Hour, Minute, and Second

To get the hour, minute, and second from a TIME or DATETIME, we can use HOUR(), MINUTE(), and SECOND() functions:

SELECT HOUR('2023-03-15 07:45:30') AS hour;
-- Output: 7

SELECT MINUTE('2023-03-15 07:45:30') AS minute;
-- Output: 45

SELECT SECOND('2023-03-15 07:45:30') AS second;
-- Output: 30

Advanced Date/Time Extraction

MySQL also allows for extracting more complex parts of a date such as the day of the week or the week of the year:

DAYOFWEEK, DAYOFYEAR, and WEEKOFYEAR

You can determine the day of the week (1=Sunday, 2=Monday, …, 7=Saturday) by using the DAYOFWEEK() function. Similarly, DAYOFYEAR() and WEEKOFYEAR() return a day’s ordinal number within the year and the week number, respectively:

SELECT DAYOFWEEK('2023-03-16'), DAYOFYEAR('2023-03-16'), WEEKOFYEAR('2023-03-16'); 
-- Output: 5, 75, 11

Extracting and Manipulating Time Stamps

The UNIX_TIMESTAMP() function is also especially utilitarian, converting the date or datetime expression to Unix time stamp, which is the number of seconds since ‘1970-01-01 00:00:00’ UTC.

SELECT UNIX_TIMESTAMP('2023-03-15 12:00:00');
-- Output: 1678876800

Frequently, you’ll want to format these date/time values for more readability or according to specific business logic. The DATE_FORMAT() function takes a date value and a format string. It returns the date as a string formatted according to the format string.

SELECT DATE_FORMAT('2023-03-15 07:45:30', '%W, %M %d %Y %T');
-- Output: Wednesday, March 15 2023 07:45:30

Conclusion

In conclusion, MySQL 8 simplifies date and time handling significantly with a wide array of functions that provide high precision and specificity. Whether it is extraction or formatting, the latest MySQL version makes it all intuitive and efficient, making your SQL queries both powerful and elegant.

Next Article: TIMESTAMPDIFF() in MySQL 8: Get the difference between two timestamps

Previous Article: UNIX_TIMESTAMP() and UTC_TIMESTAMP() in MySQL 8: Explained with examples

Series: MySQL Tutorials: From Basic to Advanced

MySQL

You May Also Like

  • MySQL: How to reset the AUTO_INCREMENT value of a table
  • MySQL: How to add a calculated column to SELECT query
  • MySQL: Eliminate orphan rows in one-to-many relationships
  • MySQL: Using R-Tree Indexes for Spatial Data Types
  • How to Create Custom Collations in MySQL
  • Using Hash Indexes in MySQL: A Practical Guide
  • Understanding Full-Text Indexes in MySQL
  • Partial Indexes in MySQL: A Practical Guide
  • MySQL: How to Remove FOREIGN KEY Constraints
  • Using ENUM in MySQL 8: A Practical Guide (with Examples)
  • MySQL: Creating a Fixed-Size Table by Using Triggers
  • One-to-Many Relationship in MySQL 8: A Practical Guide
  • Using Regular Expressions in MySQL 8: The Complete Guide
  • Using Loops in MySQL: A Practical Guide (with Examples)
  • How to Execute an SQL File in VS Code
  • Making use of the JSON_REMOVE() function in MySQL 8
  • MySQL 8: How to count rows in related tables
  • Replication in MySQL 8: A Comprehensive Guide
  • MySQL 8: FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE() functions – Explained with examples