3

I need to MySQL write a query where it retrieves all rows where the unix timestamp field ("added_on") is more than 6 months old.

5 Answers 5

7
SELECT *
FROM yourtable
WHERE added_on <= UNIX_TIMESTAMP(DATE_SUB(now(), INTERVAL 6 MONTH))
Sign up to request clarification or add additional context in comments.

Comments

2
SELECT * FROM mytable WHERE added_on < (NOW() - (6 * 30 * 24 * 60 * 60));

Comments

2

MySQL's DATE_ADD() (aka DATE_SUB) function provides your functionality :

     SELECT * FROM table WHERE DATE_ADD(FROM_UNIXTIME(added_on), INTERVAL 6 MONTH) > NOW()

... and is quite readable :-)

Comments

2
select * from table
where now() - interval 6 month > from_unixtime(added_on)

Comments

1
SELECT * FROM foobar WHERE added_on < UNIX_TIMESTAMP() - 15778463

This isn't exactly 6 months, as its a bit different every year, but it should be close enough for every purpose (converted to seconds by Google)

You can also convert the UNIX timestamp to a "real" timestamp and use MySQL's date/time functions on it, which'll probably be more accurate and looks prettier than having an 15778463 integer hardcoded to the query (you can use INTERVAL 6 months), but it'll also be much slower than working with plain integers.

3 Comments

To allow usage of indexes do WHERE added_on < UNIX_TIMESTAMP() - 15778463 instead
Updated. I'm used to postgres, who can still understand it and use the index
THa'd explain why you think working with 'plain integers' would be much slower than working with plain integers (a.k.a 'real timestamp')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.