select document based on date range
Something like

(   SELECT * 
    FROM `template` 
    WHERE DATE(`valid`) &gt;= DATE(:date) 
    ORDER BY DATE(`valid`) 
    LIMIT 1
)
UNION ALL
(   SELECT * 
    FROM `template` 
    WHERE DATE(`valid`) &lt;= '1970-01-01' OR `valid` IS NULL
)
ORDER BY `valid` DESC 
LIMIT 1


or

SELECT * 
FROM `template` 
WHERE CASE WHEN DATE(`valid`) &gt; '1970-01-01'
           THEN `valid`
           ELSE '2038-01-19'
      END &gt;= DATE(:date) 
ORDER BY CASE WHEN DATE(`valid`) &gt; '1970-01-01'
              THEN `valid`
              ELSE '2038-01-19'
         END
LIMIT 1


and so on...