postgresqlpostgresql-9.6

Postgres: Is Date between now and interval for EVERY birthday


I want to be able to return Users who have a birthday between now and a specified time interval.

User Model

My Time Interval = 30 days

My Data Set

|---------------------|------------------|------------------|
|      id             |     name         |     birthday     |
|---------------------|------------------|------------------|
|          1          |        Tim       |   27/06/1994     |
|---------------------|------------------|------------------|

My Attempt

SELECT * FROM User where User.birthday BETWEEN NOW()::timestamp AND to_char(NOW() + interval '30 days','MM-DD')::timestamp;

Returns

Empty. Postgres is assuming that by omitting the year I actually mean year 1.

What I want

This query to return all users whose birthday resides in the interval regardless of the year.

Attempt From Answers (Many thanks @Mureinik)

SELECT *
FROM   user
WHERE  birthday BETWEEN TO_CHAR(NOW(), 'MM-DD') AND
TO_CHAR(NOW() + INTERVAL '30 days','MM-DD')

Issues with this answer


Solution

  • I generated a new date based on the current year and the user's birthday month and day, then see if that is in the next 30 days.

    select *
    from user
    where date(date_part('year', current_date)||'-'||date_part('month', birthday)||'-'||date_part('day', birthday))
        between current_date and current_date + interval '30 days';
    

    For example:

    # select * from user;
     id | name  |  birthday
    ----+-------+------------
      1 | Tim   | 1994-06-27
      2 | Steve | 1982-06-23
      3 | Dave  | 1980-07-29
    (3 rows)
    
    # select *
    from user
    where date(date_part('year', current_date)||'-'||date_part('month', birthday)||'-'||date_part('day', birthday))
        between current_date and current_date + interval '30 days';
     id | name  |  birthday
    ----+-------+------------
      1 | Tim   | 1994-06-27
      2 | Steve | 1982-06-23
    (2 rows)