如果它为null,则为where子句中的字段设置默认值

时间:2016-06-15 20:55:29

标签: postgresql

如果尚未设置,我想在查询中为今天的日期字段设置默认值。基本上我想在where子句中使用NULL的任何日期的默认值。下面可能是使用伪代码的想法。

SELECT id
FROM coupons
WHERE expiration_date BETWEEN start_date
AND (IF end_date IS NULL THEN RETURN current_date ELSE RETURN end_date)

1 个答案:

答案 0 :(得分:2)

使用 COALESCE

 SELECT id
 FROM coupons
 WHERE expiration_date BETWEEN start_date
                       AND COALESCE (end_date, current_date())

不确定这是否是性能最佳的查询。我会查看EXPLAIN ANALYZE

也许这样的事情更好

 SELECT id
 FROM coupons
 WHERE expiration_date BETWEEN start_date
                           AND end_date
   AND end_date IS NOT NULL

 UNION ALL

 SELECT id
 FROM coupons
 WHERE expiration_date BETWEEN start_date
                           AND current_date()
   AND end_date IS NULL