Datetime equal or greater than today in MySQL - mysql

What's the best way to do following:
SELECT * FROM users WHERE created >= today;
Note: created is a datetime field.

SELECT * FROM users WHERE created >= CURDATE();
But I think you mean created < today
You can compare datetime with date, for example: SELECT NOW() < CURDATE() gives 0, SELECT NOW() = CURDATE() gives 1.

SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())
Read more:
http://www.tomjepson.co.uk/tutorials/36/mysql-select-where-date-today.html

SELECT * FROM users WHERE created >= NOW();
if the column is datetime type.

Answer marked is misleading. The question stated is DateTime, but stated what was needed was just CURDATE().
The shortest and correct answer to this is:
SELECT * FROM users WHERE created >= CURRENT_TIMESTAMP;

If 'created' is datetime type
SELECT * FROM users WHERE created < DATE_ADD(CURDATE(), INTERVAL 1 DAY);
CURDATE() means also '2013-05-09 00:00:00'

If the column have index and a function is applied on the column then index doesn't work and full table scan occurs, causing really slow query.
Bad Query; This would ignore index on the column date_time
select * from users
where Date(date_time) > '2010-10-10'
To utilize index on column created of type datetime comparing with today/current date, the following method can be used.
Solution for OP:
select * from users
where created > CONCAT(CURDATE(), ' 23:59:59')
Sample to get data for today:
select * from users
where
created >= CONCAT(CURDATE(), ' 00:00:00') AND
created <= CONCAT(CURDATE(), ' 23:59:59')
Or use BETWEEN for short
select * from users
where created BETWEEN
CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59')
Tip:
If you have to do a lot of calculation or queries on dates as well as time, then it's very useful to save date and time in separate columns. (Divide & Conquer)

SELECT * FROM users WHERE created >= now()

The below code worked for me.
declare #Today date
Set #Today=getdate() --date will equal today
Select *
FROM table_name
WHERE created <= #Today

SELECT * FROM table_name WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING(json_date, 3, 2 ) ) >= NOW();
json_date ["05/11/2011"]

you can return all rows and than use php datediff function inside an if statement, although that will put extra load on the server.
if(dateDiff(date("Y/m/d"), $row['date']) <=0 ){
}else{
echo " info here";
}

Related

Fetch date where date time greater than current date time [duplicate]

What's the best way to do following:
SELECT * FROM users WHERE created >= today;
Note: created is a datetime field.
SELECT * FROM users WHERE created >= CURDATE();
But I think you mean created < today
You can compare datetime with date, for example: SELECT NOW() < CURDATE() gives 0, SELECT NOW() = CURDATE() gives 1.
SELECT * FROM myTable WHERE DATE(myDate) = DATE(NOW())
Read more:
http://www.tomjepson.co.uk/tutorials/36/mysql-select-where-date-today.html
SELECT * FROM users WHERE created >= NOW();
if the column is datetime type.
Answer marked is misleading. The question stated is DateTime, but stated what was needed was just CURDATE().
The shortest and correct answer to this is:
SELECT * FROM users WHERE created >= CURRENT_TIMESTAMP;
If 'created' is datetime type
SELECT * FROM users WHERE created < DATE_ADD(CURDATE(), INTERVAL 1 DAY);
CURDATE() means also '2013-05-09 00:00:00'
If the column have index and a function is applied on the column then index doesn't work and full table scan occurs, causing really slow query.
Bad Query; This would ignore index on the column date_time
select * from users
where Date(date_time) > '2010-10-10'
To utilize index on column created of type datetime comparing with today/current date, the following method can be used.
Solution for OP:
select * from users
where created > CONCAT(CURDATE(), ' 23:59:59')
Sample to get data for today:
select * from users
where
created >= CONCAT(CURDATE(), ' 00:00:00') AND
created <= CONCAT(CURDATE(), ' 23:59:59')
Or use BETWEEN for short
select * from users
where created BETWEEN
CONCAT(CURDATE(), ' 00:00:00') AND CONCAT(CURDATE(), ' 23:59:59')
Tip:
If you have to do a lot of calculation or queries on dates as well as time, then it's very useful to save date and time in separate columns. (Divide & Conquer)
SELECT * FROM users WHERE created >= now()
The below code worked for me.
declare #Today date
Set #Today=getdate() --date will equal today
Select *
FROM table_name
WHERE created <= #Today
SELECT * FROM table_name WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) , '-', SUBSTRING( json_date, 7, 2 ) , '-', SUBSTRING(json_date, 3, 2 ) ) >= NOW();
json_date ["05/11/2011"]
you can return all rows and than use php datediff function inside an if statement, although that will put extra load on the server.
if(dateDiff(date("Y/m/d"), $row['date']) <=0 ){
}else{
echo " info here";
}

How to append timestamp to mysql time returned by curdate()?

In Mysql, we have a function `
curdate()
` which returns today's date.
i.e when execute
select curdate();
it returns date as,
2018-06-22
I want to append the time stamp to this date like
hh:mm:ss
How can I do it? Please help me.
I want to query database with attached timestamp.
something like this,
select * from user where user_created_on >= (curdate() 00:00:00)
timestamp is
00:00:00.
Just concatenate time section:
SELECT * FROM user WHERE user_created_on >= CONCAT(CURDATE(), ' 00:00:00');
select * from user where user_created_on >= getdate()
or
select * from user where user_created_on >= now()
both of these will have that timestamp with hours,mins, and seconds
ps: there is a curtime() that gets the timestamp as well as convert(varchar, curdate(), 108) will too :)
if you want all hours of the day you can use
where data_inicio between (CONCAT(CURDATE(), ' 00:00:00')) and (CONCAT(CURDATE(), ' 23:59:59'));

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

How to compare timestamp dates with date-only parameter in 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

Retrieve rows less than a day old

I have a column date, which has a default value of CURRENT_TIMESTAMP, eg: 2011-11-16 15:34:02. Is there any way to put a condition in the mysql statement (not in php) to retrieve rows which are less than a day old? Something like:
SELECT * FROM orders where date > 24 hours ago
You can use timestampadd() to get the timestamp for 24 hours ago
SELECT * FROM orders WHERE `date` > timestampadd(hour, -24, now());
This is equivalent to
SELECT * FROM orders WHERE `date` > timestampadd(day, -1, now());
SELECT *
FROM orders
WHERE DATE(`date`) = DATE(NOW() - INTERVAL 1 DAY)
Note the backticks around date, as it's a reserved word.
yup, combine *date_sub* with interval 1 day and curdate() and maybe something else
see documentation here http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub
This statement returns all today's rows:
select * from orders where date_field >= CURDATE();
CURDATE() returns today's date, so searches the records starting from midnight.
You can use also the difference directly with timestampdiff function witch is similar to timestampadd.
SELECT * FROM orders WHERE TIMESTAMPDIFF(HOUR, date, NOW()) > 24;
I think this can't as optimized as using timestampadd (because it calculate the difference for each row) but it's, in my opinion, more readable and an alternative if you don't care about optimizing.