SQL WHERE clause: sort by date for string - php

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'

Related

Filter MySQL Query By DateTime Stored As Varchar

I'm trying to filter a MySQL query by a field that stores datetime values, but uses a varchar data type.
Example data:
16:56:41 01/14/21 GMT
Example code:
SELECT * FROM table_name WHERE STR_TO_DATE(datetime,'%H:%i:%S %m/%d/%y') BETWEEN '00:00:00 01/14/21' AND '23:59:59 01/14/21'"
The query is currently returning nothing at all. However the code below works:
SELECT * FROM table_name
Any thoughts would be much appreciated.
Your use of STR_TO_DATE is correct, but your date literals are off. Fix them, and your query should work:
SELECT *
FROM table_name
WHERE STR_TO_DATE(datetime,'%H:%i:%S %m/%d/%y') >= '2021-01-14' AND
STR_TO_DATE(datetime,'%H:%i:%S %m/%d/%y') < '2021-01-15';
The above assumes that you want records occurring on 14th January, 2021, proper. Note that we don't need to even include the H:M:S components and can just use date literals.
It would be best to make your datetime column a proper datetime type column, rather than text. This would avoid the need to use STR_TO_DATE.

Sort by Date field which is a VARCHAR in the database

All,
I have the following query:
SELECT ...
FROM....
WHERE...
ORDER BY gear_checkout_summary.check_out_date DESC";
I then have the following dates for example:
12/29/2012
11/30/2012
09/04/2012
07/21/2013
07/08/2013
06/29/2013
They are sorted this way when my results are returned. My data element is stored as VARCHAR(10) in my database since I messed up that design. Is there a way to change my query so it sorts the dates correctly?
Thanks!
Try this:
ORDER BY SUBSTR(check_out_date, 7) DESC, check_out_date DESC
This first orders by the year using the SUBSTR() function. For rows that have the same year, it then orders by the date itself. This second-level ordering doesn't require SUBSTR() because MM/DD is already ordered properly.
STR_TO_DATE will see your job
STR_TO_DATE(gear_checkout_summary.check_out_date, '%c/%e/%Y') // will give '2013-06-23' in Date format
This will convert your varchar field into date format.
This would put the date in the proper MySQL date format and then ordering would be simple.
SELECT
STR_TO_DATE(gear_checkout_summary.check_out_date,"%m/%d/%Y") AS fixed_date
...
FROM ...
WHERE ...
ORDER BY fixed_date DESC
As others have stated, you should fix the format in the database if at all anyway possible. You may need to change the insert statements, but it will be worth the extra work. Here is what you would need to do to format the dates in the database
ALTER TABLE gear_checkout_summary ADD check_out_date_temp DATE AFTER check_out_date;
UPDATE gear_checkout_summary SET check_out_date_temp = STR_TO_DATE(gear_checkout_summary.check_out_date,"%m/%d/%Y");
ALTER TABLE gear_checkout_summary DROP check_out_date;
ALTER TABLE gear_checkout_summary CHANGE check_out_date_temp check_out_date DATE;
Here is explanation of above code:
Create new column in your table.
Populate the new column with the dates from the previous column formatted correctly.
Drop the old bad formatted column.
rename new column to previous columns name.
Use str_to_date:
select *
from your_table
order by STR_TO_DATE(yourDateField,'%m/%d/%Y') desc;
This will convert the string to a valid MySQL date. Check this link: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_str-to-date
You should change your data type to DATE... it is the easiest and cleanest way to store dates.
I tried all codes and at the end I achieve my sorting on varchar date with this code...
ORDER BY SUBSTR(check_out_date, 7) DESC, ORDER BY SUBSTR(check_out_date, 1,2) DESC,ORDER BY SUBSTR(check_out_date, 4,2) DESC
First sort by year, then by month and at the end by day...

Wrong search between dates

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.

Select a year from a sql value which has a date value of xxxx-xx-xx

In my SQL table i have birthdates stores in the column bday as (for example) 1987-02-31
I want to have a SELECT query that only chooses from the year, and ignores the month and day, such as :
SELECT FROM users WHERE bday=1987
is this possible to do with the dates stored this way?
You can simply use the YEAR() MySQL function:
WHERE YEAR(bday)=1987
#soju's answer is correct if the field is a Date datatype, but...
You specifically said that your database has them stored as 1987-02-31
To me this suggests that you might be dealing with a database that uses varchar or another text field to store what should be dates.
If this is the case, you can use the SUBSTRING function.
WHERE SUBSTRING(bday, 1,4) = '1987'
SELECT FROM users WHERE bday LIKE '1987-%'
With MySQL, if your bday is a date column (not a text one), you can use the year() function like this:
select * from users where year(bday)=1987;

PHP mysql: how do I select records for today, or a particular day?

I am working with a table on which I can't change the structure.... Now there is a varchar column which contains a timestamp. Now I need to select the records whose timestamp translates to the current date, or a specified date.
Any help?
First off you shouldn't be storing date information in a mysql database with a VARCHAR field. Rather use DATETIME that is what it is for. I can only guess how you have stored your timestamp date in the database but I am going to assume it is the following format:
YYYY-mm-dd hh:mi:ss (ie '2011-04-15 09:23:55')
You now have to format your input which I am assuming is a time object or it is a string in the same format as the data in the database:
$yourdate = strftime("%Y-%m-%d", $input);
then construct your query
query = "select * from table where substring(datecol, 1, 10) = '$yourdate'";
execute this and you should be good
Based on the format that you're storing the date as a string, use the STR_TO_DATE function to parse out the date. Then you can use it as a part of the where clause to query desired data.
try this
select * from table where date(your_field)=CURDATE()
or specific date
select * from table where date(your_field)=DATE_FORMAT(2011-05-31 00:02:00, '%Y-%m-%d')

Categories