Last active
July 23, 2023 07:28
-
-
Save crshmk/f8c98199b29ef515f0a94df518828671 to your computer and use it in GitHub Desktop.
mysql DATE_SUB() (date subtract)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT CURRENT_TIMESTAMP; | |
+---------------------+ | |
| current_timestamp | | |
+---------------------+ | |
| 2023-07-23 13:28:42 | | |
+---------------------+ | |
# subtract 10 minutes from current timestamp | |
SELECT DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 10 MINUTE); | |
+-------------------------------------------------+ | |
| DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 10 MINUTE) | | |
+-------------------------------------------------+ | |
| 2023-07-23 13:20:17 | | |
+-------------------------------------------------+ | |
# determine if one timestamp occurred at least ten minutes prior to another timestamp | |
SELECT "2023-01-01 09:00:00" > DATE_SUB("2023-01-01 09:09:00", INTERVAL 10 MINUTE); | |
+-----------------------------------------------------------------------------+ | |
| "2023-01-01 09:00:00" > DATE_SUB("2023-01-01 09:09:00", INTERVAL 10 MINUTE) | | |
+-----------------------------------------------------------------------------+ | |
| 1 | | |
+-----------------------------------------------------------------------------+ | |
SELECT "2023-01-01 09:00:00" > DATE_SUB("2023-01-01 09:19:00", INTERVAL 10 MINUTE); | |
+-----------------------------------------------------------------------------+ | |
| "2023-01-01 09:00:00" > DATE_SUB("2023-01-01 09:19:00", INTERVAL 10 MINUTE) | | |
+-----------------------------------------------------------------------------+ | |
| 0 | | |
+-----------------------------------------------------------------------------+ | |
# created - TIMESTAMP or DATETIME type | |
# select things created withing 30 days of a timestamp | |
SELECT * FROM things WHERE created > DATE_SUB("2023-07-23 13:28:42", INTERVAL | |
30 DAY); | |
# select all things created within the last month | |
CREATE TABLE `things` ( | |
`created` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP | |
); | |
SELECT * FROM things WHERE created > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment