Languages
[Edit]
EN

MySQL - compare datetime values

0 points
Created by:
Dirask Community
6900

In this article, we would like to show you how to compare datetime values in MySQL.

Quick solution:

SELECT *
FROM `table_name`
WHERE `datetime_column_name` <= 'yyyy-mm-dd';

Note:

You can replace theĀ <=Ā operator with any other comparison operator.

Practical example

To show how to compare datetime values, we will use the following table:

MySQL - example data used to compare date values
MySQL - example data used to compare datetime values

Note:

At the end of this article you can find database preparation SQL queries.

Example 1

In this example, we will display all the datetimesĀ beforeĀ 2000-01-04.

Query:

SELECT *  
FROM `dates` 
WHERE `date` < '2000-01-04';

Output:

MySQL - compare datetime values - result
MySQL - compare datetime values - result

Example 2

In this example, we will select all the datetimesĀ from 2000-01-04 inclusive and display them without timeĀ using DATE() function (yyyy-mm-ddĀ format only).

Query:

SELECT DATE(`date`)
FROM `dates`
WHERE `date` <= '2000-01-04';

Output:

MySQL - compare datetime values, display without time - result
MySQL - compare datetime values, display without time - result

Database preparation

create_tables.sqlĀ file:

create TABLE `dates`(
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`date` DATETIME,
	PRIMARY KEY (`id`)
);

insert_data.sqlĀ file:

insert into `dates`
	(`date`) 
VALUES 
	('2000-01-01'),
	('2000-01-02'),
	('2000-01-03'),
	('2000-01-04'),
	('2000-01-05'),
	('2000-01-06');

MySQL - dates

Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join