Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding the latest date of 2 date columns in SQL
    primarykey
    data
    text
    <p>I'm having trouble finding a solution to the following SQL query:</p> <p>I have a table that contains 2 date columns: <code>PurchaseDate</code> and <code>RefundDate</code></p> <p>I have a <code>StartDate</code> and <code>EndDate</code> that defines the date range for the query.</p> <p>I want to restrict the query by either the <code>PurchaseDate</code> OR the <code>RefundDate</code> whichever is <strong>earliest</strong>. Also either date can be null.</p> <p>So if PurchaseDate is 18.Nov.2013 and RefundDate is 03.Dec.2013 then I want to use <code>PurchaseDate</code> in the <code>where</code> clause to restrict the result set within the <code>startDate</code> and <code>EndDate</code></p> <p>Another example, is if PurchaseDate is 01.Aug.2013 and RefundDate is 19.May.2013 then I would want to use RefundDate in the where clause.</p> <p>This is what I've got so far but it's not correct, I need to select whichever is the earliest of the 2 dates to restrict the where clause:</p> <pre><code>SELECT OrderID, AddressID, PurchaseDate, RefundDate FROM Orders WHERE (PurchaseDate IS NOT NULL AND PurchaseDate &gt;= @queryStartDate AND PurchaseDate &lt;= @queryEndDate) OR (RefundDate IS NOT NULL AND RefundDate &gt;= @queryStartDate AND RefundDate &lt;= @queryEndDate) </code></pre> <p>I thought about using <code>COALESCE</code> but this won't work as it will just pick the first date that is non-null rather than the earliest.</p> <p>I think I'm going to have to do two queries and union them but it feels like there is a better way and I can do it with one query and some clever magic in the where clause....</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload