I have a table with (among other things) dates in a field.
I need to get a list of all dates that are more recent than the oldest date, older than the most recent date, and are completely missing from the table.
So, if the table contained:
2012-01-02
2012-01-02
2012-01-03
2012-01-05
2012-01-05
2012-01-07
2012-01-08
I want a query that returns:
2012-01-04
2012-01-06
Something like this (assuming your table is named
your_tableand the date column is namedthe_date):Edit:
the
WITHclause is called a “common table expression” and is equivalent to a derived table (“inline view”).It’s similar to
The second CTE simply creates a list of dates “on-the-fly” using a undocumented feature of Oracle’s
connect byimplementation.Re-using a select (like I did with calculating the first and last date) is a bit easier (and IMHO more readable) than using derived tables.
Edit 2:
This can be done with a recursive CTE as well:
Which should work in all DBMS supporting recursive CTEs (PostgreSQL and Firebird – being more standard compliant – do need the
recursivekeyword though).Note the hack
select (select oldest from date_range) + lvl, lvl + 1in the recursive part. This should not be necessary, but Oracle still has some bugs with regards to DATEs in a recursive CTE. In PostgreSQL the following works without problems: