Truncate table with date time older than n days - mysql

I want to truncate some records from a table with date time clause.
This link have a solution, but it's not working for me.
TRUNCATE TABLE 'meter_to_sim_mapping' WHERE 'meter_to_sim_mapping'.'mapped_at' <=
In above where clause I want to add the date time value. The value is 2018-04-02 16:03:52. The query should delete all the records prior to this date.
How can I truncate the table with date-time?
Any help would be highly appreciated.

You need to use DELETE
DELETE FROM TABLE_NAME
WHERE DATE_COLUMN < NOW() - INTERVAL N DAY
or
DELETE FROM TABLE_NAME
WHERE CAST(DATE_COLUMN AS DATE) < STR_TO_DATE('1-01-2012', '%d-%m-%Y') - INTERVAL N DAY
In place of NOW() You can use your datetime value
STR_TO_DATE('12-01-2014 00:00:00','%m-%d-%Y %H:%i:%s')
Demo
http://sqlfiddle.com/#!9/4607a6/1

Below example may work for you:
DELETE FROM TABLE_NAME
WHERE DATE_COLUMN = DATE_SUB("2018-04-02 16:03:52", INTERVAL 10 DAY);
You can change it accordingly as per your requirement.
Reference: MySQL DATE_SUB() Function

Related

Get records for last 2 days

I am trying to create a query to get the records for last two days. In my table there is a field called dates. Values are as below:
05-08-2018 08:05:22
05-08-2018 10:15:42
dd-mm-yyyy hh:ii:ss
I have created the query.
SELECT id,title,description, dates
FROM post_feed where `dates` BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE()
ORDER BY dates DESC LIMIT 100
When I run the query it return 0 records. It looks like issue with date format.
Seems like your dates are stored as varchar. You must convert them to date (e.g. by using STR_TO_DATE) before you can perform any comparison.
Assuming for example that today is Aug-05 and you want results for Aug-04 and 05 (inclusive):
SELECT id, title, description, dates
FROM post_feed
WHERE STR_TO_DATE(dates, '%d-%m-%Y') BETWEEN CURRENT_DATE - INTERVAL 1 DAY AND CURRENT_DATE
ORDER BY dates DESC
LIMIT 100
SQL Fiddle
Try this WHERE clause:
WHERE STR_TO_DATE(dates, '%d-%m-%Y %H:%i:%s') BETWEEN DATE_ADD(CURDATE(), INTERVAL -2 DAY) AND CURDATE()
Your second date is before your first date. Put greater date at first place & put lesser date at second place.
SELECT id,title,description, dates
FROM post_feed where CAST(`dates`as date) BETWEEN CURDATE() AND CURDATE() - INTERVAL 1 DAY
ORDER BY dates DESC LIMIT 100
Fix your data! Your query doesn't work because the "date" value are stored as text/varchar. This is easily fixed:
update post_feed
set dates = str_to_date(date, '%Y-%m-%d %H:%i:%s')
alter table post_feed
modify column datetime;
Voila! Your queries will now work.

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 reduce one day in existing date column in mysql database?

I have table tbl_dtcount. In that table there is one column for date.
Now I need to reduce one day for each and every rows in that date field. The date is beginning from 2012-05-19 to 2012-07-03. What is the MySQL update statement to perform this?
How about this.
Update tbl_dtcount
set mydate = DATE_SUB(mydate, INTERVAL 1 DAY)
where <conditions>;
UPDATE table_name
SET date_column = DATE_SUB('1998-01-02', INTERVAL 1 DAY)
....
see detail MySQL DATE_SUB

mysql date_sub using a field as interval

I need help with mysql and date_sub(). I have a table call Activity
Activity(id,deadline,alert)
Activity(1,'2011-04-18','1 DAY');
Activity(2,'2011-04-13','1 MONTH');
Every row in A have an 'alert', this field indicate how time before the deadline an activity have to reported.
For example
On 2011-04-17 I have to report the activity with 'id' 1
On 2011-03-14 I have to report the activity with 'id' 2
I trying to use date_sub() functions, but I can't use a field as params of this function. Any idea how to fix this?
SELECT *
FROM `activities`
WHERE date_sub(`deadline`, INTERVAL alert) >= CURDATE();
Split the alert into 2 fields
Alert_count: integer
Alert_period: enum('hour','day','month','week')
And change the query like so:
SELECT *
FROM `activities`
WHERE CASE alert_period
WHEN 'hour' THEN date_sub(`deadline`, INTERVAL alert_count HOUR) >= CURDATE();
WHEN 'day' THEN date_sub(`deadline`, INTERVAL alert_count DAY) >= CURDATE();
...
END CASE
If the number of alerts is small, you could write out a case:
WHERE case
when alert = '1 DAY' then date_sub(`deadline`, INTERVAL 1 DAY)
when alert = '1 MONTH' then date_sub(`deadline`, INTERVAL 1 MONTH)
... etc ...
end >= CURDATE();
Although this solution will work it's not the most efficient way of storing this data because each time you query for this data MySQL must look at the interval value in every row, compute it against deadline date and then return you the answer.
If you were to compute this information just before you insert the data and store alert_date as a DATE column then (assuming you index it too) it'd be very fast for MySQL to find the rows with a query like:
SELECT id FROM activity WHERE alert=CURRENT_DATE();
even more efficient (it'd allow it to be query cached):
SELECT id FROM activity WHERE alert="2011-04-23";
Strings are not allowed after INTERVAL, you can convert your all alert limit to day on one column.
Activity(id,deadline,alert)
Activity(1,'2011-04-18','1');
Activity(2,'2011-04-13','30');
and use as:
SELECT *
FROM `activities`
WHERE date_sub(`deadline`, INTERVAL alert DAY) >= CURDATE();

Select mysql query between date?

How to select data from mysql table past date to current date? For example, Select data from 1 january 2009 until current date ??
My column "datetime" is in datetime date type. Please help, thanks
Edit:
If let say i want to get day per day data from 1 january 2009, how to write the query? Use count and between function?
select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()
or using >= and <= :
select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()
All the above works, and here is another way if you just want to number of days/time back rather a entering date
select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
You can use now() like:
Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();
Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59) on the end date or you won't get any results from that day, i.e.:
This WILL include records from 2019-12-02:
SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'
This WON'T include records from 2019-12-02:
SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'