How to compare timestamp dates with date-only parameter in MySQL? - mysql

In a SQL statement, how do I compare a date saved as TIMESTAMP with a date in YYYY-MM-DD format?
Ex.: SELECT * FROM table WHERE timestamp = '2012-05-25'
I want this query returns all rows having timestamp in the specified day, but it returns only rows having midnight timestamp.
thanks

You can use the DATE() function to extract the date portion of the timestamp:
SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'
Though, if you have an index on the timestamp column, this would be faster because it could utilize an index on the timestamp column if you have one:
SELECT * FROM table
WHERE timestamp BETWEEN '2012-05-25 00:00:00' AND '2012-05-25 23:59:59'

As suggested by some, by using DATE(timestamp) you are applying manipulation to the column and therefore you cannot rely on the index ordering.
However, using BETWEEN would only be reliable if you include the milliseconds. In the example timestamp BETWEEN '2012-05-05 00:00:00' AND '2012-05-05 23:59:59' you exclude records with a timestamp between 2012-05-05 23:59:59.001 and 2012-05-05 23:59:59.999. However, even this method has some problems, because of the datatypes precision. Occasionally 999 milliseconds is rounded up.
The best thing to do is:
SELECT * FROM table
WHERE date>='2012-05-05' AND date<'2012-05-06'

WHERE cast(timestamp as date) = '2012-05-05'

SELECT * FROM table WHERE timestamp >= '2012-05-05 00:00:00'
AND timestamp <= '2012-05-05 23:59:59'

Use a conversion function of MYSQL :
SELECT * FROM table WHERE DATE(timestamp) = '2012-05-05'
This should work

