Date SQL query doesn't work as expected - mysql

I have the following query:
SELECT * FROM incomings WHERE date >= '2011-04-01%' AND date <= '2011-04-29%'
And it shows results from 01-04 to 28-04. This may be a weird question but, it I think it should show results from 29-04 too, right?
What's wrong?

Your syntax is odd. That query would normally be written:
SELECT * FROM incomings WHERE date >= '2011-04-01' AND date <= '2011-04-29'
I think from the way that you're trying to query the data that your date column is actually a DATETIME or TIMESTAMP column. If that's the case then '2011-04-29%' will be being cast to '2011-04-29 00:00:00'
I would recommend you use this SQL instead:
SELECT * FROM incomings WHERE date >= '2011-04-01' AND date < '2011-04-30'

What is the purpose of the "%" here (besides making the date invalid) ?
If "date" is of type DATETIME, then :
'2011-04-29 00:00:00' is <= to '2011-04-29'
'2011-04-29 00:00:01' is not <= to '2011-04-29'

You don't need the leading %, the date without hours is interpreted as midnight (or the very start) of given date.

Related

query for date range '01-01-2019' and '02-02-2019' is not working

I have a query with date range like between '01-01-2019' and '03-02-2019' and it is working while I change day(02) of date range like '01-01-2019' and '02-02-2019' then Query is not working.
I have a query with date range from '01-01-2019' and To : '03-02-2019' like
SELECT * FROM `customer_info` WHERE `rec_date` between '01-01-2019' and '03-02-2019'
so it is working but when I change the day of date range like from '01-01-2019' and To : '02-02-2019' and query is
SELECT * FROM `customer_info` WHERE `rec_date` between '01-01-2019' and '02-02-2019'
But query is not working.
I want from this query that it should fetch records after changing day of date range of TO : '02-02-2019'.Please tell me solution why it is not fetching records.
With Only Date:
MySQL date format is this : YYYY-MM-DD. In a simple way it can be queried as
select * from customer_info where rec_date between '2019-01-01' and '2019-02-02'
OR
select * from customer_info where rec_date between >= '2019-01-01' and '2019-02-02'
With Date & Time:
Just use the format which MySQL handles dates YYYY-MM-DD HH:MM:SS and have the query as
select * from customer_info where rec_date >= '2019-01-01' and rec_date <= '2019-02-02'
Especially since MySQL now supports sub-second time precision. Using 23:59:59 is one full second short of the end of a day. where rec_date >= '2019-01-01' and rec_date <= '2019-02-02' is the most precise way to define a date range and will work for any level of time precision from date to sub-second units.
OR
Simple as that.
select * from customer_info where rec_date between '2019-01-01 00:00:00' and '2019-02-02 23:59:00'
That rec_date is probably a VARCHAR or CHAR type instead of a DATE type.
Then it should be transformed to a DATE type before getting a range from that.
Otherwise the BETWEEN will compare the strings alphabetically.
And when you then query a date range, use the 'YYYY-MM-DD' format for date constants.
That won't lead to a confusion with the months and days.
(Is '01-04-2019' the 1st of April, or the 4th of January?)
SELECT *
FROM `customer_info`
WHERE STR_TO_DATE(rec_date,'%m-%d-%Y') BETWEEN '2019-01-01' and '2019-03-02'

mysql and date comparison with date function and without

I notice a strange behavior for me when using date() and without:
when I use
SELECT * FROM `mytable` WHERE date(date_add) >= '2017-08-01' and date(date_add) <= '2017-08-31'
I get all dates records within the given date range but if do:
SELECT * FROM `mytable` WHERE date_add >= '2017-08-01' and date_add <= '2017-08-31'
I don't get the rows from the last day 31, why? (the date_add field is datetime type)
EDIT:
How should I code date range correctly? Because what I understand so far is that if I don't use full time like YYYY-MM-DD HH-MM-SS I should always compare with DATE() to avoid missing results from the last day.
That's because date_add is a DATETIME field. If the time for the date 2017-08-31 is something like 08:15:00 or 13:21:00 in your table, your date is "bigger" than just 2017-08-31 00:00:00. Your comparison would just return data for the 2017-08-31 having the time 00:00:00.
Because without the date() transformation your comparison imply the values '2017-08-01 00:00:00' and '2017-08-01 00:00:00'

Calculate difference between dates

The title might be a bit misleading, but what I want is:
SELECT * FROM table ORDER BY pid ASC
And in one of the columns I have a DATE(). I want to compare the current date (not time) and return how many days are left till that date. Let's say the date is 2013-04-20 and today's date is 2013-04-16 I don't want to get any data if it's < current date. If it is I want it returned in days.
I've been looking around here and I've found no way to do it, and I can't for the love of me figure it out.
If you're looking for the difference between two date you can use the GETDATE function in MS SQL
SELECT DATEDIFF(DD, DateOne, DateTwo) FROM TABLE
This will return the difference in number of days between the two dates.
If you only want rows where the date field is less than or equal to today's date you can use:
SELECT DATEDIFF(DD, DateField, GETDATE())
FROM TableName
WHERE DateField <= GETDATE()
If you're using MySQL you can use DATEDIFF()
SELECT
DATEDIFF(NOW(), date_column) AS days_diff
FROM
tablename
Get the difference between two dates (ANSI SQL)
select the_date_column - current_date as days_left
from the_table
where the_date_column - current_date <= 4;
SQLFiddle: http://sqlfiddle.com/#!12/3148d/1

How to compare timestamp dates with date-only parameter in MySQL?

