MySQL Question: ORDER BY /// DATEDIFF

MySQL

There's two columns dateRequested and dateCompleted in DATE type and I want to select only 4 of the rows with the least time between the two.

SELECT *, DATEDIFF(dateCompleted,dateRequested) AS Time
FROM ticket
ORDER BY Time;

With the above statement I get what I want but since there are nulls and in the case of the question for the sake of a challenge I guess there is negative time between the two so I really only want those where Time >= 0

Example of what I get with above statement

I've tried with a CASE statement but I don't fully grasp that yet so any help would be appreciated.

Thanks

Best Answer

In this case I would use a where clause to further qualify the data you are getting back in this case something like:

SELECT *, DATEDIFF(dateCompleted,dateRequested) AS Time
FROM ticket
WHERE ((dateCompleted IS NOT NULL) AND (dateRequested IS NOT NULL)) 
ORDER BY Time;

Since you said you are also trying to return only 4 rows you should use LIMIT 4 in your query, however I'm not sure if that would go before or after your ORDER BY.

If you have tried some things, let us know what you have already tried and what the errors are, this can help prevent people from reinventing the wheel and get your problem fixed faster.