243

I am trying to query my postgresql db to return results where a date is in certain month and year. In other words I would like all the values for a month-year.

The only way i've been able to do it so far is like this:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN '2014-02-01' AND '2014-02-28'

Problem with this is that I have to calculate the first date and last date before querying the table. Is there a simpler way to do this?

Thanks

1
  • Is the interval always a month or could it be, that you start maybe at 15th and end up on 7th of following month? Commented Apr 28, 2014 at 8:37

4 Answers 4

356

With dates (and times) many things become simpler if you use >= start AND < end.

For example:

SELECT
  user_id
FROM
  user_logs
WHERE
      login_date >= '2014-02-01'
  AND login_date <  '2014-03-01'

In this case you still need to calculate the start date of the month you need, but that should be straight forward in any number of ways.

The end date is also simplified; just add exactly one month. No messing about with 28th, 30th, 31st, etc.


This structure also has the advantage of being able to maintain use of indexes.


Many people may suggest a form such as the following, but they do not use indexes:

WHERE
      DATEPART('year',  login_date) = 2014
  AND DATEPART('month', login_date) = 2

This involves calculating the conditions for every single row in the table (a scan) and not using index to find the range of rows that will match (a range-seek).

Sign up to request clarification or add additional context in comments.

5 Comments

The first approach needs to mess around with months (instead of days) f.ex. 2014-12-01 & 2015-01-01. The second can be indexed too, but that's not trivial, i admit -- EXTRACT() seems more compatibe.
You can avoid date calculations in your application by using interval. e.g.: WHERE login_date >= '2014-02-01' AND login_date < '2014-02-01'::date + INTERVAL '1 month' This still uses indexes while simplifying your code.
@MatBailie, special thanks for the DATEPART notice!
flawless answer!
datepart function doesn't exist - it is called date_part()
104

From PostreSQL 9.2 Range Types are supported. So you can write this like:

SELECT user_id
FROM user_logs
WHERE '[2014-02-01, 2014-03-01]'::daterange @> login_date

this should be more efficient than the string comparison

4 Comments

For Anyone having TimeStamp type for login_date : SELECT user_id FROM user_logs WHERE '[2014-02-01, 2014-03-01]'::daterange @> login_date::date
Is it possible to build a dynamic range? I'd like to make an INNER JOIN checking if a timestamp in a table is in range from two attributes on a second table.
It seems tsrange(lower-bound, upper-bound) does the trick!
Very useful and quite the way to go, especially when you want to create ranges like [from, to) or (from, to], making sure left or right side doesn't match the equal case
67

Just in case somebody land here... since 8.1 you can simply use:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'

From the docs:

BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.

2 Comments

Be aware, that this query includes 2014-02-28 00:00:00
Doc over here
22
SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'

Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.

3 Comments

Be aware, that this query includes 2014-03-01 00:00:00.
@johnson would you then do something like ... AND '2014-03-01' - interval '1 microsecond' to mitigate this?
I'd just use the accepted answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.