Postgresql query between date ranges

前端 未结 5 1592
轻奢々
轻奢々 2020-12-04 07:51

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

相关标签:
5条回答
  • 2020-12-04 08:29
    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.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-04 08:51

    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

    0 讨论(0)
  • 2020-12-04 08:51

    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.

    0 讨论(0)
  • 2020-12-04 08:51

    Read the documentation.

    http://www.postgresql.org/docs/9.1/static/functions-datetime.html

    I used a query like that:

    WHERE
    (
        date_trunc('day',table1.date_eval) = '2015-02-09'
    )
    

    or

    WHERE(date_trunc('day',table1.date_eval) >='2015-02-09'AND date_trunc('day',table1.date_eval) <'2015-02-09')    
    

    Juanitos Ingenier.

    0 讨论(0)
提交回复
热议问题