Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WHERE clause with BETWEEN and null date parameters

Tags:

sql

sql-server

One of my WHERE clauses is the following:

AND (DateCreated BETWEEN @DateFrom and @DateTo OR (@DateFrom IS NULL OR @DateTo IS NULL))

@DateFrom and @DateTo are input parameters that may be NULL.

If they are both null, then I need to basically ignore the BETWEEN and return all records.

If @DateFrom is NULL, but @DateTo is NOT NULL, then I need to return all records with DateCreated being no greater than @DateTo (inclusive).

If @DateFrom is NOT NULL, but @DateTo is NULL, then I need to return all records with DateCreated being no earlier than @DateFrom (inclusive) up to today's date.

DateCreated is not a null or some time it is null field.

So far my WHERE clause is not working exactly like I want.

like image 566
gooseman Avatar asked Feb 11 '15 16:02

gooseman


People also ask

Can we use null in where clause?

Null values can be used as a condition in the WHERE and HAVING clauses. For example, a WHERE clause can specify a column that, for some rows, contains a null value.

Can you use between with dates SQL?

The SQL BETWEEN OperatorThe values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.

Can we use datediff in where clause?

Note: DATEADD and DATEDIFF SQL function can be used in the SELECT, WHERE, HAVING, GROUP BY and ORDER BY clauses.

Can we insert null in date column?

"NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement. Example: CREATE table test1 (col1 date); INSERT into test1 values (NULL);


2 Answers

Just need some extra criteria to handle when one or the other is NULL:

AND (
    (DateCreated >= @DateFrom and DateCreated < DATEADD(day,1,@DateTo)) 
 OR (@DateFrom IS NULL AND @DateTo IS NULL)
 OR (@DateFrom IS NULL AND DateCreated < DATEADD(day,1,@DateTo))
 OR (@DateTo IS NULL AND DateCreated >= @DateFrom)
    )

Edit: Giorgi's approach was simpler, here it is adapted for use with DATETIME:

AND (       (DateCreated >= @DateFrom OR @DateFrom IS NULL) 
        AND (DateCreated < DATEADD(day,1,@DateTo) OR @DateTo IS NULL)
    )

The issue with BETWEEN or <= when using a DATE variable against a DATETIME field, is that any time after midnight on the last day will be excluded.

'2015-02-11 13:07:56.017' is greater than '2015-02-11' Rather than casting your field as DATE for comparison, it's better for performance to add a day to your variable and change from <= to <.

like image 74
Hart CO Avatar answered Oct 04 '22 17:10

Hart CO


Try this:

WHERE ((DateCreated >= @DateFrom OR @DateFrom IS NULL) AND (DateCreated =< @DateTo OR @DateTo IS NULL))
like image 45
Giorgi Nakeuri Avatar answered Oct 04 '22 16:10

Giorgi Nakeuri