0

Given a table with a column that contains a timestamp, I would like to count the number of instances where the TIMEDIFF(now(), timeStamp) is greater than some value. The issue I ran into is implementing this all into a statement. My efforts:

SELECT COUNT*()
FROM sometable
WHERE (SELECT TIMEDIFF(now(),column_from_sometable) > 10

I'm just not quite sure how to use the TIMEDIFF in the where statement to use it for a comparison. (Apparently you must use SELECT to call the method, and then I'm just not sure how to access the column from sometablein that statement).

1
  • Is COUNT*() a typo? Did you mean COUNT(*)? Commented Jul 10, 2014 at 19:33

1 Answer 1

2

You don't need a sub select provided the column column_from_sometable belong to same table sometable. You can dimply include in WHERE condition like

SELECT COUNT(*)
FROM sometable
WHERE TIMEDIFF(now(),column_from_sometable) > 10

You can as well simplify this by adding the condition in your aggregate function like

SELECT SUM(CASE WHEN TIMEDIFF(now(),column_from_sometable) > 10 THEN 1 ELSE 0 END)
FROM sometable
Sign up to request clarification or add additional context in comments.

4 Comments

I think the first is simpler. I think the key is: In order to output a result set, you need a SELECT somewhere. The examples for TIMEDIFF() use a SELECT just to get a simple result set without using a table. Within a query, you can use the function without putting SELECT in front of it.
@MarcusAdams, that correct but I have seen many people (Here in SO) prefer the 2nd option rather :)
@Rahul If there's no difference in performance I prefer code that's easier to understand. Most times it's code with a few lines more. So I agree with Marcus (+1 for both)
That was a typo indeed. Thank you for your solution, that is what I needed!

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.