mySQL between dates that span over multiple years - mysql

Hi I was wondering why this statement is working in mySQL
SELECT COUNT(*) AS `numrows`
FROM (`myTable`)
WHERE DATE_FORMAT(creationDateTime, '%m/%d/%Y') BETWEEN '02/21/2011' AND '03/20/2011'
but this is not
SELECT COUNT(*) AS `numrows`
FROM (`myTable`)
WHERE DATE_FORMAT(creationDateTime, '%m/%d/%Y') BETWEEN '12/21/2010' AND '03/20/2011'
The first statement returns 'xx' count of the number of rows while the second one returns '0'
The only difference I see is that the "from" date is in 2010 and the "end" date is in 2011. To test if this was the problem I queried from '12/31/2010' and it still gave me 0 results but when I set the start date as '01/01/2011' it gave me the number of records that were created in that time span.
Is there something I am missing with regards to mySQL's BETWEEN and using dates from different years?
Thanks for the help!

Try using the date format BETWEEN '2010-12-21' AND '2011-03-20'. Also remove the DATE_FORMAT() function.
So, this:
SELECT COUNT(*) AS `numrows`
FROM `myTable`
WHERE creationDateTime BETWEEN '2010-12-21' AND '2011-03-20'

DATE_FORMAT() returns a string, not a date. By using it you're forcing a string comparison instead of a date comparison. You should omit the DATE_FORMAT and use YYYY-MM-DD date strings instead.

Related

Date and time conversion query in SQL

In my database table, there is a date column i.e. EXPECTED DATE which is in dd-mm-yyyy format, and the datatype of the column is text. Now, I want to convert the format to yyyy-mm-dd. But the date is not changing at all and also when I tried to get the timestamp for the expected date column . I am getting some errors. For date coming I have used this STR_TO_DATE. But the year is not coming like what I expect and the timestamp also.
For example:
select STR_TO_DATE ('30-11-2011', '%d,%m,%y') as date ;
returns a result as
2020-11-30
And for timestamp
select STR_TO_DATE ('2011,11,30 12,30,45', '%y,%m,%d, %H,%I,%S');
I am not getting errors.
Please help me get the correct answers for this problem.
For the first query you need to use the %Y. Remember that it is always better to use "Y" for the years when you are writing a query for year.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For the second one also, you can use '%Y' in the place of '%y'. For minutes, use '%i' not '%I'. For hours and minutes, you can use whatever you like.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");
Refer to the below documentation for more clarification on SQL commands.
You need %Y (capital Y) for the 4 digit year, when using MySQL's STR_TO_DATE. Also, minutes is represented by %i, not %I, the latter which is hours on a 0 to 12 scale. So use:
SELECT STR_TO_DATE('30-11-2011', '%d-%m-%Y');
SELECT STR_TO_DATE('2011,11,30 12,30,45', '%Y,%m,%d %H,%i,%S');
For the first query you need to use the %Y'.
SELECT STR_TO_DATE("30,11,2011", "%d,%m,%Y");
For minutes, use this one only '%i'.
SELECT STR_TO_DATE("2011,11,30 12,30,45", "%Y,%m,%d %h,%i,%s");

MySQL Query Group By Date

I have tried various recommendations based off of other posts with no avail.
I have a database scheme of records with a Created_Date Key, and Value would be 01/01/2017
I am trying to query the database records to give a returned count of How many records per month and which month those fall in line with.
With the following
SELECT SQL_NO_CACHE MONTH(`Created_Date`), COUNT(*)
FROM `CRM_Leads`
GROUP BY MONTH(`Created_Date`)
I return
MONTH(`Created_Date`) COUNT(*)
NULL 872
I have also tried almost all the variations on the following post
Count records for every month in a year
Any help would be appreciated.
assuming your created_date is a string of format ('dd-mm-yyyy') the you should convert as date with str_to_date
SELECT SQL_NO_CACHE MONTH(str_to_date(`Created_Date`, '%d/%m/%Y')), COUNT(*)
FROM `CRM_Leads`
GROUP BY MONTH(str_to_date(`Created_Date`, '%d/%m/%Y'))
For as long as you store date/time information as strings, you will have great difficulty using any date/time specific functions and features. If you are getting NULL from MONTH(str_to_date(Created_Date, '%d/%m/%Y')) then the str_to_date isn't converting the strings to dates and the most likely reason for this is the d m y "pattern" is not corrrect.
All you have old us about your "strings that might be dates" is that one of them looks like this: 01/01/2017. Now that could be DD/MM/YYYY or MM/DD/YYYY and we simply cannot tell which one is correct from the single value you have chosen to share with us. Look for any day value greater then 12 in your data e.g. 17/01/2017 ==> DD/MM/YYYY or 01/17/2017 ==> MM/DD/YYYY
Once you have made the choice of which pattern your "strings that might be dates" follow; apply that pattern in the str_to_date() function. You migh want to try a few different patterns to get the best one (and these are just 3 of many you could try):
# which pattern is best for you?
SELECT Created_Date
, str_to_date(`Created_Date`, '%d/%m/%Y') "d/m/y"
, str_to_date(`Created_Date`, '%m/%d/%Y') "m/d/y"
, str_to_date(`Created_Date`, '%Y-%m-%d') "y-m-d"
FROM `CRM_Leads`
You will not have success with your group by query until you choose the most appropriate d m y pattern to apply in teh str_to_date function. Note here that you might also have a variety of patterns in your data, in which case you have an even bigger problem to solve.
Once you have made the choice of which pattern your "strings that might be dates" follow; apply that pattern in the str_to_date() function and ONLY THEN your group by query will work.

