Discussion Locked

Date range search SQL query in MS SQL Se

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
I am looking for the SQL query for performing search by using a condition in which I have "Date" as a column name and datatype is "datetime" in the database. My search criteria is date range ("from" date and "to" date).

6 replies

by medievaldude

In this example, I'll use 5/1/2002 as my "from" date and 5/13/2002 as my "to" date

SELECT *
FROM mytable
WHERE [Date] >= '05/01/2002'
AND [Date] <= '05/13/2002'

by medievaldude

This query will include both 5/1/2002 and 5/13/2002 in the final result set. If you want to exclude them, drop both = signs, rendering it like this:
WHERE [Date] > '05/01/2002'
AND [Date] < '05/13/2002'

by shanghai sam

Medievaldude is correct but to avoid issues to do with date formats I use a 3 letter abbreviation for the month e.g.

SELECT *
FROM mytable
WHERE [Date] >= 'May/01/2002'
AND [Date] <= 'May/13/2002'

There can be issues to do with the SQL parser guessing the format of a numerical date with random results

This discussion is closed to new replies.