# Postgres - Query distinct/longest date ranges

**URL:** https://matillioncommunity.discourse.group/t/postgres-query-distinct-longest-date-ranges/1123
**Category:** Maia
**Created:** [August 7, 2024, 3:09am UTC](https://matillioncommunity.discourse.group/t/postgres-query-distinct-longest-date-ranges/1123 "2024-08-07T03:09:02Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![vivansai4](https://sea2.discourse-cdn.com/flex002/user_avatar/matillioncommunity.discourse.group/vivansai4/32/55_2.png) [@vivansai4](https://matillioncommunity.discourse.group/u/vivansai4)
#### Post date: [August 7, 2024, 3:09am UTC](https://matillioncommunity.discourse.group/t/postgres-query-distinct-longest-date-ranges/1123/1 "2024-08-07T03:09:02Z")

</div>

I'm looking to apply some logic that returns the distinct/longest date ranges in a particular table. In the example below, PKID 1 contains the date ranges in 2-4, then is proceeded by 5. I can't think of a good way to return 1 and 5 without writing multiple&nbsp;

MIN()

&nbsp;

&nbsp;and&nbsp;

MAX()

&nbsp;

&nbsp;aggregates, comparing lengths of time, or writing a 10 line&nbsp;

CASE

&nbsp;

&nbsp;statement with&nbsp;

LAG()

&nbsp;functions. Is there an easier way to return PKID 1 and 5 without doing 20 levels of logic tests?

I've found a few posts that come close to this problem but aren't the same. I can't think of a way to implement the&nbsp;

OVERLAP

&nbsp;function in this instance, but enjoyed learning about it

---

<div class="post-metadata">

### Author: ![ClaireSeniorCommunityManager](https://avatars.discourse-cdn.com/v4/letter/c/7ba0ec/32.png) [@ClaireSeniorCommunityManager](https://matillioncommunity.discourse.group/u/ClaireSeniorCommunityManager)
#### Post date: [September 5, 2024, 9:39am UTC](https://matillioncommunity.discourse.group/t/postgres-query-distinct-longest-date-ranges/1123/2 "2024-09-05T09:39:38Z")

</div>

Hi [@vivansai4](https://matillioncommunity.discourse.group/u/vivansai4)​ and thanks for posting!

It's possible to interpret your question more than one way, depending on what you're trying to achieve. However, it looks like this same question may have already been answered over on [StackOverflow.](https://stackoverflow.com/questions/78841575/postgres-query-distinct-longest-date-ranges)

Is that your question, and are you happy with the answer? If not, could you give an example of the input data and results you're looking for?

Happy to help if it's still needed!

Many thanks,

Claire
