Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete mysql record older than 30 days

How to delete mysql record older than 30 days? my code will delete all the records even which are inserted yesterday.

require('../conn_db.php');
mysql_select_db("my_news",$conn);
mysql_query("SET NAMES utf8");
mysql_query("DELETE FROM my_news WHERE date < DATE_SUB(NOW(), INTERVAL 1 MONTH)");
mysql_close("my_news");

And mysql table

date int(10)
1321095600
1322107200
...
1328288400
1328290440
like image 592
fish man Avatar asked Mar 16 '12 09:03

fish man


People also ask

Can we use limit in delete query in MySQL?

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the condition in the WHERE clause. You cannot use ORDER BY or LIMIT in a multiple-table DELETE .

How do I delete multiple records in MySQL?

Another way to delete multiple rows is to use the IN operator. DELETE FROM table_name WHERE column_name IN (value 1, value 2, value 3, etc...); If you want to delete all records from the table then you can use this syntax.

How do I delete a specific number of rows in MySQL?

To delete rows in a MySQL table, use the DELETE FROM statement: DELETE FROM products WHERE product_id=1; The WHERE clause is optional, but you'll usually want it, unless you really want to delete every row from the table.

What is dob in MySQL?

MySQL uses yyyy-mm-dd format for storing a date value. This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want.


2 Answers

First off, if you really want to delete records older than 30 days, use INTERVAL 30 DAY instead, when you use INTERVAL 1 MONTH you will delete records added on Mars 31st, when it's April 1st.

Also, your date-column is of type int, and DATE_SUB() will return a date in this format YYYY-MM-DD HH:MM:SS, so they are not comparable. You could do this to work around that problem:

DELETE FROM my_news WHERE date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY))
like image 87
professorsloth Avatar answered Sep 19 '22 15:09

professorsloth


Your MySQL Table does not store a date, but rather a unix timestamp (judging from the data you have provided). To delete do the following:

mysql_query("DELETE FROM my_news WHERE date < ".strtotime('-1 month'));
like image 31
clops Avatar answered Sep 22 '22 15:09

clops