]> begriffs open source - ai-pg/blob - full-docs/txt/rangetypes.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / rangetypes.txt
1
2 8.17. Range Types #
3
4    8.17.1. Built-in Range and Multirange Types
5    8.17.2. Examples
6    8.17.3. Inclusive and Exclusive Bounds
7    8.17.4. Infinite (Unbounded) Ranges
8    8.17.5. Range Input/Output
9    8.17.6. Constructing Ranges and Multiranges
10    8.17.7. Discrete Range Types
11    8.17.8. Defining New Range Types
12    8.17.9. Indexing
13    8.17.10. Constraints on Ranges
14
15    Range types are data types representing a range of values of some
16    element type (called the range's subtype). For instance, ranges of
17    timestamp might be used to represent the ranges of time that a meeting
18    room is reserved. In this case the data type is tsrange (short for
19    “timestamp range”), and timestamp is the subtype. The subtype must have
20    a total order so that it is well-defined whether element values are
21    within, before, or after a range of values.
22
23    Range types are useful because they represent many element values in a
24    single range value, and because concepts such as overlapping ranges can
25    be expressed clearly. The use of time and date ranges for scheduling
26    purposes is the clearest example; but price ranges, measurement ranges
27    from an instrument, and so forth can also be useful.
28
29    Every range type has a corresponding multirange type. A multirange is
30    an ordered list of non-contiguous, non-empty, non-null ranges. Most
31    range operators also work on multiranges, and they have a few functions
32    of their own.
33
34 8.17.1. Built-in Range and Multirange Types #
35
36    PostgreSQL comes with the following built-in range types:
37      * int4range — Range of integer, int4multirange — corresponding
38        Multirange
39      * int8range — Range of bigint, int8multirange — corresponding
40        Multirange
41      * numrange — Range of numeric, nummultirange — corresponding
42        Multirange
43      * tsrange — Range of timestamp without time zone, tsmultirange —
44        corresponding Multirange
45      * tstzrange — Range of timestamp with time zone, tstzmultirange —
46        corresponding Multirange
47      * daterange — Range of date, datemultirange — corresponding
48        Multirange
49
50    In addition, you can define your own range types; see CREATE TYPE for
51    more information.
52
53 8.17.2. Examples #
54
55 CREATE TABLE reservation (room int, during tsrange);
56 INSERT INTO reservation VALUES
57     (1108, '[2010-01-01 14:30, 2010-01-01 15:30)');
58
59 -- Containment
60 SELECT int4range(10, 20) @> 3;
61
62 -- Overlaps
63 SELECT numrange(11.1, 22.2) && numrange(20.0, 30.0);
64
65 -- Extract the upper bound
66 SELECT upper(int8range(15, 25));
67
68 -- Compute the intersection
69 SELECT int4range(10, 20) * int4range(15, 25);
70
71 -- Is the range empty?
72 SELECT isempty(numrange(1, 5));
73
74    See Table 9.58 and Table 9.60 for complete lists of operators and
75    functions on range types.
76
77 8.17.3. Inclusive and Exclusive Bounds #
78
79    Every non-empty range has two bounds, the lower bound and the upper
80    bound. All points between these values are included in the range. An
81    inclusive bound means that the boundary point itself is included in the
82    range as well, while an exclusive bound means that the boundary point
83    is not included in the range.
84
85    In the text form of a range, an inclusive lower bound is represented by
86    “[” while an exclusive lower bound is represented by “(”. Likewise, an
87    inclusive upper bound is represented by “]”, while an exclusive upper
88    bound is represented by “)”. (See Section 8.17.5 for more details.)
89
90    The functions lower_inc and upper_inc test the inclusivity of the lower
91    and upper bounds of a range value, respectively.
92
93 8.17.4. Infinite (Unbounded) Ranges #
94
95    The lower bound of a range can be omitted, meaning that all values less
96    than the upper bound are included in the range, e.g., (,3]. Likewise,
97    if the upper bound of the range is omitted, then all values greater
98    than the lower bound are included in the range. If both lower and upper
99    bounds are omitted, all values of the element type are considered to be
100    in the range. Specifying a missing bound as inclusive is automatically
101    converted to exclusive, e.g., [,] is converted to (,). You can think of
102    these missing values as +/-infinity, but they are special range type
103    values and are considered to be beyond any range element type's
104    +/-infinity values.
105
106    Element types that have the notion of “infinity” can use them as
107    explicit bound values. For example, with timestamp ranges,
108    [today,infinity) excludes the special timestamp value infinity, while
109    [today,infinity] include it, as does [today,) and [today,].
110
111    The functions lower_inf and upper_inf test for infinite lower and upper
112    bounds of a range, respectively.
113
114 8.17.5. Range Input/Output #
115
116    The input for a range value must follow one of the following patterns:
117 (lower-bound,upper-bound)
118 (lower-bound,upper-bound]
119 [lower-bound,upper-bound)
120 [lower-bound,upper-bound]
121 empty
122
123    The parentheses or brackets indicate whether the lower and upper bounds
124    are exclusive or inclusive, as described previously. Notice that the
125    final pattern is empty, which represents an empty range (a range that
126    contains no points).
127
128    The lower-bound may be either a string that is valid input for the
129    subtype, or empty to indicate no lower bound. Likewise, upper-bound may
130    be either a string that is valid input for the subtype, or empty to
131    indicate no upper bound.
132
133    Each bound value can be quoted using " (double quote) characters. This
134    is necessary if the bound value contains parentheses, brackets, commas,
135    double quotes, or backslashes, since these characters would otherwise
136    be taken as part of the range syntax. To put a double quote or
137    backslash in a quoted bound value, precede it with a backslash. (Also,
138    a pair of double quotes within a double-quoted bound value is taken to
139    represent a double quote character, analogously to the rules for single
140    quotes in SQL literal strings.) Alternatively, you can avoid quoting
141    and use backslash-escaping to protect all data characters that would
142    otherwise be taken as range syntax. Also, to write a bound value that
143    is an empty string, write "", since writing nothing means an infinite
144    bound.
145
146    Whitespace is allowed before and after the range value, but any
147    whitespace between the parentheses or brackets is taken as part of the
148    lower or upper bound value. (Depending on the element type, it might or
149    might not be significant.)
150
151 Note
152
153    These rules are very similar to those for writing field values in
154    composite-type literals. See Section 8.16.6 for additional commentary.
155
156    Examples:
157 -- includes 3, does not include 7, and does include all points in between
158 SELECT '[3,7)'::int4range;
159
160 -- does not include either 3 or 7, but includes all points in between
161 SELECT '(3,7)'::int4range;
162
163 -- includes only the single point 4
164 SELECT '[4,4]'::int4range;
165
166 -- includes no points (and will be normalized to 'empty')
167 SELECT '[4,4)'::int4range;
168
169    The input for a multirange is curly brackets ({ and }) containing zero
170    or more valid ranges, separated by commas. Whitespace is permitted
171    around the brackets and commas. This is intended to be reminiscent of
172    array syntax, although multiranges are much simpler: they have just one
173    dimension and there is no need to quote their contents. (The bounds of
174    their ranges may be quoted as above however.)
175
176    Examples:
177 SELECT '{}'::int4multirange;
178 SELECT '{[3,7)}'::int4multirange;
179 SELECT '{[3,7), [8,9)}'::int4multirange;
180
181 8.17.6. Constructing Ranges and Multiranges #
182
183    Each range type has a constructor function with the same name as the
184    range type. Using the constructor function is frequently more
185    convenient than writing a range literal constant, since it avoids the
186    need for extra quoting of the bound values. The constructor function
187    accepts two or three arguments. The two-argument form constructs a
188    range in standard form (lower bound inclusive, upper bound exclusive),
189    while the three-argument form constructs a range with bounds of the
190    form specified by the third argument. The third argument must be one of
191    the strings “()”, “(]”, “[)”, or “[]”. For example:
192 -- The full form is: lower bound, upper bound, and text argument indicating
193 -- inclusivity/exclusivity of bounds.
194 SELECT numrange(1.0, 14.0, '(]');
195
196 -- If the third argument is omitted, '[)' is assumed.
197 SELECT numrange(1.0, 14.0);
198
199 -- Although '(]' is specified here, on display the value will be converted to
200 -- canonical form, since int8range is a discrete range type (see below).
201 SELECT int8range(1, 14, '(]');
202
203 -- Using NULL for either bound causes the range to be unbounded on that side.
204 SELECT numrange(NULL, 2.2);
205
206    Each range type also has a multirange constructor with the same name as
207    the multirange type. The constructor function takes zero or more
208    arguments which are all ranges of the appropriate type. For example:
209 SELECT nummultirange();
210 SELECT nummultirange(numrange(1.0, 14.0));
211 SELECT nummultirange(numrange(1.0, 14.0), numrange(20.0, 25.0));
212
213 8.17.7. Discrete Range Types #
214
215    A discrete range is one whose element type has a well-defined “step”,
216    such as integer or date. In these types two elements can be said to be
217    adjacent, when there are no valid values between them. This contrasts
218    with continuous ranges, where it's always (or almost always) possible
219    to identify other element values between two given values. For example,
220    a range over the numeric type is continuous, as is a range over
221    timestamp. (Even though timestamp has limited precision, and so could
222    theoretically be treated as discrete, it's better to consider it
223    continuous since the step size is normally not of interest.)
224
225    Another way to think about a discrete range type is that there is a
226    clear idea of a “next” or “previous” value for each element value.
227    Knowing that, it is possible to convert between inclusive and exclusive
228    representations of a range's bounds, by choosing the next or previous
229    element value instead of the one originally given. For example, in an
230    integer range type [4,8] and (3,9) denote the same set of values; but
231    this would not be so for a range over numeric.
232
233    A discrete range type should have a canonicalization function that is
234    aware of the desired step size for the element type. The
235    canonicalization function is charged with converting equivalent values
236    of the range type to have identical representations, in particular
237    consistently inclusive or exclusive bounds. If a canonicalization
238    function is not specified, then ranges with different formatting will
239    always be treated as unequal, even though they might represent the same
240    set of values in reality.
241
242    The built-in range types int4range, int8range, and daterange all use a
243    canonical form that includes the lower bound and excludes the upper
244    bound; that is, [). User-defined range types can use other conventions,
245    however.
246
247 8.17.8. Defining New Range Types #
248
249    Users can define their own range types. The most common reason to do
250    this is to use ranges over subtypes not provided among the built-in
251    range types. For example, to define a new range type of subtype float8:
252 CREATE TYPE floatrange AS RANGE (
253     subtype = float8,
254     subtype_diff = float8mi
255 );
256
257 SELECT '[1.234, 5.678]'::floatrange;
258
259    Because float8 has no meaningful “step”, we do not define a
260    canonicalization function in this example.
261
262    When you define your own range you automatically get a corresponding
263    multirange type.
264
265    Defining your own range type also allows you to specify a different
266    subtype B-tree operator class or collation to use, so as to change the
267    sort ordering that determines which values fall into a given range.
268
269    If the subtype is considered to have discrete rather than continuous
270    values, the CREATE TYPE command should specify a canonical function.
271    The canonicalization function takes an input range value, and must
272    return an equivalent range value that may have different bounds and
273    formatting. The canonical output for two ranges that represent the same
274    set of values, for example the integer ranges [1, 7] and [1, 8), must
275    be identical. It doesn't matter which representation you choose to be
276    the canonical one, so long as two equivalent values with different
277    formattings are always mapped to the same value with the same
278    formatting. In addition to adjusting the inclusive/exclusive bounds
279    format, a canonicalization function might round off boundary values, in
280    case the desired step size is larger than what the subtype is capable
281    of storing. For instance, a range type over timestamp could be defined
282    to have a step size of an hour, in which case the canonicalization
283    function would need to round off bounds that weren't a multiple of an
284    hour, or perhaps throw an error instead.
285
286    In addition, any range type that is meant to be used with GiST or
287    SP-GiST indexes should define a subtype difference, or subtype_diff,
288    function. (The index will still work without subtype_diff, but it is
289    likely to be considerably less efficient than if a difference function
290    is provided.) The subtype difference function takes two input values of
291    the subtype, and returns their difference (i.e., X minus Y) represented
292    as a float8 value. In our example above, the function float8mi that
293    underlies the regular float8 minus operator can be used; but for any
294    other subtype, some type conversion would be necessary. Some creative
295    thought about how to represent differences as numbers might be needed,
296    too. To the greatest extent possible, the subtype_diff function should
297    agree with the sort ordering implied by the selected operator class and
298    collation; that is, its result should be positive whenever its first
299    argument is greater than its second according to the sort ordering.
300
301    A less-oversimplified example of a subtype_diff function is:
302 CREATE FUNCTION time_subtype_diff(x time, y time) RETURNS float8 AS
303 'SELECT EXTRACT(EPOCH FROM (x - y))' LANGUAGE sql STRICT IMMUTABLE;
304
305 CREATE TYPE timerange AS RANGE (
306     subtype = time,
307     subtype_diff = time_subtype_diff
308 );
309
310 SELECT '[11:10, 23:00]'::timerange;
311
312    See CREATE TYPE for more information about creating range types.
313
314 8.17.9. Indexing #
315
316    GiST and SP-GiST indexes can be created for table columns of range
317    types. GiST indexes can be also created for table columns of multirange
318    types. For instance, to create a GiST index:
319 CREATE INDEX reservation_idx ON reservation USING GIST (during);
320
321    A GiST or SP-GiST index on ranges can accelerate queries involving
322    these range operators: =, &&, <@, @>, <<, >>, -|-, &<, and &>. A GiST
323    index on multiranges can accelerate queries involving the same set of
324    multirange operators. A GiST index on ranges and GiST index on
325    multiranges can also accelerate queries involving these cross-type
326    range to multirange and multirange to range operators correspondingly:
327    &&, <@, @>, <<, >>, -|-, &<, and &>. See Table 9.58 for more
328    information.
329
330    In addition, B-tree and hash indexes can be created for table columns
331    of range types. For these index types, basically the only useful range
332    operation is equality. There is a B-tree sort ordering defined for
333    range values, with corresponding < and > operators, but the ordering is
334    rather arbitrary and not usually useful in the real world. Range types'
335    B-tree and hash support is primarily meant to allow sorting and hashing
336    internally in queries, rather than creation of actual indexes.
337
338 8.17.10. Constraints on Ranges #
339
340    While UNIQUE is a natural constraint for scalar values, it is usually
341    unsuitable for range types. Instead, an exclusion constraint is often
342    more appropriate (see CREATE TABLE ... CONSTRAINT ... EXCLUDE).
343    Exclusion constraints allow the specification of constraints such as
344    “non-overlapping” on a range type. For example:
345 CREATE TABLE reservation (
346     during tsrange,
347     EXCLUDE USING GIST (during WITH &&)
348 );
349
350    That constraint will prevent any overlapping values from existing in
351    the table at the same time:
352 INSERT INTO reservation VALUES
353     ('[2010-01-01 11:30, 2010-01-01 15:00)');
354 INSERT 0 1
355
356 INSERT INTO reservation VALUES
357     ('[2010-01-01 14:45, 2010-01-01 15:45)');
358 ERROR:  conflicting key value violates exclusion constraint "reservation_during_
359 excl"
360 DETAIL:  Key (during)=(["2010-01-01 14:45:00","2010-01-01 15:45:00")) conflicts
361 with existing key (during)=(["2010-01-01 11:30:00","2010-01-01 15:00:00")).
362
363    You can use the btree_gist extension to define exclusion constraints on
364    plain scalar data types, which can then be combined with range
365    exclusions for maximum flexibility. For example, after btree_gist is
366    installed, the following constraint will reject overlapping ranges only
367    if the meeting room numbers are equal:
368 CREATE EXTENSION btree_gist;
369 CREATE TABLE room_reservation (
370     room text,
371     during tsrange,
372     EXCLUDE USING GIST (room WITH =, during WITH &&)
373 );
374
375 INSERT INTO room_reservation VALUES
376     ('123A', '[2010-01-01 14:00, 2010-01-01 15:00)');
377 INSERT 0 1
378
379 INSERT INTO room_reservation VALUES
380     ('123A', '[2010-01-01 14:30, 2010-01-01 15:30)');
381 ERROR:  conflicting key value violates exclusion constraint "room_reservation_ro
382 om_during_excl"
383 DETAIL:  Key (room, during)=(123A, ["2010-01-01 14:30:00","2010-01-01 15:30:00")
384 ) conflicts
385 with existing key (room, during)=(123A, ["2010-01-01 14:00:00","2010-01-01 15:00
386 :00")).
387
388 INSERT INTO room_reservation VALUES
389     ('123B', '[2010-01-01 14:30, 2010-01-01 15:30)');
390 INSERT 0 1