I have a set of records in a table, with some records having invalid date. I wanted to ignore those invalid records and do a check with rest of the records. I framed a query like below but I don’t find it working.
select * from tbl_name i
where is_date(i.dob) and i.dob::date > CURRENT_DATE;
I got to know that sql doesn’t short circuit so it also consider invalid record and end up in date/time out of range. Please help me alter this query in a way i could eliminate invalid dates and do date comparison on valid dates only.
2
Answers
There is no guarantee for short-circuiting in Postgres. Neither in a "plain" WHERE clause, nor when using a derived table (
from (select ...) where ...
). One way to force the evaluation in two steps would be a materialized common table expressions:The
materialized
keyword prevents the optimizer from pushing the condition of the outer query into the CTE.Obviously this assumes that
is_date()
will never return false positivesUsing CASE in the
WHERE
to differentiate between a valid date and an invalid one and run the>
comparison for valid date otherwise returnFALSE
.