how do I select on date equality in a mySQL query? - mysql

I want to select rows from a table given a particular date of record in mysql
SELECT * from TABLENAME WHERE FROM_DATE='06/11/2012'
I am not getting anything useful.

First of all, you should use the standard date format Y-m-d - otherwise you have to make some nasty queries and sorting is a real b*tch.
Using the standard date format you can easily do something like this:
SELECT * FROM tablename WHERE from_date > '2012-06-11'

DATE comparisons are very likely what you want here. If your from_date column has the data type of DATE, then your code should be safe and robust if you do this:
WHERE from_date = STR_TO_DATE('06/11/2012', '%m/%d/%Y')
#Repox pointed out that you might consider putting your date literals in the canonical format '2012-06-11'. That's true, if you can do it. But STR_TO_DATE will do it for you if you need it to. There's a list of the %x conversion items here. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
If you're using DATETIME data types, beware: comparisons are more complex than they seem. DATETIME items are like floating point numbers: if one of them exactly equals another it's only by coincidence. That's because they represent moments (milliseconds) in time, not just days.
Presuming your from_date column has the DATETIME type, you should use
WHERE from_date >= STR_TO_DATE('06/11/2012', '%m/%d/%Y')
AND from_date < STR_TO_DATE('06/11/2012', '%m/%d/%Y') + INTERVAL 1 DAY
This will catch all moments in time on the day you want, up to but not including the first moment of the next day.
If your from_date items are represented as character strings, take the trouble to convert them to DATE or DATETIME data types. Seriously. Your results will be far better.

SELECT * from TABLENAME WHERE FROM_DATE='2012/06/13'

It would be better if you use the DATE() function of mysql
SELECT * FROM tablename WHERE DATE(from_date) > '2012-06-11'
Because, if the datatype of the from_date you set as TIMESTAMP or DATETIME then it won't return the correct results sometimes when you directly use the '>' symbol

Related

SQL get date from timestamp

