mySQL query between two dates and two times - mysql

I would like to query a mySQL table to pull out data between two dates and two times. I know how to do this for a single "datetime" column using the "between" call but my columns are one "date" column, and one "time" column. All the solution I can find online are for single datetime columns.
My ranges go from "day1" at 15:30 to day1+1day at 15:14
So far I can get the following range (which works):
SELECT time,
close
FROM intraday_values
WHERE date="2005-03-01"
and time between "15:30" and "23:59"
But I obviously need to incorporate 2 dates and two times. I have tried the following but get an error:
SELECT time,
close
FROM intraday_values
between date="2005-03-01"
and time="15:30"
and date="2005-03-02"
and time = "15:14"
Could someone help me formulate the query correctly? Many thanks

Not sure if your date field is indexed. If they are then the "concat" examples others have given may not perform very well.
As an alternative you can use a query of the form:
select *
from foo
where (date > lower_date and date < upper_date) -- technically this clause isn't needed if they are a day apart
or (date = lower_date and time >= lower_time)
or (date = upper_date and time <= upper_time)
It's not pretty but it works and will allow mysql to make use of indexes on the date field if they exist.
So your query would be
SELECT time,
close
FROM intraday_values
where (date > "2005-03-01" and date < "2005-03-02")
or (date = "2005-03-01" and time >= "15:30")
or (date = "2005-03-02" and time <= "15:14")

Use concat to combine these two column and cast it to datetime for the best results
SELECT
time,close
FROM
intraday_values
where
cast(concat(date," ",time) as datetime)
between
cast("2005-03-01 15:30") as datetime
and cast("2005-03-02 15:14") as datetime

Related

mysql filter by date and time separately

I have to perform a query on a MySQL database.
I have a table with records, have a column called "date" (the date type), and a column called "time" (type. Integer is stored by multiplying the time of day by 60. eg 8 am is stored as 480).
Unfortunately, the format of this table can not be modified.
My table stores attentions of doctors on call. The doctors on duty working in two shifts: from 8-20, and 20-8.
I need to know the amount of attention for every doctor.
My query must be filtered by date range and shift.
The problem is that, in the case of doctors working at the turn of 20-8, I have to consider a change of day. (sorry for my bad English).
What I have done is this, this would be an example to date of yesterday, and doctors shift 20-8.
SELECT * FROM attentions WHERE (date >= '2015-07-23' and time >=1200) and (date <= '2015-07-24' and time <480)
the query does not work at all.
Supposing the date field is called: 'a_date' with format 'yyyy-mm-ss' and the time field is a number, the query should be:
SELECT * FROM attentions WHERE (date(a_date) >= '2015-07-23' and time >=1200) and (date(a_date) <= '2015-07-24' and time <480)
Can you check using between?
SELECT * FROM attentions WHERE date between '2015-07-23' and '2015-07-24' and time between 1200 and 480
I think you can also use this -
SELECT * FROM ***** where CREATED_DATETIME between '2015-03-12 00:00:00' and '2015-05-11 00:00:00';

mysql query in between dates not working

I have the following mysql table:
tasks:
=====================
tid
status
desc
duedate
And i have the following records in that table:
records
===========================
1
active
Test description
08/15/2014
2
active
Another description
08/31/204
I am trying to get the days that there is a task for, in that particular month. I have the following query but when i run it it gets both records but "day" is null on both of them for some reason. Can someone please help me with this.
MYSQL QUERY
====================
SELECT DATE_FORMAT(due_date,'%d') AS day FROM tasks WHERE due_date BETWEEN '08/01/2014' AND '08/31/2014'
Try:
SELECT DAY(due_date) AS day
FROM tasks
WHERE due_date >= '2014-08'
AND due_date < '2014-09';
DAY() is a better function for what you want and I prefer using >= and < than BETWEEN for date comparisons, as it allows you to specify precise ranges more easily. Here, for example, you don't need to know the number of days in the month.
I have also used the default date format, which is preferable. If you need the, in my opinion, cray American date format, use DATE_FORMAT() in your SELECT.
This will only work with DATE, DATETIME and TIMESTAMP columns, which is how your due_date should be stored, preferably DATE.
UPDATE
To convert the VARCHAR column to DATE run:
UPDATE tasks SET due_date=STR_TO_DATE(due_date,'%m/%d/%Y')
Then change the type. Also remember to change your INSERT statements to use the default format.
You've got to convert those "date" strings to proper date values with STR_TO_DATE:
SELECT
DAY(STR_TO_DATE(due_date,'%m/%d/%Y')) AS day
FROM tasks
WHERE
STR_TO_DATE(due_date, '%m/%d/%Y')
BETWEEN STR_TO_DATE('08/01/2014' '%m/%d/%Y')
AND STR_TO_DATE('08/31/2014', '%m/%d/%Y')
else you're comparing strings instead.
Note:
It would be better to use a proper DATE or DATETIME column instead.
With the current VARCHAR format MySQL is unable to use indexes. That's very bad for performance.
You can convert your data by adding another column to your table:
ALTER TABLE tasks
ADD COLUMN new_due_date DATE;
Then you use an UPDATE statement to fill this new column
UPDATE tasks
SET new_due_date = STR_TO_DATE(due_date, '%m/%d/%Y');
If you don't need your old column anymore then you can delete this column and modify the new column to have the name of the old one. Then you will have your table with all your data in a DATE column.

Mysql Select with Dates and maybe Case when