In a SQL statement, how do I compare a date saved as TIMESTAMP with a date in YYYY-MM-DD format?
Ex.: SELECT * FROM table WHERE timestamp = '2012-05-25'
I want this query returns all rows having timestamp in the specified day, but it returns only rows having midnight timestamp.
thanks
You can use the DATE() function to extract the date portion of the timestamp:
SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'
Though, if you have an index on the timestamp column, this would be faster because it could utilize an index on the timestamp column if you have one:
SELECT * FROM table
WHERE timestamp BETWEEN '2012-05-25 00:00:00' AND '2012-05-25 23:59:59'
As suggested by some, by using DATE(timestamp) you are applying manipulation to the column and therefore you cannot rely on the index ordering.
However, using BETWEEN would only be reliable if you include the milliseconds. In the example timestamp BETWEEN '2012-05-05 00:00:00' AND '2012-05-05 23:59:59' you exclude records with a timestamp between 2012-05-05 23:59:59.001 and 2012-05-05 23:59:59.999. However, even this method has some problems, because of the datatypes precision. Occasionally 999 milliseconds is rounded up.
The best thing to do is:
SELECT * FROM table
WHERE date>='2012-05-05' AND date<'2012-05-06'
WHERE cast(timestamp as date) = '2012-05-05'
SELECT * FROM table WHERE timestamp >= '2012-05-05 00:00:00'
AND timestamp <= '2012-05-05 23:59:59'
Use a conversion function of MYSQL :
SELECT * FROM table WHERE DATE(timestamp) = '2012-05-05'
This should work
As I was researching this I thought it would be nice to modify the BETWEEN solution to show an example for a particular non-static/string date, but rather a variable date, or today's such as CURRENT_DATE(). This WILL use the index on the log_timestamp column.
SELECT *
FROM some_table
WHERE
log_timestamp
BETWEEN
timestamp(CURRENT_DATE())
AND # Adds 23.9999999 HRS of seconds to the current date
timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL '86399.999999' SECOND_MICROSECOND));
I did the seconds/microseconds to avoid the 12AM case on the next day. However, you could also do `INTERVAL '1 DAY' via comparison operators for a more reader-friendly non-BETWEEN approach:
SELECT *
FROM some_table
WHERE
log_timestamp >= timestamp(CURRENT_DATE()) AND
log_timestamp < timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY));
Both of these approaches will use the index and should perform MUCH faster. Both seem to be equally as fast.
SELECT * FROM table WHERE DATE(timestamp) = '2012-05-25'
It will work but not used index on "timestamp" column if you have any because of DATE function. below query used index and give better performance
SELECT * FROM table WHERE timestamp >= '2012-05-05 00:00:00'
AND timestamp <= '2012-05-05 23:59:59'
OR
SELECT * FROM table
WHERE timestamp >= '2012-05-05' AND timestamp < '2012-05-06'
Try running these to check stats
explain SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'
explain SELECT * FROM table WHERE timestamp >= '2012-05-05 00:00:00'
AND timestamp <= '2012-05-05 23:59:59'
In case you are using SQL parameters to run the query then this would be helpful
SELECT * FROM table WHERE timestamp between concat(date(?), ' ', '00:00:00') and concat(date(?), ' ', '23:59:59')
When I read your question, I thought your were on Oracle DB until I saw the tag 'MySQL'. Anyway, for people working with Oracle here is the way:
SELECT *
FROM table
where timestamp = to_timestamp('21.08.2017 09:31:57', 'dd-mm-yyyy hh24:mi:ss');
Use
SELECT * FROM table WHERE DATE(2012-05-05 00:00:00) = '2012-05-05'
Let me leave here it may help someone
For people coming from nodejs and expressjs
getDailyIssueOperations(dateName, date, status) {
const queryText = `
select count(*) as total from issues
where date(${dateName})='${date}' and status='${status}';
`;
},
in case date and column name are variables please find the implementation usefull

how to test date and datetime with mysql

My table is using a datetime (YYYY-MM-DD HH:MM:SS) and i need to display today's entries.
my code is only :
SELECT *
FROM table
WHERE date = '$date'
ORDER BY score DESC
with
$date = date("Y-m-d");
well, as expected it doesnt work :| you guys have a solution here ?
Following from Pascal Martin, you could extract the date part from the date+time field:
SELECT * FROM table WHERE DATE(date) = '2009-12-19'
Source: MySQL - Date and Time Functions
Be aware however, that this query will not use an index on your date+time field, if you will be having one. (Stack Overflow: How does one create an index on the date part of DATETIME field in MySql)
Your date is "2009-12-19" (or something like that, depending on the day), which is interpreted as "2009-12-19 00:00:00".
In your database, you probably don't have any date that's exactly equal to that one, by the second : your dates are like "2009-12-19 12:15:32".
A solution is to compare like this :
select *
from table
where date >= '2009-12-19'
and date < '2009-12-20'
Which will be interpreted as :
select *
from table
where date >= '2009-12-19 00:00:00'
and date < '2009-12-20 00:00:00'
And, if you don't want to do the math to get the date of the following date, you can use the adddate function :
select *
from table
where date >= '2009-12-19'
and date < adddate('2009-12-19', interval 1 day)
So, in your case, something like this should do the trick :
select *
from table
where date >= '$date'
and date < adddate('$date', interval 1 day)
order by score desc
You probably want to format the data when you select it:
SELECT *, DATE_FORMAT(date, '%Y-%m-%d') AS dateformat FROM table
WHERE dateformat = '$date' ORDER BY score DESC
You are comparing datetime and date expression, that is why its not working. Use Date() method to return the date part from datetime and then do the comparison. WHERE DATE(date) = '$date' should do. You might have to use aliases to handle this name collision.