Wrong search between dates - php

In the database I have table users which have column 'birthday'
Here is the sql query that I use to fetch the results
SELECT *
FROM (`users`)
WHERE `birthday` between '12/11/1982' and '31/01/1983'
The problems is that I get records only for year 1982?
Notice that records for 1983 year exists.
What could be the problem here ?

This is just an alternative answer from Mark Byers. If the data type of your column birthday is varchar and has format of dd/MM/yyyy, please do read this; otherwise, read from Mark Byer's.
The first thing you need to do is to convert your column into DATE or DATETIME datatype by using STR_TO_DATE,
SELECT *
FROM `users`
WHERE STR_TO_DATE(`birthday`,'%d/%m/%Y')
between '1982-01-12' and '1983-12-31'
SQLFiddle Demo
SOURCES
STR_TO_DATE
DATE formats

You should put the year first in your date literals:
SELECT *
FROM `users`
WHERE `birthday` between '1982-11-12' AND '1983-01-31'
From the documentation:
Date and time values can be represented in several formats, such as quoted strings or as numbers, depending on the exact type of the value and other factors. For example, in contexts where MySQL expects a date, it interprets any of '2015-07-21', '20150721', and 20150721 as a date.
If you are using a varchar type then it still makes sense to put the date first (both in the data and in the query) because then your dates will sort correctly when using the default sorting order.

Related

Date comparison from VARCHAR column value

I have a SQL table where one of the columns 'creator' is a VARCHAR data type. That column stores values like this one: Mike Jones|05-17-2015 1:21 pm consisting of the person that created the record, the date and time it was created.
I need to use the date portion of that varchar data to form a SQL query, so that we can generate a list of tickets created between two dates. We can't restructure the table easily so i'm stuck working this out in its current format, otherwise we just would have added a CREATED date field and compared on that.
The SQL being attempted is this:
SELECTticknumb,cnames,creator,ticktype,tickstatusFROMaticketsWHEREcreator>= '%05-24-2015%' ANDcreator<= '%05-30-2015%' ANDtickstatusNOT LIKE 'Closed,Complete'
Is there a way to do this directly within the SQL query without having to to a looped explode in the php first to extract and compare the earliest / latest dates?
Here is SQL snippet how you can convert your value in varchar column to date type.
SELECT STR_TO_DATE(SUBSTRING_INDEX(`creator`, '|', -1), '%m-%d-%Y %h:%i %p')
http://sqlfiddle.com/#!9/710a2/7/0
Another inspiration
how to convert a string to date in mysql?
How to split the name string in mysql?
I hope it is what you are looking for.

MySQL comparing stored date with current date and execute

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')

SQL WHERE clause: sort by date for string

I have a column in my database table that holds dates in the format (mmm-yy) Ex: Aug-13. I'm trying to select all dates after Jun-12. The problem is the column is a string so when I say WHERE column > 'Jun-12' it gives me values that are alphabetically greater than Jun-12 such as May-12, which is not what i want. Any thoughts on how to go about this?
Store dates as dates, not strings. That's the recommended way of doing it and I recommend changing your code accordingly.
In this case, you could use STR_TO_DATE function to compare the dates on the fly:
SELECT * FROM table_name WHERE column > STR_TO_DATE('Jun-12','%m-%y');
Hope this helps!
In this situation you'll should be able to convert to a date and then filter as required, the below code should give you a guide,
SELECT *
FROM Table
WHERE CAST('01-' + column AS DATETIME) > '01-JUN-12'

Selecting records between two dates using PHP from MySql database

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.

Mysql select query after certain date

I am trying to pull records after a certain date using mysql query , the field type is date in my database and the query is
SELECT * FROM tickets WHERE created_on > 26-08-2011
But it is not working and also showing all before that date
Thanks
The date you are using is a string, so it needs to be placed inside quotes. Also, the format is the wrong way around:
SELECT * FROM tickets WHERE created_on > '2011-08-26'
For more information, see the MySQL docs. In particular, note the very first line:
The format of a DATE value is 'YYYY-MM-DD'. According to standard SQL,
no other format is permitted.
The date is defined in yyyy-mm-dd, so you should use the date as 2011-08-26.
Using a date in this format is ideal for sorting as the numbers are arranged as incremental pieces.
You have to use quotes on string values, see the post of James Allardice.
Try using quotes on the date and write dates in yyyy-mm-dd format for best results. '2011-08-26'

Categories