SELECT range of date in Text field

Date
9/25/2015
9/26/2015
9/27/2015
9/28/2015
9/29/2015
9/30/2015
10/1/2015
10/2/2015
10/3/2015
10/4/2015
10/5/2015
Can anyone help me in MySQL. I would like to select only date from 9/28/2015 to 10/4/2015.
Please take note, this date is in Text field.
Thank you.
you can use STR_TO_DATE(yourdatefield, '%m/%d/%Y') to convert text to date and you can later use between clause to restrict output data.
Convert first your dates using CONVERT, then use BETWEEN in your WHERE clause.
Try this..
SELECT * FROM TableName
WHERE Date BETWEEN CONVERT(DATE,'9/28/2015') AND CONVERT(DATE,'10/4/2015')
You can try like this:
WHERE `Date` BETWEEN CAST('9/28/2015' AS DATE) AND CAST('10/4/2015' AS DATE)
or
WHERE STR_TO_DATE(`Date`, '%m/%d/%Y') BETWEEN STR_TO_DATE('9/28/2015', '%m/%d/%Y') AND STR_TO_DATE('10/4/2015', '%m/%d/%Y')
DEMO
Also try to avoid storing dates as Text. Instead use Date datatype to store dates.
Try this , in where clause used function str_to_date
SELECT `dateVal`,`id`
FROM `datecheck`
WHERE STR_TO_DATE(`dateVal`,'%m/%d/%Y') between STR_TO_DATE('9/28/2015',
'%m/%d/%Y') AND STR_TO_DATE('10/4/2015', '%m/%d/%Y')
I had the same type of issue but in my case the date stored also contains the time (also in a text field, for instance 2017-09-11 05:07:58 PM). This is for a wordpress site but I want to query the database directly, the date is in a meta_value.
To make this work I ended using a subbstring of the date, i am posting this in case it helps someone:
SELECT ID, display_name, user_email, meta_value FROM bfge_users, bfge_usermeta WHERE (bfge_users.ID = bfge_usermeta.user_id) AND meta_key ='user_login' AND CAST(SUBSTR(meta_value,1,POSITION(' ' IN meta_value)) AS DATE) between '2017-09-11' AND '2017-09-13';
use between, you can read more here:
Select data from date range between two dates
and question is dublicate

MySQL query to search in between two time range between two dates using timestamp data

I have timestamp values in my db. It has values like 2014-11-25 10:30:00.
I need to get all records between two dates and that has time between certain range like between 2014-10-20 to 2014-11-25 and between 9am to 7pm..
I need the query for this...
You can use the following query , I used it in my code for displaying data between two dates.
SELECT * from tablename WHERE columnname BETWEEN '2014-10-20 00:00:00' AND '2014-11-25 23:59:59'
The query includes start time of the particular date to end time of ending particular date.
You edit your query according to your start and end timings.
You can use internal mysql functions for convert datetype.
I think you need DATE() and TIME() functions.
Details you can find here
Thanks for your reply guys. I have found the answer
SELECT * FROM alerts
WHERE DATE BETWEEN '2014-11-16' AND '2014-11-26'
AND TIME(DATE) BETWEEN '09:00' AND '19:00'
Is giving the expected result.. :-)

Number of days between current date and date field

I have this problem if anyone can help.
There is a field (date) in my table (table1) that is a date in the format 3/31/1988 (M/D/y), and my necessity is to define how many days have passed since that date.
I have tried to give this instruction
SELECT DATEDIFF(CURDATE(), date) AS days
FROM table1
But it gives back 'null' and I think this happens because the two date formats are different (CURDATE() is YMD.....
Is it correct? can anyone help me?
Thank you in advance
You can use STR_TO_DATE():
SELECT DATEDIFF(CURDATE(),STR_TO_DATE(date, '%m/%d/%Y')) AS days
FROM table1
SQLFiddle Demo
Your DATE field should have DATE or DATETIME format to be used as DATEDIFF argument correctly.
Also DATE is MySQL keyword and I am not sure that you can use it as valid field name.
You can use this for accurate result
SELECT DATEDIFF(CURDATE(), DATE_FORMAT(FROM_UNIXTIME(UNIX_TIMESTAMP(`date`)), '%Y-%m-%d')) AS days FROM `table1`
If you want to consider results without - signs that you have to follow parameters position as below :
SELECT DATEDIFF(Big_Date,Small_Date) AS days FROM table1.
positive results e.g 5 (with no sign), if you place a Small date as the first parameter then it will results minus sign e.g -5.