0

I have table like below,

Order_id      Created_Date       Approved_Date
_______________________________________________
1              2016-08-01         2016-08-05
2              2016-07-01         2016-07-04
3              2016-06-01         NULL


Select * from table1 where Approved_date between '2016-05-01' and '2016-08-31'

If the Approved_date is NULL, it should consider Created_date dynamically.

2 Answers 2

1
Select * from table1 
where coalesce(Approved_date, Created_Date) between '2016-05-01' and '2016-08-31'

or to keep making use of indexes

Select * from table1 
where 
(
   Approved_date is not null 
   and Approved_date between '2016-05-01' and  '2016-08-31'
)
or 
(
   Approved_date is null 
   and Created_Date between '2016-05-01' and  '2016-08-31'
)
Sign up to request clarification or add additional context in comments.

1 Comment

You've mixed up the dates in your second query. (And I doubt that SQL Server would use an index for that query, but it may be worth a try. A pity that SQL Server doesn't support function indexes where you would simply index coalesce(approved_date,created_date).)
0

Use COALESCE:

SELECT t1.Order_id,
       t1.Created_Date,
       COALESCE(t1.Approved_Date, t1.Created_Date)
FROM table1 t1
WHERE Approved_date BETWEEN '2016-05-01' AND '2016-08-31'

From the documentation:

Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.

In other words, in the above query Approved_Date will be used if it be not NULL, otherwise it was fallback to the Created_Date.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.