tags:

views:

436

answers:

2

is there a simpler way than writing:

select date_sub(curdate(), interval WEEKDAY(curdate()) day) as LastMonday
from dual

A: 

I think that that is as simple as you will get it.

Jambobond
+4  A: 

If you're not using an ancient MySQL, you can wrap this in a stored function.

CREATE FUNCTION `LastMonday`() RETURNS DATETIME    
  RETURN DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) ;

and then call

select LastMonday() as LastMonday

Update:

If you're having performance problems, you can persist the value in a session variable. That way you can be sure that it will only be calculated once.

set @LastMonday=LastMonday();
select @Lastmonday;

(in this simple query it makes no difference of course...)

Wouter van Nifterick
that's exactly how I had "avoided" the long looking date calculations up to now ... I was/am worried about potential overhead ...
lexu
I've since added your "performance update" suggestion to our codebase. It makes a huge difference, somehow I'd expected the function be called only once .. (but how is the optimizer to know I'm not returning time in milliseconds ..)
lexu
The trick here is that the value is calculated once and then cached manually. You could try what the optimizer does. It might be smart enough to cache it too, but you can't really rely on it.
Wouter van Nifterick