Search code examples
sqlpostgresqlcase

find users with overlapping subscription dates


I have a subscription table:

user_id | start_date | end_date
1         1/1/2019   1/31/2019
2         1/15/2019  1/17/2019
3         1/29/2019  2/4/2019
4         2/5/2019   2/10/2019

I am looking to get the list of users with overlapping subscription with ANY of the other users.

user_id overlap
1   True
2   True
3   True
4   False

I tried this :

select  u1.user_id,
        case when u1.end_date > u2.start_date and u1.start_Date < u2.end_date 
        then 'True' 
        else 'False' end as overlap
from subscriptions u1 
join subscriptions u2 
    on u1.user_id <> u2.user_id

but it gives me following results:

1   True
1   True
1   False
2   True
2   False
2   False
3   True
3   False
3   False
4   False
4   False
4   False

Solution

  • I am thinking that you can use exists:

    select s.*,
           (exists (select 1
                    from subscriptions s2
                    where s2.start_date < s.end_date and
                          s2.end_date > s.start_date and
                          s2.user_id <> s.user_id
                   )
           ) as has_overlap_flag
    from subscriptions s;
    

    Here is a db<>fiddle.