im having a problem where i cant think of a solution, maybe im having a bad table-structure or i just dont know enough about mysql select commands to think of a good solution. Maybe you can help me out:
So i got a table that has a Column with the Date-format (yyyy-mm-dd) i wanted to select all upcoming dates so i did:
SELECT * WHERE date >= now.
This worked kinda well but i also got "dates" where only the year is entered (2014-00-00) i also wanted to select these but "now" is already bigger so i made another column with the year only and if the month, date or both arent known i will use 0000-00-00 and the Column "year" now i could select like this:
SELECT * WHERE date >= now AND year >=now(year)
Now all entrys with 0000-00-00 wont be selected. If i use OR the entrys from last year will be shown.
So thats my problem, is there any way i can change my table so i can have entries with only the year or only year and month and of course all together? I already considered get rid of the date-format and use simple INT with seperated columns for year, month and date. But i think i will have the same problem.
Sometimes i just want to do a capsuled select like
SELECT *
WHERE (date >= now AND year >= now(year))
OR date == "0000-00-00" (i know that this doesnt work)
If I understood your problem correctly, you could use this request:
WHERE (date >= now OR year > now(year))
There is probably a simpler way though, that would preserve your design, like initializing at January 1st (01-01) instead of 00-00
I think you can use this code:
$_SESSION['month'] = //set here your selected month
$_SESSION['year'] = //set here your selected year
SELECT * FROM table WHERE DATEPART(m,date) >= '".$_SESSION['month']."' AND DATEPART(yyyy,year) >= '".$_SESSION['year']."' AND date <> '0000-00-00'
Change your table structure format. Actually just allow for that field to have null value when not entered. By default it will be null then. You shouldn't be storing 0000-00-00 as a value for Date type field. I would rather leave it as null , or as suggested in some of previous answers, initialize it with some other date. It would be much easier to manipulate with database then.
the problem is that half of you write is not MySQL and your database schema is terrible...
You have the following problems:
column data date does not have the date data type.
To fix it, you need to add a cast to the select statement eg. cast(datecolumn as date)
select * from table where cast(datecolumn as date) >= '2014-01-10';
the way to use now date is using the now function.
select now(), date(now());
result> 2014-01-10 11:11:36, 2014-01-10
select * from table where cast(datecolumn as date) >= date(now());
Because your datecolumn is not a date (2014-00-00 is not a valid date), you need to use string manipulation to extract the year.
select substring('2014-01-01', 1,4)
result> 2014
select * from table where substring(datecolumn, 1,4) = year(now());
The comparassion operator is = and not ==
the select statement syntax looks like this (pay attention because you are missing the table in your statement)
select * from [Table] where [column] = condition ...
You probably need or instead of ands, therefore your query should look like this:
select * from FooTable where
cast(datecolumn as date) >= date(now())
or substring(datecolumn, 1,4) >= year(now())
or datecolumn = '0000-00-00'
You should use something like phpmyAdmin or mySQL workbench to test your sql queries before try to use them on php, java or whatever is your programing language.

Sql - find if date is between two dates

I have a field of FromDate and a field of ToDate.
I am looking for the rows that today is between the "from" and "to"
select * from job
where job.type='manager'
and '2014-01-22' between job.FromDate and job.ToDate
The query does not throw an exception , and it even returns some rows. But it isn't right- the rows it returns do not have the dates I am looking for.
P.S. the date format I am using is the correct one for my DB.
Try this
select * from job
where job.type='manager'
and job.FromDate <= '2014-01-22' and job.ToDate >= '2014-01-22'
Comparing dates is often tricky, especially if the values are stored as datetime and not date. The time components can affect the comparison. Another possibility is that ToDate is NULL for the most recent records. Here is one way to fix this:
select *
from job
where job.type ='manager' and
date('2014-01-22') between date(job.FromDate) and date(coalesce(job.ToDate, '2099-12-31'))
However, the use of the function on the columns can make the query less efficient. Instead, you might try:
select *
from job
where job.type ='manager' and
job.FromDate < '2014-01-23' and
(job.ToDate >= '2014-01-22' or job.ToDate is null);

Getting week started date using MySQL

If I have MySQL query like this, summing word frequencies per week:
SELECT
SUM(`city`),
SUM(`officers`),
SUM(`uk`),
SUM(`wednesday`),
DATE_FORMAT(`dateTime`, '%d/%m/%Y')
FROM myTable
WHERE dateTime BETWEEN '2011-09-28 18:00:00' AND '2011-10-29 18:59:00'
GROUP BY WEEK(dateTime)
The results given by MySQL take the first value of column dateTime, in this case 28/09/2011 which happens to be a Saturday.
Is it possible to adjust the query in MySQL to show the date upon which the week commences, even if there is no data available, so that for the above, 2011-09-28 would be replaced with 2011/09/26 instead? That is, the date of the start of the week, being a Monday. Or would it be better to adjust the dates programmatically after the query has run?
The dateTime column is in format 2011/10/02 12:05:00
It is possible to do it in SQL but it would be better to do it in your program code as it would be more efficient and easier. Also, while MySQL accepts your query, it doesn't quite make sense - you have DATE_FORMAT(dateTime, '%d/%m/%Y') in select's field list while you group by WEEK(dateTime). This means that the DB engine has to select random date from current group (week) for each row. Ie consider you have records for 27.09.2011, 28.09.2011 and 29.09.2011 - they all fall onto same week, so in the final resultset only one row is generated for those three records. Now which date out of those three should be picked for the DATE_FORMAT() call? Answer would be somewhat simpler if there is ORDER BY in the query but it still doesn't quite make sense to use fields/expressions in the field list which aren't in GROUP BY or which aren't aggregates. You should really return the week number in the select list (instead of DATE_FORMAT call) and then in your code calculate the start and end dates from it.