Filter by datetime MYSQL formatting - mysql

I have a Mysql Table that is used for a log file on the that table there is a field called 'log_date' And it stores the date in the following format( %Y-%m-%d %H:%i.%s ).On the DB the dates look like something this 2013-20-05 00:00.00. Lets say today's date is 2013-20-05 And I have log files from 2013-01-01 to present day. If I run a query like this:
SELECT * FROM log_table
WHERE STR_TO_DATE(log_date, '%Y-%m-%d %H:%i.%s') < '2013-05-05 00:00.00'
This is returning every row in the DB including rows that are greater than 2013-05-05 00:00.00
And if I reverse the < (less then) to a > (greater then) with a query that looks like this:
SELECT * FROM log_table
WHERE STR_TO_DATE(log_date, '%Y-%m-%d %H:%i.%s') > '2013-05-05 00:00.00'
Then it returns ZERO rows. I think the time stamp is what is causing the problem I have worked with the date format before but not the DateTime format. Why is this happening?

log_date should be of DateTime data type. It is much simpler to use MySQL DATE function. Some examples
SELECT * FROM log_table
WHERE DATE(log_date) < '2013-05-05'
SELECT * FROM log_table
WHERE DATE(log_date) > '2013-05-05'
SELECT * FROM log_table
WHERE DATE(log_date) BETWEEN '2013-04-05' AND '2013-05-05'
SELECT * FROM log_table
WHERE DATE(log_date) BETWEEN DATE(CURRENT_DATE() - INTERVAL 2 WEEK) AND
DATE(CURRENT_DATE() + INTERVAL 4 DAY)

You can try with that..
WHERE DATE_FORMAT(AUCTION_DATE, '%Y%m%d') >= DATE_FORMAT('2013/5/18', '%Y%m%d')
You can also get today date using now() function.

Related

Get users that have payment due in one day sql

This is probably easy to do but I can't seem to get my head around it. I have a user table that has a next_payment DATETIME column which gets update every month. I would like a query to get all the users where their next_payment DATETIME is in one day from the current datetime.
I tried something like this but it also gets me users where their next_payment is due in like 15 minutes. Not good
SELECT * FROM users WHERE next_payment >= NOW() AND next_payment <= NOW() + INTERVAL 1 DAY
I also tried something like this but this doesn't work either as it gives me all users that had next_payment datetime like 2 or 3 months ago (Not good).
SELECT * FROM users WHERE next_payment <= NOW() + INTERVAL 1 DAY
Thanks in advance for any help
Need to Cast the datetime field to date so you can include all data within the period and use between
SELECT * FROM
users
WHERE
cast(next_payment as date)
between cast(NOW() as date)
AND cast(NOW() + INTERVAL 1 DAY as date)
DATEDIFF works fine in MySQL:
SELECT
*
FROM
users
WHERE
DATEDIFF(next_payment, NOW()) = 1
SQL Fiddle for this example.
I would use:
SELECT * FROM users
WHERE TIMESTAMPDIFF(HOUR,NOW(),next_payment) <= 24

Retrieve data of last month uploads

I'm trying to retrieve some data from a database using MySQL. I would like to SELECT just the records that I uploaded in the last month and not the previous ones. This script has to be dynamic : I mean that on 1st of February it should retrieve data from 1st of January to 1st of February and so on.
My table structure is really simple : the upload date is stored in the column 'reg_date' that is a TIMESTAMP type.
Does anyone know how to do this in a single query? Thanks!
This can all be done in a single SQL query using the CURDATE() and INTERVAL functions so no PHP date calculation is required.
SELECT *
FROM `TABLE`
WHERE `reg_date` BETWEEN CURDATE() - INTERVAL 1 MONTH AND CURDATE()
You can filter the data like so:
select *
from your_table
where reg_date between date_sub(curdate(), interval 1 month) and curdate()
just use this query:
select * from your_table_name where reg_date between '2017-03-01' and '2017-03-31';

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

Getting MySQL data after specific date

How can I fetch MySQL data after a specific timestamp? What should the query look like?
mysql_query("SELECT * FROM table where TheNameOfTimestampColumn > than the date");
SELECT * FROM table WHERE TheNameOfTimestampColumn > '2009-01-28 21:00:00'
SELECT * FROM table WHERE TheNameOfTimestampColumn > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 DAY)
You can select this by :
select * from table_name where date_column > "2001-01-01 00:00:00"
or if you need data within certain time frame then you can try using between key word such as:
select * from table_name where date_column
between "2018-01-04 00:00:00" and "2018-01-04 11:59:59";
Note that date format should be in YYYY-MM-DD HH:MM:SS
If you're using a unix timestamp, you can do the following:
SELECT * FROM table WHERE TheNameOfTimestampColumn > FROM_UNIXTIME(your_time_stamp_here)
You can use MySQL DATE function like below
For instance, if you want results after 2017-09-05
SELECT DATE(timestamp_field) as date FROM stocks_annc WHERE DATE(timestamp_field) >= '2017-09-05'
Make sure to wrap the date within single quotation ''
Hope this helps.