As I was researching this I thought it would be nice to modify the BETWEEN solution to show an example for a particular non-static/string date, but rather a variable date, or today's such as CURRENT_DATE(). This WILL use the index on the log_timestamp column.
SELECT *
FROM some_table
WHERE
log_timestamp
BETWEEN
timestamp(CURRENT_DATE())
AND # Adds 23.9999999 HRS of seconds to the current date
timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL '86399.999999' SECOND_MICROSECOND));
I did the seconds/microseconds to avoid the 12AM case on the next day. However, you could also do `INTERVAL '1 DAY' via comparison operators for a more reader-friendly non-BETWEEN approach:
SELECT *
FROM some_table
WHERE
log_timestamp >= timestamp(CURRENT_DATE()) AND
log_timestamp < timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY));
Both of these approaches will use the index and should perform MUCH faster. Both seem to be equally as fast.

SELECT * FROM table WHERE DATE(timestamp) = '2012-05-25'
It will work but not used index on "timestamp" column if you have any because of DATE function. below query used index and give better performance
SELECT * FROM table WHERE timestamp >= '2012-05-05 00:00:00'
AND timestamp <= '2012-05-05 23:59:59'
OR
SELECT * FROM table
WHERE timestamp >= '2012-05-05' AND timestamp < '2012-05-06'
Try running these to check stats
explain SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'
explain SELECT * FROM table WHERE timestamp >= '2012-05-05 00:00:00'
AND timestamp <= '2012-05-05 23:59:59'

In case you are using SQL parameters to run the query then this would be helpful
SELECT * FROM table WHERE timestamp between concat(date(?), ' ', '00:00:00') and concat(date(?), ' ', '23:59:59')

When I read your question, I thought your were on Oracle DB until I saw the tag 'MySQL'. Anyway, for people working with Oracle here is the way:
SELECT *
FROM table
where timestamp = to_timestamp('21.08.2017 09:31:57', 'dd-mm-yyyy hh24:mi:ss');

Use
SELECT * FROM table WHERE DATE(2012-05-05 00:00:00) = '2012-05-05'

Let me leave here it may help someone
For people coming from nodejs and expressjs
getDailyIssueOperations(dateName, date, status) {
const queryText = `
select count(*) as total from issues
where date(${dateName})='${date}' and status='${status}';
`;
},
in case date and column name are variables please find the implementation usefull

Related

Selecting from table where timestamp between X doesn't return all rows

I have database table with different records and they all have timestamp with them.
When I want to get a certain month (for example April) records is use following query:
SELECT *
FROM `water`
WHERE timestamp >= DATE_FORMAT('2020-04-01', '%Y-%m-%d')
AND timestamp <= DATE_FORMAT('2020-04-30', '%Y-%m-%d')
AND watercar='JV03'
ORDER by timestamp DESC
It will return me records which timestamp is between 01.04.2020-29.04.2020 but it misses the last day of april 30.04.2020 record.
I also tried >= <= and between operators, same issue although the record does exist.
What am I missing?
DB Fiddle: https://www.db-fiddle.com/f/nWFFZmUt7FM17c98DXRRQw/0
Update your query to this:
SELECT *
FROM `water`
WHERE timestamp between DATE_FORMAT('2020-04-01', '%Y-%m-%d 00:00:00') AND DATE_FORMAT('2020-04-30', '%Y-%m-%d 23:59:59') AND watercar='JV03'
ORDER by timestamp DESC
or
SELECT *
FROM `water`
WHERE DATE(timestamp) between DATE_FORMAT('2020-04-01', '%Y-%m-%d') AND DATE_FORMAT('2020-04-30', '%Y-%m-%d') AND watercar='JV03'
ORDER by timestamp DESC
First, there should be no need to use date_format). MySQL should understand dates in the YYYY-MM-DD format.
Second, do not use between with date/time values. Instead, to get everything in April, use:
where timestamp >= date('2020-04-01') and
timestamp < date('2020-05-01')
This formulation works both when the column as a time component and when it does not. So, I recommend it in all situation.
If you want to pass in the end date as a parameter, you can use:
where timestamp >= :start_dt and
timestamp < :end_dt + interval 1 day

Query MYSQL with a date in the format of 10-OCT-15

I am trying to query a MYSQL database to return all records with today's date -
SELECT *
FROM credit_application
created_on = '15-OCT-15';
But it's failing because of the 'OCT' part within the query. How can I resolve this please?
Use mysql DATE_FORMAT function
SELECT *
FROM credit_application
DATE_FORMAT(created_on,'%d-%b-%y') = '15-OCT-15';
Use mysql STR_TO_DATE function
SELECT *
FROM credit_application
created_on = STR_TO_DATE('15-OCT-15', '%d-%b-%y');
Of course, this assumes your created_on field is just a DATE. If it's actually a DATETIME or TIMESTAMP, then you'll need to do a range query instead:
SELECT *
FROM credit_application
created_on >= STR_TO_DATE('15-OCT-15', '%d-%b-%y') AND
created_on < DATE_ADD(STR_TO_DATE('15-OCT-15', '%d-%b-%y'), INTERVAL 1 DAY);
The other suggestions of using DATE_FORMAT would require the function to be applied to every row in the table, preventing use of any index you might have. It would be a non-sargable query.

Select current months records mysql from timestamp column

I have a mysql DB that has a TIMESTAMP field titled date. How can I select all fields where the month is the current month?
Thanks in advance!
UPDATE
A much better index-friendly way to query your data for a range of dates
SELECT id, FROM_UNIXTIME(timestampfield) timestamp
FROM table1
WHERE timestampfield >= UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY - INTERVAL 1 MONTH)
AND timestampfield < UNIX_TIMESTAMP(LAST_DAY(CURDATE()) + INTERVAL 1 DAY);
Note: You don't apply any function to your column data, but rather do all necessary calculations on the right side of the conditions (which are constants and are evaluated only once post-execution). This way you allow MySQL to benefit from index(es) that you might have on the timestampfield column.
Original answer:
SELECT id, FROM_UNIXTIME(timestampfield) timestamp
FROM table1
WHERE MONTH(FROM_UNIXTIME(timestampfield)) = MONTH(CURDATE())
AND YEAR(FROM_UNIXTIME(timestampfield)) = YEAR(CURDATE())
Note: Although this query produces the correct results it effectively invalidates the proper usage of the index(es) that you might have on the timestampfield column (meaning MySQL will be forced to perform a fullscan)
Here is SQLFiddle demo
Use this query may this help you,
Query = "SELECT * FROM <table_name> WHERE MONTH(date_entered) = MONTH(CURDATE())";
In my opinion, the following is more readable than the accepted answer...
SELECT id, FROM_UNIXTIME(timestampfield) timestamp
FROM table1
WHERE timestampfield >= DATE_FORMAT(NOW(), '%Y-%m-01')
Note: This would select any records from the next month as well. That usually doesn't matter, because none have been created.
If you want indexes to be used, don't apply any function to the column:
SELECT *
FROM tableX
WHERE `date` >= UNIX_TIMESTAMP((LAST_DAY(NOW())+INTERVAL 1 DAY)-INTERVAL 1 MONTH)
AND `date` < UNIX_TIMESTAMP(LAST_DAY(NOW())+INTERVAL 1 DAY) ;
The functions used can be found in MySQL docs: Date and Time functions
try this
SELECT * FROM table WHERE month(data) = EXTRACT(month FROM (NOW()))
SELECT 'data of your choice '
FROM 'your table'
WHERE
MONTH'datecolumn'=MONTH(CURRENT_DATE )
replace text in ' ' with appropriate from your database
SELECT [columns]
FROM [the_table]
WHERE MONTH([date_column]) = MONTH(CURDATE())
Replace the text between [] (including the []) with your data.
The query below can benefit from the index and no functions applied to the timestamp field for where clause evaluation.
SELECT *
FROM TableName
WHERE TimestampField >=
(CURDATE() - INTERVAL (DAY(CURDATE())-1) DAY)
AND TimestampField <
LAST_DAY(CURDATE()) + INTERVAL 1 DAY;
If your timestamp field is time part is truncated, go for this one,
SELECT *
FROM TableName
WHERE TimestampField BETWEEN
(CURDATE() - INTERVAL (DAY(CURDATE())-1) DAY)
AND
LAST_DAY(CURDATE());
As of 2020, you can use BETWEEN to handle the query from the very beginning.
SELECT *
FROM [TABLE]
WHERE [DATE_FIELD]
BETWEEN
CAST('2020-30-01' AS DATE) AND CAST('2020-10-31' AS DATE);
I know is not the most "automatic" way, but from a SQL perspective it is very friendly and straightforward.
Source
https://www.techonthenet.com/mysql/between.php
Try this one it will work better because of the range. You don't need to calculate month and year for every row. It will slow the process. User range for better performance.
SELECT * FROM table WHERE columnName between DATE_FORMAT(current_date() ,'%Y-%m-01') and current_date();
SELECT
*
FROM
tableName
WHERE
EXTRACT(YEAR_MONTH FROM columnName) = EXTRACT(YEAR_MONTH FROM CURDATE())
I think in MySQL here is the simplest method which i have tried and works well, you want to select rows where timestampfield is in this month.
SELECT * FROM your_table
WHERE MONTH(timestampfield)=MONTH(CURRENT_DATE()) AND
YEAR(timestampfield)=YEAR(CURRENT_DATE());
the above will return all records that the timestampfield is this month in MySQL

Select date range on mysql timestamp

I am trying the following but get no results:
SELECT *
FROM users_test
WHERE dateadded >= UNIX_TIMESTAMP('2012-02-01 00:00:00')
AND dateadded < UNIX_TIMESTAMP('2012-11-01 00:00:00');
Yet I know there are columns with dates within that range e.g.
2012-05-11 17:10:08
Is there a better way to do this?
Eventually I want to search multiple parameters, albeit not at the same time, like today, yesterday, last week, last month etc and also a date range and month range
Have you tried?
SELECT *
FROM users_test
WHERE dateadded >= '2012-02-01 00:00:00'
AND dateadded < '2012-11-01 00:00:00'
For what I can see, it seems your table has the data stored in the same way you want to look for it (2012-05-11 17:10:08), so in this case you won't need UNIX_TIMESTAMP.
Also I can see you want to exclude the 2nd date from results (because you're using < instead of <=), otherwise using WHERE dateadded BETWEEN '2012-02-01 00:00:00' AND '2012-11-01 00:00:00' would be fine as well...
Just use the SQL BETWEEN keyword. That's all.
try this:
SELECT * FROM
users_test
WHERE
dateadded BETWEEN '2012-02-01 00:00:00' AND '2012-11-01 00:00:00'
SELECT * FROM table_name WHERE DATE(date_field) between '2015-05-10' and '2015-05-21`

