Mysql date interval - mysql

I am trying to select rows which are within a certain time period:
$sql = mysql_query(" SELECT * FROM table WHERE ... AND
date BETWEEN ('$date' - Interval 2 YEAR) AND ('$date' + Interval 2 YEAR)
OR date ISNULL");
The format of the dates saved in this column are mm/dd/yyyy
a. how do I select the time interval? currently it is selecting all the rows, not just those within this date range.
b. Am I using the corret syntax to make sure we include all null options as well?
Update.
Following the answers and comments I changed the column type to "Date" (it was varchar), and have also changed the current type of the existing entries to the correct date format.
I now have 2 questions:
a. This is still not working... What else might be the problem?
b. I want to change in PHP where the entry is saved. How ahould I go about this? Is the following correct:
$new_date = mysql_query("STR_TO_DATE($old_date_string,'%m/%d/%Y')");
Solution.
First, I changed the column type to DATE (from VARCHAR).
Second, I moved and converted all the existing entries from their existing column and type (str) to new type (date) and new column.
Third, I added parentheses to the "date" section.
Fourth, I changed ISNULL to IS NULL - addin a space, which changes it from a function to a statement.
Fifth, I am now updating my script so that in the future dates will be saved to the new column in the new type, converting them to the correct fprmat before saving them to the database.
Thankyou #nnicholas and everybody.

If you are really storing your dates as strings I suggest you update your table with something like the following -
-- add a new column of type DATE
ALTER TABLE `table` ADD COLUMN `date_new` DATE AFTER `date`;
-- populate the new column from the old one
UPDATE `table` SET `date_new` = STR_TO_DATE(`date`,'%m/%d/%Y');
-- drop the old column
ALTER TABLE `table` DROP COLUMN `date`;
-- rename the new column
ALTER TABLE `table` CHANGE `date_new` `date` DATE;
After making these changes handling dates will be much easier for you. When inserting the dates that you are receiving you simply use STR_TO_DATE('new_value','%m/%d/%Y') to convert the date during the insert -
mysql_query("INSERT INTO `table` (field1, field2, `date`)
VALUES('value1', 'value2', STR_TO_DATE('$old_date_string','%m/%d/%Y')");
This assumes that $old_date_string has already been sanitised.
With your table structure updated the standard date arithmetic functions will work as intended.
$sql = mysql_query("SELECT *
FROM table
WHERE ...
AND (`date` BETWEEN ('$date' - INTERVAL 2 YEAR) AND ('$date' + INTERVAL 2 YEAR) OR `date` IS NULL)");
$date must be in Y-m-d format.

You can't do date comparisons on it if it's not stored in the database as a date.
You could do something very ugly casting it to a date with STR_TO_DATE() and then comparing but I'd suggest reworking your table structure to store this date as a DATE object.
SELECT * FROM table WHERE ... AND
STR_TO_DATE(date, '%m/%d/%Y') BETWEEN ('$date' - Interval 2 YEAR) AND ('$date' + Interval 2 YEAR)
OR date ISNULL
This assumes that $date is in the correct MySQL DATE format of 2012-03-14 (for 14th March 2012)

You have to CAST/CONVERT your date field that you are getting from MySQL (you really called a date field 'date'? that's a bad idea).
The best answer is to convert your date column to an actual DATE type. You should also not really use the mm/dd/yyyy format as its ambiguous.

You need to enclose the entire date checking part in brackets, like so:
$sql = mysql_query(" SELECT * FROM table WHERE ... AND
(
date BETWEEN ('$date' - Interval 2 YEAR) AND ('$date' + Interval 2 YEAR)
OR date ISNULL
)");
And it should work as expected.
Apart from the missing brackets, your condition seems to take into account NULLs all right (i.e. NULLs would be included in the output regardless of the argument passed).
UPDATE
It seems I was mistaken in presuming that the date column was the date type. #James C has got the point, as well as #nnichols, and their suggestion about changing the column type seems the way to go in your situation.

Related

How do I update MySQL table to alter my date format from Excel numeric to standard?

I used a script to insert some CSV data into my MySQL schema. The table contains about 26k records, but the dates are all in Excel numeric form-- e.g., 44890 instead of 11/25/22.
The script to update the date fields is this:
DATE('1899-12-30') + INTERVAL c.Start_Date DAY AS Start_Date_c, -- converts Excel numeric date to date
DATE('1899-12-30') + INTERVAL c.End_Date DAY AS End_Date_c, -- converts Excel numeric date to date
But I don't know how to incorporate this outside of a SELECT statement. I want to update the table directly in the schema, if possible.
I imagine I would do something like this:
UPDATE my_table
SET
Start_Date = DATE('1899-12-30') + INTERVAL Start_Date DAY,
End_Date = DATE('1899-12-30') + INTERVAL End_Date DAY
But I'm not quite sure and don't want to risk running this and messing something up (is there a way to do a test?)... I use DataGrip if that matters.

How to cast this integer value to date in MySQL

i have airbnb data and i want to cast column last_reviews (which datatype is int) to date
this is my sql code http://sqlfiddle.com/#!9/b5ea42/31
how do i cast int > date?
or how do i create last_reviews column as datatype date?
The last_review date seems to be the number of days since 1900-01-01 so in MySQL you would:
SELECT '1900-01-01' + INTERVAL last_review DAY AS last_review_date
FROM ...
The result checks out for the sample data (which you should delete).
last_review values looks like VB(A) numeric representation for dates. If so then test this:
SELECT last_review, '1900-01-01' + INTERVAL last_review DAY
FROM airbnb
Adjust constant part (maybe it must be '1899-12-31'?) if needed.

How to delete string date older then 2020/11 month in MySQL?

I have a database, with around 500k rows, I don't know why but instead of using "Date" type on the column it uses "varchar". Now the date has a format - 01/02/2021 07:08:49 AM
My question is how should an SQL query look to delete this kind of "old" date rows from the table? Or in another hand how should I convert the column without losing the data and holding the same format to a Date type column?
I tried deleting with something like this:
DELETE FROM `visited` WHERE LEFT(`last_visit_date`, 2) != '01' OR LEFT(`last_visit_date`, 2) != '12';
However, this didn't fully clean the table.
Any help would be appreciated.
You may use STR_TO_DATE in your delete query to convert the text dates to bona fide dates:
DELETE
FROM visited
WHERE
STR_TO_DATE(last_visit_date, '%d/%m/%Y %h:%i:%s %p') < '2020-11-01';
Note that if your text dates actually have month before day, then use this call to STR_TO_DATE:
STR_TO_DATE(last_visit_date, '%m/%d/%Y %h:%i:%s %p')
If you don't want to lose the dates with the wrong format, you can update the table:
UPDATE visited
SET last_visit_date = STR_TO_DATE(last_visit_date, '%d/%c/%Y %r')
WHERE last_visit_date LIKE '__/__/____ __:__:__ __';
and change the data type of the column to DATETIME (if all the other values of last_visit_date are valid datetimes):
ALTER TABLE visited MODIFY last_visit_date DATETIME;
See a simplified demo.

Checking Values Stored In A Column In A Date of Birth Format in Database

I am currently trying to get all records in a database that have a date of birth set to a future date. But I am not sure how to check the existing values stored and make sure they are greater than/less than today's date.
Currently all I have is,
select * from [table_name]
where [column_name] = .........;
the formats of the saved dates are DD-FEB-YY and they are stored in a column within a person table.
Use the CURDATE() function to get today's date. This will return all records later than today:
SELECT * FROM table WHERE dateColumn > CURDATE()

Only SELECT yesterdays date with weird date format

I need to only SELECT data where the date field is yesterdays date. The only problem I'm having is that the data in the date field looks like the following 20160412 062815.000
I don't really care about the time, I just want to search dynamically for anything with yesterdays date. I've tried a multitude of CURDATE() -1 but I'm unsure how to just search the first 8 digits of the field.
Assuming the date value is stored as a string, and the first 8 characters are always the date in YYYYMMDD format, then you can use a query like this:
select *
from your_table
where your_column like concat(date_format(current_date() - interval 1 day,'%Y%m%d'),'%')
One advantage of this query is that it can leverage an index on your date field, unlike the other answers so far.
Format yesterday's date to a number and convert the date string also to a number.
select * from your_table
where date_format(curdate() - interval 1 day, '%Y%m%d') * 1 = date_col * 1
SQLFiddle demo
*1 is a math operation that forces MySQL to convert strings to a number.
you can use subdate(currentDate, 1)
select * from your_table
where subdate(currentDate, 1) = DATE(your_date)