I am trying to put together a SQL query that will return data based on a simple WHERE
condition but will also return the first available record if the condition is not met.
author_id | post_id | publish_date |
---|---|---|
1 | 31 | 2021-07-23 |
2 | 432 | 2021-06-22 |
2 | 555 | 2020-07-23 |
Using the data above my basic query would look like this
select *
from posts
where author_id = 1
and publish_date > '2021-07-01'
order by publish_date
Results, ie posts by the author published after a specified date
author_id | post_id | publish_date |
---|---|---|
1 | 31 | 2021-07-23 |
Since author 2 has no posts after this date I would like it to return the most recent post of the specified author. I want to be able to output "<author> hasn't posted since <search_date>, the most recent post was on <publish_date>" without querying the database multiple times.
Desired result for author_id 2 (who doesn't have any posts where publish_date > '2021-07-01')
author_id | post_id | publish_date |
---|---|---|
2 | 432 | 2021-06-22 |
Is it possible to query for the first available record if the date condition is not met in a single statement?