views:

135

answers:

2

I could use this query to select all orders with a date on a monday:

SELECT * from orders WHERE strftime("%w", date)="1";

But as far as I know, this can't be speed up using an index, as for every row strftime has to be calculated.

I could add an additional field with the weekday stored, but I want to avoid it. Is there a solution that makes use of an index or am I wrong and this query actually works fine? (That means it doesn't have to go through every row to calculate the result.)

+1  A: 

If you want all Mondays ever, you'd need a field or sequential scan. What you could do, is calculate actual dates for example for all Mondays within a year. The condition WHERE date IN ('2009-03-02', '2009-02-23', ...) would use index

vartec
Wouldn't that be just as expensive as going through every table entry?
Georg
Not at all. There would be a lot fewer Mondays, then rows in the table. Moreover, those dates can be cached or stored.
vartec
It would use the index, assuming you have one, because you are dealing with complete dates.
anon
+1  A: 

Or as an alternative to vartec's suggestion, construct a calendar table consisting only of a date and a day name for each day in the year (both indexed) and then perform your query by doing a JOIN against this table.

anon