how to test date and datetime with mysql

My table is using a datetime (YYYY-MM-DD HH:MM:SS) and i need to display today's entries.
my code is only :
SELECT *
FROM table
WHERE date = '$date'
ORDER BY score DESC
with
$date = date("Y-m-d");
well, as expected it doesnt work :| you guys have a solution here ?
Following from Pascal Martin, you could extract the date part from the date+time field:
SELECT * FROM table WHERE DATE(date) = '2009-12-19'
Source: MySQL - Date and Time Functions
Be aware however, that this query will not use an index on your date+time field, if you will be having one. (Stack Overflow: How does one create an index on the date part of DATETIME field in MySql)
Your date is "2009-12-19" (or something like that, depending on the day), which is interpreted as "2009-12-19 00:00:00".
In your database, you probably don't have any date that's exactly equal to that one, by the second : your dates are like "2009-12-19 12:15:32".
A solution is to compare like this :
select *
from table
where date >= '2009-12-19'
and date < '2009-12-20'
Which will be interpreted as :
select *
from table
where date >= '2009-12-19 00:00:00'
and date < '2009-12-20 00:00:00'
And, if you don't want to do the math to get the date of the following date, you can use the adddate function :
select *
from table
where date >= '2009-12-19'
and date < adddate('2009-12-19', interval 1 day)
So, in your case, something like this should do the trick :
select *
from table
where date >= '$date'
and date < adddate('$date', interval 1 day)
order by score desc
You probably want to format the data when you select it:
SELECT *, DATE_FORMAT(date, '%Y-%m-%d') AS dateformat FROM table
WHERE dateformat = '$date' ORDER BY score DESC
You are comparing datetime and date expression, that is why its not working. Use Date() method to return the date part from datetime and then do the comparison. WHERE DATE(date) = '$date' should do. You might have to use aliases to handle this name collision.