Kokizzu
Kokizzu

Reputation: 26838

SQL query date string by range

Spec: I need to query by date month and day only (ignoring year)

Input:

start := '2015-12-29'
end := '2016-01-03'

Output:

1986-12-30
1980-01-01
1982-12-31
1978-01-03
...

Current solution:

SELECT *
FROM users
WHERE RIGHT(birthday,5) >= $1
  AND RIGHT(birthday,5) <= $2

But this only works when the year not overlap, what's the easiest solution for this case?

My simplest solution is by generating the SQL string using another language:

if start_year == end_year {
    date_where = `
    AND RIGHT(birth_date,5) >= RIGHT(` + Z(start) + `,5)
    AND RIGHT(birth_date,5) <= RIGHT(` + Z(end) + `,5)
    `
} else {
    date_where = `
    AND ( RIGHT(birth_date,5) >= RIGHT(` + Z(start) + `,5)
        AND RIGHT(birth_date,5) <= '12-31'
    ) OR ( RIGHT(birth_date,5) >= '01-01'
        AND RIGHT(birth_date,5) <= RIGHT(` + Z(end) + `,5)
    )`
}

I believe there are better way than this..

Upvotes: 0

Views: 63

Answers (1)

Frank Heikens
Frank Heikens

Reputation: 127086

A date is not a string, don't use string functions to handle a date. Use date functions like EXTRACT:

SELECT  '2015-12-29'::date,
    EXTRACT(month from '2015-12-29'::date),
    EXTRACT(day from '2015-12-29'::date);

Upvotes: 1

Related Questions