Following Table (let’s name it validity_period):
------------------------------- id | valid_from | valid_until ------------------------------- 1 2012-11-12 2012-12-02 2 2012-12-03 NULL 3 2012-12-15 2012-12-21
(valid_from is not nullable; valid_until is nullable, but don’t have to be null)
Now I want to find out which entry is valid today (2012-12-19). From the logical sight of view it has to be entry 3, because the entries can overlap each other but only one entry is valid on one day. (On 2012-12-22 it has to be entry 2 which is valid.)
Note that all entries can have a valid_until, but there can’t be more than one entry where valid_until is NULL.
How would I perform this in a SQL-Query? (If possible in SQLAlchemy, but I also can translate it myself from raw SQL)
(I’m using PostgreSQL 9.1)
EDIT: Here my final resolution. Thanks to all contributors!
SELECT *
FROM validity_period
WHERE valid_from <= CURRENT_DATE AND
valid_until >= CURRENT_DATE
UNION
SELECT *
FROM validity_period
WHERE valid_from <= CURRENT_DATE AND
valid_until IS NULL
ORDER BY valid_from DESC
LIMIT 1;
Try something like this:
Simply remove the DESC if you want the first rather than the last null field