HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Element of an array in a daterange?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
arraydaterangeelement

Problem

I have an array of dates, and I want to find out if any of the elements in the array appear within a given daterange.

For example (pseudocode - doesn't work, wrapped for readability):

SELECT ARRAY['2017-01-01'::DATE, '2017-02-03'::DATE] && 
    daterange('2017-01-01', '2017-01-31', '[]');


What this example is trying to show (although it doesn't work), is whether there's an overlap between values between my array of dates and the daterange.

Ideally I could do it with sets, and work out if there's a union between the two, but it doesn't seem possible to cast daterange objects to anything.

I did manage to get this working, but I can't work out how to subsequently reduce the rows:

SELECT daterange('2017-01-01', '2017-01-31', '[]') @> 
    unnest(ARRAY ['2017-01-01' :: DATE, '2016-07-30' :: DATE]);


This returns me multiple rows:

?column?
----------
 t
 f
(2 rows)


Does anyone have any pointers for this? Any help is appreciated.

Solution

I've got an array of dates, and I want to find out if any of the elements in the array appear within a given daterange.

Depending on the query, you can use

  • row aggregation with bool_or mentioned by joanolo in his answer.



-
or, you can use ANY with the contains operator @>

SELECT daterange('2017-01-01', '2017-01-31', '[]')  @> 
  ANY(ARRAY['2017-01-01'::date, '2017-02-03'::date]);

SELECT daterange('2017-01-01', '2017-01-31', '[]')  @> 
  ANY(ARRAY['2016-01-02'::date, '2016-01-09'::date]);

Code Snippets

SELECT daterange('2017-01-01', '2017-01-31', '[]')  @> 
  ANY(ARRAY['2017-01-01'::date, '2017-02-03'::date]);

SELECT daterange('2017-01-01', '2017-01-31', '[]')  @> 
  ANY(ARRAY['2016-01-02'::date, '2016-01-09'::date]);

Context

StackExchange Database Administrators Q#160105, answer score: 6

Revisions (0)

No revisions yet.