'How to select records by max of 3 possibly undefined properties in Cosmos DB using SQL

In a Cosmos DB container I have documents with 3 properties related to expiry dates, each of which can be undefined or null.

I need to select all the items where either

  • All expiry dates are undefined or null
  • The max of the expiry dates with values is after the current time.

I have it working with the query below, but it feels very "brute force" and there must be a better way of doing it.

In particular to pick the max expiry date to do the comparison with. I'm using nested ternary operators, which provide a default value if the the date is null or not defined, and then picks which of the 3 to use.

-- let through any with no expiry dates
(
 (NOT IS_DEFINED(c.expiryDate) OR IS_NULL(c.expiryDate)) AND
 (NOT IS_DEFINED(c.otherExpiryDate) OR IS_NULL(c.otherExpiryDate)) AND
 (NOT IS_DEFINED(c.child.expiryDate) OR IS_NULL(c.child.expiryDate))
) 
OR
-- let through any where the max of the 3 expiry date columns is after today
(
((IS_NULL(c.expiryDate) OR NOT IS_DEFINED(c.expiryDate) 
    ? '1900-01-01' 
    : c.expiryDate) 
  > (IS_NULL(c.otherExpiryDate) OR NOT IS_DEFINED(c.otherExpiryDate) 
       ? '1900-01-01' 
       : c.otherExpiryDate))
-- expiryDate > otherExpiryDate, so now compare it with child.expiryDate       
? ((IS_NULL(c.expiryDate) OR NOT IS_DEFINED(c.expiryDate) 
      ? '1900-01-01' 
      : c.expiryDate) 
    > (IS_NULL(c.child.expiryDate) OR NOT IS_DEFINED(c.child.expiryDate) 
         ? '1900-01-01' 
         : c.child.expiryDate))
       ? c.expiryDate 
       : c.child.expiryDate
-- otherExpiryDate >= expiryDate, so now compare it with child.expiryDate      
: ((IS_NULL(c.otherExpiryDate) OR NOT IS_DEFINED(c.otherExpiryDate) 
      ? '1900-01-01' 
      : c.otherExpiryDate) 
    > (IS_NULL(c.child.expiryDate) OR NOT IS_DEFINED(c.child.expiryDate) 
         ? '1900-01-01' 
         : c.child.expiryDate))
       ? c.otherExpiryDate 
       : c.child.expiryDate
)
>= GetCurrentDateTime()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source