tags:

views:

185

answers:

2

I have a database with a bunch of dates. I would like to, given a date, get the next date in the database and previous date in the database.

So given a databse with 10/10/09, 10/12/09, and 10/15/09, if someone enters the date 10/13/09, it should return 10/12/09 as the previous date and 10/15/09 as the next date.

How can I do this? Thanks!

+4  A: 

You can do this easily using two queries:

-- get previous date
SELECT MAX(DateField) WHERE DateField < '2009-10-13';
-- get next date
SELECT MIN(DateField) WHERE DateField > '2009-10-13';

If you have an index on DateField, then this query will also be very efficient.

too much php
+4  A: 

You can also use this to easily return the entire record rather than just the date.

-- Get previous date row
SELECT TOP 1 OrderDate, ... FROM Table WHERE OrderDate < @MyDate ORDER BY OrderDate DESC
-- Get Next date row
SELECT TOP 1 OrderDate, ... FROM Table WHERE OrderDate > @MyDate ORDER BY OrderDate

Note that the previous orders by the date in descending order where as the next orders by ascending order.

Peter Oehlert
+1 Beat me to it. This is really a better method because you can get other fields associated with those dates if desired, and the performance is otherwise identical.
harpo
The question is tagged as _mysql_, which would require `LIMIT` instead of `TOP`.
Alex Barrett
How could you do the same thing if you were only given the year or only the year and month?
Binarytales
@BinaryTales, I'm not quite sure what your asking. If you only had stored the year and month as ints in the table you could do the same thing. Of course, because these are far less descriptive you're going to get some indeterminism. Something like:SELECT TOP 1 OrderYear, OrderMonth, ... FROM Table WHERE OrderYear < DATEPART(yy, @MyDate) AND OrderMonth < DATEPART(mm, @MyDate) ORDER BY OrderYear, OrderMonth
Peter Oehlert