I am trying to get a report between two date and I don't know What is the best way, I did a query but sometimes it doesn't work and I dont know where the error is.
Thank you again.
I am saving datetime in mysql field type varchar with php date('h:iA d-m-Y').
Example in mysql row date:
09:22AM 26-06-2015
08:00AM 27-06-2015
10:00PM 28-06-2015
When I use this data example $since=01-06-2015 $until=30-06-2015 this works
But if I use this data $since=01-06-2015 $until=01-07-2015 this doesn't work.
$since = $_REQUEST['since'];
$until = $_REQUEST['until'];
mysql_query("select * from paradas where DATE_FORMAT(STR_TO_DATE(SUBSTR(date, 9),'%d-%m-%Y') , '%d-%m-%Y') between '".$since."' and '".$until."' ");
By storing your date and time as a VARCHAR, instead as a DATETIME you also change the comparison between two rows from a datetime comparison (chronological) to a string comparison (lexigrafical).
If you now (as in your example) chose a string representation, where the lexigrafical comparison provides different results than the chronological comparison, you can no longer use contructs like BETWEEN or operators like <= and friends.
Solution: If you want to store date and time information, use the DATETIME column type.
In addition to that let me direct you to this SO question for a discussion of your SQL query.
EDIT
Just to make that clear:
In a lexigraphical order '01-06-2015' < '20-06-2015' < '30-06-2015', which is the same as the chronological order
But in a lexigraphical order '01-06-2015' < '01-07-2015' < '20-06-2015', which is contrary to chronological order.
Related
I have a table which consist of ddate and time_start column and I wanted to compare it to today.
In SQL Server, I can directly cast ddate and timestart to format my desired date and compare it to GETDATE().
In my case, how do I compare the separate (ddate and time_start) to today?
EDITED
What I wanted is to concatenate it like '2020-06-01 11:23:00' and then compare it to today
The content of whereRaw() should be similar to what you're doing in plain SQL. If not, feel free to customize it.
DB::table('your_table')
->whereRaw('CONCAT(ddate, " ", time_start) = GETDATE()')
I have stored dates (dd/mm/yyyy) in text format in a table in a field called dates. I want to compare those dates with the current date and if the dates are smaller (if the dates have passed) to move the entire row into a new table called archive. Tried something with the DATEDIFF() but I'm new to MySQL and can't figure it out.
I'm going to preface my answer with a short remark: storing "date" values in SQL database in VARCHAR columns is an anti-pattern. MySQL provides native datatype DATE which is designed to handle "date" values. But that's just a remark, doesn't answer your question.
You can use the convenient MySQL STR_TO_DATE function to convert strings into DATE values. For example:
STR_TO_DATE('15/05/2015','%d/%m/%Y')
You could use a column reference in place of the literal, e.g.
STR_TO_DATE(t.mycharcol,'%d/%m/%Y')
and that will return a DATE value you can compare to another DATE value, using the standard inequality operator < for example.
To return the current date from the database, you can use an expression such as
DATE(NOW())
Putting that together, you could write a query like this:
SELECT t.*
FROM t
WHERE STR_TO_DATE(t.mycharcol,'%d/%m/%Y') < DATE(NOW())
If you want to take the result from a SELECT statement and insert those rows into another table, you can use the INSERT ... SELECT form of the INSERT statement.
Reference: https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date
Beware of the behavior with badly formatted or invalid dates, e.g.
SELECT STR_TO_DATE('35/05/2015','%d/%m/%Y')
, STR_TO_DATE('15-05-2015','%d/%m/%Y')
I am using HTML input type="date" to allow users to input appointment dates.
Now I want to query the database and show all appointments that are "today" and in the future.
Not dates that have already passed.
Here is my SQL Script
$today = date('d-m-Y');
$sql = "SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF('$today', `date`) >= 0
ORDER BY `id` DESC";
Can someone guide me as to how I can achieve this?
I have seen several directions online but I want to have the sorting done at the moment of query.
I have solved the issue!
My date() format was incorrect because HTML input type="date" inserts YYYY-MM-DD into the database =/
$today = date('d-m-Y');
should be
$today = date('Y-m-d');
My operator >= should have been <= to show today and future dates.
Thanks everyone for the help. I should have tried fixing it for 5 more minutes before posting.
Why are you using PHP to compare dates in the database? I assume its a date field so you can use MySQL to do it for you:
SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF(date_format(now(), '%Y/%m/%d'), `date`) >= 0
ORDER BY `id` DESC
None of the responses have specified sargable predicates. If you perform an operation on a column in the where clause, there is no discernible stopping point.
where ... some_function( some_field ) = some_constant_value ...
Even if some_field is indexed, a complete table scan must be performed because there is no way to know if the output of the operation is also ordered.
From my understanding the date column is in a sortable form -- either a date field or a string in lexically sortable format 'yyyy-mm-dd'. That being the case, don't do any operation on it.
where ... some_field >= now() ...
Thus the system can use the result of now() as a target value to find exactly where in the index to start looking. It knows it can ignore all the rows with indexed values "down" from the target value. It has to look only at rows with indexed values at or "up" from the target value. That is, it performs an index seek to the correct starting point and proceeds from there. This could mean totally bypassing many, many rows.
Or, to put it bluntly, ditch the datediff and do a direct comparison.
Hi there please help me if you can. Here is my senario:
I have a MySQL database with a column that holds a date in the form of a varchar. The format of the date is the following 29/05/2014 (i.e. d/m/Y).
I'm trying to compare the value of this column with todays date and return any rows where the date is earlier than todays date.
I'm using a php variable to store todays as follows:
$date = date("d/m/Y");
Here is my SQL query:
SELECT * FROM patients WHERE last_seen < '$date'
What gets returned
So what is returned is very unusual (to me). All records where the last_seen "day" is less than todays "day". It seems to be overlooking the month and year. So in other words if I last_seen = "30/05/2014" and todays date is "29/05/2014" this record is still returned.
Does anyone have any ideas what I might be doing wrong here?
Thanks
You really, really shouldn't store dates in a varchar field - use date or datetime or timestamp data type.
That said, sometimes you don't have control over the database and you have to deal with somebody else's bad design decision. In this case, to compare dates, convert the varchar strings to dates and compare them that way. So, in your case, you can have something like this:
$date = date("d/m/Y");
and then
SELECT * FROM patients WHERE str_to_date('last_seen', '%d/%m/%Y') < str_to_date('$date', '%d/%m/%Y')
or simpler
SELECT * FROM patients WHERE date(last_seen) < current_date
This way you are actually comparing dates and not strings containing dates. Naturally, this assumes that all dates are stored in the same format.
EDIT: I just tested the last option - and, apparently, date('30/05/2014') returns NULL on my system (mysql 5.5 on linux), hence I suggest the best way is
SELECT * FROM patients WHERE str_to_date('last_seen', '%d/%m/%Y') < current_date
You need to store your date as DATE or DATETIME in your database.
Then you can use:
SELECT * FROM patients WHERE DATE(last_seen) < CURRENT_DATE
In my project , I am generating and storing the Bill (invoice).
The date of Bill is coming to the textbox from the javascript date picker(small pop-up calender) before saving.
The format of the date is : DD-MON-YYYY (18-JUN-2013).
I am using 'Text' data type for storing dates in MySql table.
I have done selecting of records(Previous Bills) from the table by given single date like. . .
$result = mysql_query("SELECT * FROM outward WHERE date='".$date."' ORDER BY billNo");
Now, what i want to do is:
To select records (Bills) between two dates.....
My exact Question is:
Is it possible to query mysql database with this settings or I have to make some changes to select records between 2 dates efficiently ?
How can i achieve this ?
P.s. - Is it effective to use
1. "SELECT * FROM outward WHERE date BETWEEN '" . $from_date . "' AND '" . $to_date . "' ORDER by id DESC"
Or
2. SELECT * FROM outward WHERE date > "15-JUN-2013" and date < "18-JUN-2013"
You could do it in a pure SQL way, but you are going to have to do a full table scan for each query.
select the_dates,
STR_TO_DATE(the_dates, '%d-%M-%Y') as converted
from testing
where STR_TO_DATE(the_dates, '%d-%M-%Y') between '2013-06-20' and '2013-06-23'
Link to SQLFiddle
You should use strtotime PHP function to convert string date to UNIX timestamp format and change MySQL data type for date field to TIMESTAMP.
Than you can do effective queries with > and <.
If it's a DATE column, you can get all dates between 15 June 2013 and 18 June 2013 (inclusive) using this:
WHERE date BETWEEN '2013-06-15' AND '2013-06-18'
If it's a DATETIME column, do this instead:
WHERE date >= '2013-06-15' AND date < '2013-06-19'
If the date column is indexed, this approach will make sure the indexes are available for optimization. If it isn't indexed, the approach is just as fast as the many other ways you can do this.
Addendum: Just saw the "storing as text" amidst all the other shouted info. Note that this answer applies only if the type is DATE or DATETIME. I'll leave it up because the best answer is to change the column's data type and then use this or one of the other suggested options.
I am using 'Text' data type for storing dates in MySql table.
That's a problem. You should store dates as date or datetime data type in MySQL. If you don't care about the time part, date should be sufficient.
If you change your data type to date, then doing:
select x,y,z from table a where a.datecolumn between #startdate and #enddate
Should work fine.
If you use a text data type, you would have to cast the column to a date column and then apply your date selection range which is going to be slower due to the cast.
Always store data in the data type that matches its kind. If a date then a date column, if it's text then text or varchar, etc. The presentation layer of your app can worry about the format in which this data is presented to the user.
You said you were using a TEXT column to store the dates. That's an extremely bad idea. If you switch to a DATE or a DATETIME, then this becomes trivial.
Since you are storing it as text but you want SQL to parse it as a DATE SQL doesn't understand in the first place.
In your example SQL will use TEXT comparison rules. So 15-April < 15-Mar > 15-DEC
If you are storing dates in an SQL database you should be storing it as a Date and not as TEXT.