I have a database where all my data have a unix timestamp as a integer, the integer is the amount of seconds since 1.jan 1970.(like what Time.now.to_i returns in ruby http://www.unixtimestamp.com).
Is there any way i can get the date from 1447277423 in SQL? I need to group the rows by date.
I want this to be done in a view, and not use another script to do it.
Is this possible?
Convert the unix timestamp to date only (since you don't want hours/seconds), then group by it.
SELECT * FROM table
GROUP BY FROM_UNIXTIME(date_timestamp, '%Y %m %d');
Or, if you don't want to actually group them and just want them outputted all in order, ORDER BY instead.
SELECT * FROM table
ORDER BY date_timestamp
/* when ordering, it doesn't matter so much if its the whole timestamp or not since the date comes first in the timestamp */
To go one further, you can SELECT the formatted date as well
SELECT *, FROM_UNIXTIME(date_timestamp, '%Y %m %d') as date_Ymd FROM table
ORDER BY date_timestamp;
FROM_UNIXTIME docs
Just use FROM_UNIXTIME():
group by DATE(FROM_UNIXTIME(your_unix_timestamp_field))
That is the nice part of unix timestamps, you can just treat it as an integer.
SELECT something FROM table WHERE date >= 1447277423
Hope this helps

select a date lesser than a particular date

I have stored the dates as string in my database.I know it is not good,but project already has been half developed before i take over and where dates were stored as string,so i was continuing the same way.
Now i want to select dates from table where date is greater than a specific date.
I tried the following query
SELECT
*
FROM
dates
where
STR_TO_DATE(date, '%Y-%m-%d') > "2014-01-01"
but it is not returning only greater values.
Please help me to solve problem.
Demo
Your dates are not in YYYY-MM-DD format. Use the right format!
SELECT *
FROM dates
where STR_TO_DATE(date, '%m-%d-%Y') > date('2014-01-01')
If you are going to store dates as strings, then the best way is in the ISO format of YYYY-MM-DD.
You should read the documentation on str_to_date() (here).
Convert everything to date and it should be fine. Now you are comparing date and string.
What type has the date? I'd prefer a ' instead of " for strings in SQL. Let's assume that date is a VARCHAR or TEXT field (depending on which database you are using):
SELECT *
FROM dates
WHERE STR_TO_DATE(date, '%Y-%m-%d') > STR_TO_DATE('2014-01-01', '%Y-%m-%d')
If date is a real DATE
SELECT *
FROM dates
WHERE trim(date) > STR_TO_DATE('2014-01-01', '%Y-%m-%d')
Or you just convert it into a number format date_format(date,'%Y%m%d') > 20140101

Read data stored as text and use in IF statement

I have a column that stores dates as text, I need to select all the entries with date less than the date of today.
If I use this:
SELECT *
FROM mytab
WHERE expire < CURRENT_DATE( )
ORDER BY expire DESC
It doesn't select the correct entries but only the ones with da_expire empty.
How can I fix it?
In the first place, why are you storing it as string?
You need to convert it to date using MySQL's builtin function so you can be able to compare it with today's date.
WHERE STR_TO_DATE(expire, '%Y/%m/%d %H:%i') < CURDATE()
This will be a little slower since it will not use any index if you have one defined on the column.
MySQL Docs: STR_TO_DATE()
Use STR_TO_DATE(expire, '%m/%d/%Y') instead of expire in the query. I have assumed you are storing the date in month day year format. You will need to adjust the format as per the string format. However, for performance reasons convert the type of expire during load/insert process .

MySQL date validity

Does MySQL provide any function which verifies the validity of a date? The DATE function returns NULL upon provision of the invalid date 2013-02-30 for example. However, I am also using STR_TO_DATE simultaneously, which mysteriously stops DATE from working correctly.
SELECT DATE('2013-02-30'); NULL
SELECT STR_TO_DATE('2013-02-30', '%Y-%m-%d'); NOT NULL
SELECT DATE('2013-02-40'); NULL
SELECT STR_TO_DATE('2013-02-40', '%Y-%m-%d'); NULL
SELECT DATE(STR_TO_DATE('2013-02-30', '%Y-%m-%d')); NOT NULL
Why does STR_TO_DATE halt DATE's functionality and is there some workaround to verify if a date is valid when using STR_TO_DATE (which I am obligated to use)?
I have stumbled upon the answer in the meantime: apparently the DATE function skips a few validation checks, when the data type is already that of 'date' (STR_TO_DATE converts strings to date data types). Therefore, converting the date to a string after having parsed it to the correct format with STR_TO_DATE, does the trick:
#valid_date = NOT ISNULL(DATE(CONVERT(STR_TO_DATE('2013-02-29', '%Y-%m-%d'), CHAR))).
It is very difficult to verify if a field is a date because of all the different possible date formats that would need to be taken into account. BUT if you know that the field date formats are one of these:
'yyyy-mm-dd'
'yyyy-mm-dd hh:mm:ss'
'yyyy-mm-dd whatever'
This code will help you:
SELECT count(*) FROM `table`
WHERE DATE(STR_TO_DATE(`column`, '%Y-%m-%d')) IS NOT NULL
AND `column` NOT REGEXP '^[0-9\.]+$'
Basically :
the first condition tells you if is a date, but unfortunately doesn't exclude numbers (ex: DATE(STR_TO_DATE(**1**, '%Y-%m-%d')) = '2001-00-00'
the second ensures that numbers are excluded, which leaves you with dates only that follow the formats above.
If count(*) is >0 then it's a date, if it is 0 it's something else.
Note
This method works for strings of any date format as long as you know in advance what format they follow (which I know is not always the case but still helpful). Just replace the format a priori in STR_TO_DATE
i can't understand your purpose clearly, maybe this is a idea;
SELECT DATE_FORMAT(yourFiled, '%Y-%m-%d') days FROM yourTable GROUP BY days;
this is not null; you can change it. some like
SELECT DATE_FORMAT(yourFiled, '%Y-%m-%d') days FROM yourTable WHERE yourFiled > '2013-9-23 00:00:00' GROUP By days;
Try this:
SELECT DATE(STR_TO_DATE('2013-00-30', '%Y-%m-%d')); --is also NOT NULL

convert date from numeric value to date valid format

I need to filter all dates which greater than, say 01 january 2011.
select * from table_name where date > '01/01/2011';
the problem is that date field store int values, here is an example:
1339011098
1336717439
1339010538
How to convert the date field on the sql query (from the int format to date format), I need to convert it to a valid date so that I can compare it towards the above date.
Thanx.
You're going the wrong direction. Rather than converting potentially millions of records for the compare, try converting your target date, which you only need to do once. Those look like unix timestamps, so the resulting query should look like this:
SELECT * FROM `Table_name` WHERE date > unix_timestamp('01/01/2011')
Or, if you can control this, try using the ISO date format, which avoids confusion with european date formats for dates like 3/2/13:
SELECT * FROM `Table_name` WHERE date > unix_timestamp('2011-01-01')
You can use UNIX_TIMESTAMP()
select *
from table_name
where date > unix_timestamp('2011-01-01')
Or conversely use FROM_UNIXTIME()
select *
from table_name
where FROM_UNIXTIME(date, "%Y-%m-%d") > '2011-01-01'
First, you should not store date values as integers and if it's under your control your goal should be to fix the database and any queries that insert an integer value for that column instead of date.
The two date functions that you need to use with the current setup are UNIX_TIMESTAMP(), which accepts a date value and returns the epoch timestamp integer and FROM_UNIXTIME() which accepts an epoch timestamp integer and returns a date value.
For your example, you could use either:
SELECT * FROM table_name WHERE FROM_UNIXTIME(date_field) > '01/01/2011';
or
SELECT * FROM table_name WHERE date_field > UNIX_TIMESTAMP('01/01/2011');
But I would advise using FROM_UNIXTIME as a general rule as this would simplify more sophisticated queries such as:
SELECT * FROM table_name WHERE
FROM_UNIXTIME(date_field)
BETWEEN '01/01/2013' AND '04/01/2013';
Essentially, until your date field is actually storing values that are date types, your queries should covert the field values with FROM_UNIXTIME.