Datepart function alternative in MySQL
The SQL datepart
function extracts a part of the datetime data type and is used to filter or aggregate table fields in SQL databases. However, it is not directly available in MySQL.
Datepart
Function alternatives in MySQL
datepart
There are two ways to achieve similar results in MySQL .
- Usage
Extract(datetime-part FROM datetime)
method. - Usage
datetime-part(datetime)
method.
Recall that the datetime data type is a combination/concatenation of the typical date and time data types available in MySQL. Dates and times usually have their own formats: YYYY-MM-DD
and HH:MM:SS.XXXXXX
.
Therefore, the datetime data type has YYYY-MM-DD HH:MM:SS.XXXXXX
the format , where .XXXXXX
represents the 6-digit fractional seconds precision (fps) available in MySQL.
Now, let's create a simple registration_system
database to implement two datetime extraction methods.
-- Initializing
CREATE DATABASE registration_system;
USE registration_system;
-- CREATING TABLES
CREATE TABLE registered_users (
id INT AUTO_INCREMENT UNIQUE,
username VARCHAR (255) NOT NULL,
email VARCHAR(255),
registered_on DATETIME(6), -- YYYY-MM-DD HH:MM:SS.XXXXXX
PRIMARY KEY(id)
);
Output:
1 row(s) affected
-----------------------------------------------------------------------------------------
0 row(s) affected
-----------------------------------------------------------------------------------------
0 row(s) affected
We can simulate a set of registered users by inserting values into the table we created.
-- POPULATING THE TABLE WITH SAMPLE REGISTRATION DATA: 3 users
INSERT INTO registered_users(username, email, registered_on) Values
('Clint Rotterdam', 'clint_rotterdam@trialmail.com','2022-01-03 09:25:23.230872'),
('David Maxim', 'maxim_david@testmail.com','2022-01-05 10:30:24.046721'),
('Vin Petrol', 'vin_not_diesel@crudemail.com','2022-01-30 14:05:03.332891');
Output:
3 row(s) affected Records: 3 Duplicates: 0 Warnings: 0
This is the view created on the users table.
SELECT * FROM registered_users; -- Checking the table
Output:
id username email registered_on
1 Clint Rotterdam clint_rotterdam@trialmail.com 2022-01-03 09:25:23.230872
2 David Maxim maxim_david@testmail.com 2022-01-05 10:30:24.046721
3 Vin Petrol vin_not_diesel@crudemail.com 2022-01-30 14:05:03.332891
-----------------------------------------------------------------------------------------
3 row(s) returned
Use the MySQL Extract(datetime-part FROM datetime)
method to extract part of the date and time
SELECT
This method is combined with the ubiquitous statement.
datetime-part
The argument can be any of the following datetimeparts: MONTH
, MICROSECOND
, SECOND
, MINUTE
, HOUR
, DAY
, WEEK
, MONTH
, QUARTER
, YEAR
, SECOND_MICROSECOND
, MINUTE_MICROSECOND
, MINUTE_SECOND
, HOUR_MICROSECOND
, HOUR_SECOND
, HOUR_MINUTE
, DAY_MICROSECOND
, DAY_SECOND
, DAY_MINUTE
, DAY_HOUR
, YEAR_MONTH
.
Here is the official documentation for these options for additional reference.
Let's take an example. We will fetch the details of users who registered before 30th January from the database.
SELECT id AS 'USER_ID', username AS 'NAME', EXTRACT(DAY FROM registered_on) AS 'Day Registered'
FROM registered_users
WHERE EXTRACT(DAY FROM registered_on) < 30;
Output:
USER_ID NAME Day Registered
1 Clint Rotterdam 3
2 David Maxim 5
-----------------------------------------------------------------------------------------
2 row(s) returned
This output tells you two things: Extract
the function changes the output view and filters the results.
Many applications can then use this by writing very advanced queries that manipulate datetimes. For additional reference on this feature, check out the official documentation.
Use the MySQL datetime-part(datetime)
method to extract part of the date and time
This method is similar to the previous one, but has fewer parameters. In addition, combined with SELECT
the statement, this method can filter columns based on the required datetime part.
Likewise, let's get the users who registered before January 30th.
SELECT id AS 'USER_ID', username AS 'NAME', DAY(registered_on) AS 'Day Registered'
FROM registered_users
WHERE DAY(registered_on) < 30;
Output:
USER_ID NAME Day Registered
1 Clint Rotterdam 3
2 David Maxim 5
-----------------------------------------------------------------------------------------
2 row(s) returned
This result can be further improved by using Date
filters, as shown in the following example.
SELECT id AS 'USER_ID', username AS 'NAME', DATE(registered_on) AS 'Date Registered' FROM registered_users
WHERE DAY(registered_on) < 30;
Output:
USER_ID NAME Date Registered
1 Clint Rotterdam 2022-01-03
2 David Maxim 2022-01-05
-----------------------------------------------------------------------------------------
2 row(s) returned
Either method provides the same result. However, Extract
methods can more clearly describe the actions performed.
This approach is preferred for code readability and debugging.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Changing max_allowed_packet Size in MySQL Server
Publish Date:2025/04/22 Views:192 Category:MySQL
-
This article explains how to change the max_allowed_packet size in MySQL server. To understand this, we will use two operating systems, Windows 10 and Linux (Ubuntu). Changing max_allowed_packet Size in MySQL Server If we try to upload a fi
Zerofill usage, advantages and alternatives in MySQL
Publish Date:2025/04/22 Views:195 Category:MySQL
-
In this article we will understand the uses, advantages and alternatives of ZEROFILL attribute in MySQL. Use and benefits of the ZEROFILL attribute in MySQL The benefit of using the ZEROFILL attribute is that it has nothing to do with input
Compare only MySQL timestamp dates to date parameters
Publish Date:2025/04/22 Views:64 Category:MySQL
-
In this article we will use the DATE() , CAST() , and CONVERT() functions to compare MySQL timestamp dates with only the date parameter. DATE() vs. CAST() vs. CONVERT() in MySQL Below is a brief description of each function. You can also fi
Calculating Percentages in MySQL
Publish Date:2025/04/22 Views:66 Category:MySQL
-
We will use one or more columns to calculate percentages in MySQL. There are different ways to do this, and for each method we will use an example table. Calculate percentage using a column in MySQL We have a table called sales where ID, Re
Selecting multiple values using WHERE in MySQL
Publish Date:2025/04/22 Views:185 Category:MySQL
-
This article is about using MySQL query to get data from a specific table or relation that satisfies a specific condition. To do this, the WHERE clause is used in the SQL query. WHERE clause in SQL query WHERE The clause specifies the condi
Changing the connection timeout in MySQL
Publish Date:2025/04/22 Views:59 Category:MySQL
-
We are learning how to change the connection timeout in MySQL using Linux (Ubuntu 20.04) and Windows operating systems. Changing the connection timeout in MySQL Sometimes you keep losing connection to the MySQL server because the connect_ti
MySQL fix Data Is Truncated for a Column error
Publish Date:2025/04/22 Views:101 Category:MySQL
-
This article describes possible causes and solutions for the MySQL error Data is truncated for a column . Fix data truncated due to column error in MySQL Here, we will discuss the possible causes and solutions to eliminate MySQL data trunca
MySQL Error Server PID File Could Not Be Found Solution
Publish Date:2025/04/22 Views:192 Category:MySQL
-
In this article, we will study about the Error! Error Server PID File Could Not Be Found! in MySQL and its solution with full explanation. MySQL PID file The file that contains the process identification number or process ID of a running My
Get the last inserted ID using PHP MySQLi function
Publish Date:2025/04/22 Views:99 Category:MySQL
-
This article briefly introduces the PHP mysqli() function and demonstrates how to use it to get the last inserted ID from a MySQL database. PHP mysqli() Function It is an extended version of the MySQL driver called mysqli and is typically u