バージョンごとのドキュメント一覧

8.17. 範囲型 #

<title>Range Types</title>

Range types are data types representing a range of values of some element type (called the range's <firstterm>subtype</firstterm>). For instance, ranges of <type>timestamp</type> might be used to represent the ranges of time that a meeting room is reserved. In this case the data type is <type>tsrange</type> (short for <quote>timestamp range</quote>), and <type>timestamp</type> is the subtype. The subtype must have a total order so that it is well-defined whether element values are within, before, or after a range of values. 範囲型は、ある要素型(その範囲の派生元型と呼ばれます)の値の範囲を表わすデータ型です。 例えば、timestampの範囲は、会議室が予約されている時間の範囲を表すのに使うことができるでしょう。 この場合、データ型はtsrange(timestamp rangeの短縮)で、timestampが派生元型となります。 派生元型には完全な順序がなければなりません。これは、要素の値が範囲の前、中間、後のどこにあるのか明確に定義されている必要があるからです。

Range types are useful because they represent many element values in a single range value, and because concepts such as overlapping ranges can be expressed clearly. The use of time and date ranges for scheduling purposes is the clearest example; but price ranges, measurement ranges from an instrument, and so forth can also be useful. 範囲型は、一つの範囲内の多くの要素の値を表現できる、また、範囲の重なりなどの概念が明確に表現できる、などの理由で便利です。 スケジューリングのために時刻と日付の範囲を使うのがもっとも簡単な例ですが、価格の範囲、機器による測定値の範囲などといったものにも利用できるでしょう。

Every range type has a corresponding multirange type. A multirange is an ordered list of non-contiguous, non-empty, non-null ranges. Most range operators also work on multiranges, and they have a few functions of their own. すべての範囲型には、対応する多重範囲型があります。 多重範囲は、連続していない、空でない、NULLでない範囲の順序付きリストです。 ほとんどの範囲演算子は多重範囲でも機能し、いくつかの独自の機能を持っています。

8.17.1. 組み込みの範囲型と多重範囲型 #

<title>Built-in Range and Multirange Types</title>

PostgreSQL comes with the following built-in range types: PostgreSQLには、以下の組み込みの範囲型があります。

  • <type>int4range</type> &mdash; Range of <type>integer</type>, <type>int4multirange</type> &mdash; corresponding Multirange int4rangeintegerの範囲、int4multirange—対応する多重範囲

  • <type>int8range</type> &mdash; Range of <type>bigint</type>, <type>int8multirange</type> &mdash; corresponding Multirange int8rangebigintの範囲、int8multirange—対応する多重範囲

  • <type>numrange</type> &mdash; Range of <type>numeric</type>, <type>nummultirange</type> &mdash; corresponding Multirange numrangenumericの範囲、nummultirange—対応する多重範囲

  • <type>tsrange</type> &mdash; Range of <type>timestamp without time zone</type>, <type>tsmultirange</type> &mdash; corresponding Multirange tsrangetimestamp without time zoneの範囲、tsmultirange—対応する多重範囲

  • <type>tstzrange</type> &mdash; Range of <type>timestamp with time zone</type>, <type>tstzmultirange</type> &mdash; corresponding Multirange tstzrangetimestamp with time zoneの範囲、tstzmultirange—対応する多重範囲

  • <type>daterange</type> &mdash; Range of <type>date</type>, <type>datemultirange</type> &mdash; corresponding Multirange daterangedateの範囲、datemultirange—対応する多重範囲

In addition, you can define your own range types; see <xref linkend="sql-createtype"/> for more information. この他にも、独自の範囲型を定義することができます。詳しくはCREATE TYPEを参照してください。

8.17.2. 例 #

<title>Examples</title>

CREATE TABLE reservation (room int, during tsrange);
INSERT INTO reservation VALUES
    (1108, '[2010-01-01 14:30, 2010-01-01 15:30)');


&#45;- Containment

-- 含有
SELECT int4range(10, 20) @> 3;


&#45;- Overlaps

-- 重なり
SELECT numrange(11.1, 22.2) && numrange(20.0, 30.0);


&#45;- Extract the upper bound

-- 上限の取得
SELECT upper(int8range(15, 25));


&#45;- Compute the intersection

-- 共通部分の計算
SELECT int4range(10, 20) * int4range(15, 25);


&#45;- Is the range empty?

-- 範囲は空か
SELECT isempty(numrange(1, 5));

See <xref linkend="range-operators-table"/> and <xref linkend="range-functions-table"/> for complete lists of operators and functions on range types. 範囲型についての演算子と関数の完全なリストについては、表 9.55表 9.57を参照してください。

8.17.3. 閉じた境界と開いた境界 #

<title>Inclusive and Exclusive Bounds</title>

Every non-empty range has two bounds, the lower bound and the upper bound. All points between these values are included in the range. An inclusive bound means that the boundary point itself is included in the range as well, while an exclusive bound means that the boundary point is not included in the range. 空でない範囲には必ず2つの境界、つまり下限値と上限値があります。 これらの値の間にある値はすべてその範囲に含まれます。 閉じた境界とは、その境界値自体が範囲に含まれることを意味し、開いた境界とは、その境界値が範囲に含まれないことを意味します。

In the text form of a range, an inclusive lower bound is represented by <quote><literal>[</literal></quote> while an exclusive lower bound is represented by <quote><literal>(</literal></quote>. Likewise, an inclusive upper bound is represented by <quote><literal>]</literal></quote>, while an exclusive upper bound is represented by <quote><literal>)</literal></quote>. (See <xref linkend="rangetypes-io"/> for more details.) 範囲を文字列の形式で表すとき、閉じた下限値は[で、開いた下限値は(で表します。 同様に、閉じた上限値は]で、開いた上限値は)で表します。 (詳しくは 8.17.5を参照してください。)

The functions <literal>lower_inc</literal> and <literal>upper_inc</literal> test the inclusivity of the lower and upper bounds of a range value, respectively. 関数lower_incおよびupper_incはそれぞれ、範囲の下限値と上限値が閉じているかどうかを検査します。

8.17.4. 無限の(境界のない)範囲 #

<title>Infinite (Unbounded) Ranges</title>

The lower bound of a range can be omitted, meaning that all values less than the upper bound are included in the range, e.g., <literal>(,3]</literal>. Likewise, if the upper bound of the range is omitted, then all values greater than the lower bound are included in the range. If both lower and upper bounds are omitted, all values of the element type are considered to be in the range. Specifying a missing bound as inclusive is automatically converted to exclusive, e.g., <literal>[,]</literal> is converted to <literal>(,)</literal>. You can think of these missing values as +/-infinity, but they are special range type values and are considered to be beyond any range element type's +/-infinity values. 例えば、(,3]のように、範囲の下限値は省略することができ、このとき、上限値より小さいすべての値はその範囲に含まれることになります。 同じように、範囲の上限値も省略することができ、このときは、下限値より大きいすべての値がその範囲に含まれることになります。 下限値と上限値が両方とも省略されたときは、その要素型のすべての値がその範囲に含まれるとみなされます。 省略された閉じた境界は自動的に開いた境界に変換されます。例えば、[,](,)に変換されます。 省略された値を+/-無限大と考えることができますが、特殊な範囲型の値であり、いかなる範囲の要素型の+/-無限大の値も超えていると考えられます。

Element types that have the notion of <quote>infinity</quote> can use them as explicit bound values. For example, with timestamp ranges, <literal>[today,infinity)</literal> excludes the special <type>timestamp</type> value <literal>infinity</literal>, while <literal>[today,infinity]</literal> include it, as does <literal>[today,)</literal> and <literal>[today,]</literal>. 無限大の概念がある要素型では、それを明示的な境界値として使用できます。 例えば、timestampの範囲で[today,infinity)は特殊なtimestamp値、infinityを含みませんが、一方、[today,infinity][today,)[today,]と同じようにinfinityを含みます。

The functions <literal>lower_inf</literal> and <literal>upper_inf</literal> test for infinite lower and upper bounds of a range, respectively. 関数lower_infおよびupper_infはそれぞれ範囲の下限値と上限値が無限大かどうかを検査します。

8.17.5. 範囲の入出力 #

<title>Range Input/Output</title>

The input for a range value must follow one of the following patterns: 範囲値の入力は、以下の形式の一つに従わなければなりません。

(lower-bound,upper-bound)
(lower-bound,upper-bound]
[lower-bound,upper-bound)
[lower-bound,upper-bound]
empty

The parentheses or brackets indicate whether the lower and upper bounds are exclusive or inclusive, as described previously. Notice that the final pattern is <literal>empty</literal>, which represents an empty range (a range that contains no points). 前にも述べたとおり、丸括弧と大括弧は下限値と上限値が開いているか閉じているかを表します。 最後の形式がemptyであることに注意してください。これは空の範囲(範囲に含まれる値が1つもない)を表します。

The <replaceable>lower-bound</replaceable> may be either a string that is valid input for the subtype, or empty to indicate no lower bound. Likewise, <replaceable>upper-bound</replaceable> may be either a string that is valid input for the subtype, or empty to indicate no upper bound. lower-boundは、その派生元型の有効な入力値となる文字列か、あるいは省略して下限値がないことを指定するかのいずれかです。 同様に、upper-boundは、その派生元型の有効な入力値となる文字列か、あるいは省略して上限値がないことを指定するかのいずれかです。

Each bound value can be quoted using <literal>"</literal> (double quote) characters. This is necessary if the bound value contains parentheses, brackets, commas, double quotes, or backslashes, since these characters would otherwise be taken as part of the range syntax. To put a double quote or backslash in a quoted bound value, precede it with a backslash. (Also, a pair of double quotes within a double-quoted bound value is taken to represent a double quote character, analogously to the rules for single quotes in SQL literal strings.) Alternatively, you can avoid quoting and use backslash-escaping to protect all data characters that would otherwise be taken as range syntax. Also, to write a bound value that is an empty string, write <literal>""</literal>, since writing nothing means an infinite bound. 境界値は"(二重引用符)で括ることができます。 これは特に境界値が丸括弧、大括弧、カンマ、二重引用符、あるいはバックスラッシュを含んでいる場合に必要となります。そうしなければ、これらの文字は範囲の構文の一部とみなされてしまうからです。 二重引用符あるいはバックスラッシュを引用符で括られた境界値の中に入れるには、その直前にバックスラッシュを入れてください。 (また、SQLの文字列リテラルと同じように、二重引用符で括られた境界値の中で二重引用符を2つ続けることで1つの二重引用符を表すこともできます。) あるいは、引用符で括る代わりに、範囲の構文の一部とみなされるすべての文字をバックスラッシュでエスケープする、ということもできます。 なお、境界値として空文字列を指定するには""と書いてください。何も書かないと、境界値が無限大であることになってしまいます。

Whitespace is allowed before and after the range value, but any whitespace between the parentheses or brackets is taken as part of the lower or upper bound value. (Depending on the element type, it might or might not be significant.) 境界値の前後に空白文字を入れることができますが、括弧内にある空白文字はすべて下限値あるいは上限値の一部とみなされます。 (このことは、要素型によっては重要かもしれませんし、重要でないかもしれません。)

注記

These rules are very similar to those for writing field values in composite-type literals. See <xref linkend="rowtypes-io-syntax"/> for additional commentary. これらの規則は、複合型のリテラルにフィールド値を記述する時と非常によく似ています。 詳細な解説は8.16.6を参照してください。

Examples: 例:


&#45;- includes 3, does not include 7, and does include all points in between

-- 3を含み、7を含まない。その間の数はすべて含まれる
SELECT '[3,7)'::int4range;


&#45;- does not include either 3 or 7, but includes all points in between

-- 3も7も含まないが、その間の数はすべて含まれる
SELECT '(3,7)'::int4range;


&#45;- includes only the single point 4

-- 1つの値、4だけを含む
SELECT '[4,4]'::int4range;


&#45;- includes no points (and will be normalized to 'empty')

-- 含まれる点は何もない('empty'に正規化される)
SELECT '[4,4)'::int4range;

The input for a multirange is curly brackets (<literal>{</literal> and <literal>}</literal>) containing zero or more valid ranges, separated by commas. Whitespace is permitted around the brackets and commas. This is intended to be reminiscent of array syntax, although multiranges are much simpler: they have just one dimension and there is no need to quote their contents. (The bounds of their ranges may be quoted as above however.) 多重範囲の入力は、カンマで区切られた0個以上の有効範囲を含む中カッコ({および})です。 カッコとカンマの前後に空白を使用できます。 これは配列構文を連想させることを意図したものですが、多重範囲ははるかに単純で、次元が1つしかなく、内容を引用符で囲む必要はありません(ただし、範囲の境界は前述のように引用符で囲むことができます)。

Examples: 例えば、

SELECT '{}'::int4multirange;
SELECT '{[3,7)}'::int4multirange;
SELECT '{[3,7), [8,9)}'::int4multirange;

8.17.6. 範囲と多重範囲のコンストラクタ #

<title>Constructing Ranges and Multiranges</title>

Each range type has a constructor function with the same name as the range type. Using the constructor function is frequently more convenient than writing a range literal constant, since it avoids the need for extra quoting of the bound values. The constructor function accepts two or three arguments. The two-argument form constructs a range in standard form (lower bound inclusive, upper bound exclusive), while the three-argument form constructs a range with bounds of the form specified by the third argument. The third argument must be one of the strings <quote><literal>()</literal></quote>, <quote><literal>(]</literal></quote>, <quote><literal>[)</literal></quote>, or <quote><literal>[]</literal></quote>. For example: 範囲型には、その範囲型と同じ名前のコンストラクタ関数があります。 コンストラクタ関数を使うと、境界値の指定で余計な引用を使わずに済むので、リテラルの定数で範囲を記述するよりも便利なことが多いでしょう。 コンストラクタ関数は2つ、または3つの引数をとります。 引数が2つの形式では、(閉じた下限値, 開いた上限値)という標準的な形式の範囲を生成します。引数が3つの形式では、3番目の引数で指定した形式の境界の範囲を生成します。 3番目の引数は、以下の文字列のいずれかでなければなりません。 ()(][)、または[]。 例えば、


&#45;- The full form is: lower bound, upper bound, and text argument indicating
&#45;- inclusivity/exclusivity of bounds.

-- 完全な形式では、下限値、上限値、そして境界が閉じているか開いているかを
-- 示す文字列の引数を指定する
SELECT numrange(1.0, 14.0, '(]');


&#45;- If the third argument is omitted, '[)' is assumed.

-- 3番目の引数が省略されると、'[)'を指定したのと同じになる
SELECT numrange(1.0, 14.0);


&#45;- Although '(]' is specified here, on display the value will be converted to
&#45;- canonical form, since int8range is a discrete range type (see below).

-- ここでは'(]'を指定しているが、int8rangeは離散的な範囲型(下記参照)なので
-- 正規化された形式に変換されて表示される
SELECT int8range(1, 14, '(]');


&#45;- Using NULL for either bound causes the range to be unbounded on that side.

-- 境界値にNULLを指定すると、範囲の上限、あるいは下限がないことになる
SELECT numrange(NULL, 2.2);

Each range type also has a multirange constructor with the same name as the multirange type. The constructor function takes zero or more arguments which are all ranges of the appropriate type. For example: 各範囲型には、多重範囲型と同じ名前の多重範囲コンストラクタもあります。 コンストラクタ関数は、すべて適切な型の範囲である0個以上の引数を取ります。 例えば、

SELECT nummultirange();
SELECT nummultirange(numrange(1.0, 14.0));
SELECT nummultirange(numrange(1.0, 14.0), numrange(20.0, 25.0));

8.17.7. 離散的な範囲型 #

<title>Discrete Range Types</title>

A discrete range is one whose element type has a well-defined <quote>step</quote>, such as <type>integer</type> or <type>date</type>. In these types two elements can be said to be adjacent, when there are no valid values between them. This contrasts with continuous ranges, where it's always (or almost always) possible to identify other element values between two given values. For example, a range over the <type>numeric</type> type is continuous, as is a range over <type>timestamp</type>. (Even though <type>timestamp</type> has limited precision, and so could theoretically be treated as discrete, it's better to consider it continuous since the step size is normally not of interest.) 離散的な範囲とは、integerdateのように明確に定義されたステップのある要素型の範囲のことです。 このような型において、2つの要素の間に有効な値が1つもないとき、その2つの要素は隣接している、と言います。 これは連続的な範囲と対照的です。連続的な範囲では、任意の2つの値について、それらの間に別の値を見つけることが、いつでも(あるいは、ほとんどいつでも)可能です。 例えば、numeric型やtimestamp型の範囲は連続的です。 (timestampの精度は限界があるので、理論的には離散的として取り扱うことも可能ですが、ステップの大きさについて関心がないのが普通ですから、連続的であると考える方が良いでしょう。)

Another way to think about a discrete range type is that there is a clear idea of a <quote>next</quote> or <quote>previous</quote> value for each element value. Knowing that, it is possible to convert between inclusive and exclusive representations of a range's bounds, by choosing the next or previous element value instead of the one originally given. For example, in an integer range type <literal>[4,8]</literal> and <literal>(3,9)</literal> denote the same set of values; but this would not be so for a range over numeric. 離散的な範囲型に関するもう1つの考え方は、各要素の値について、あるいはの値というのものが明確に考えられるか、ということです。 これを知っていれば、範囲の境界の閉じた表現、あるいは開いた表現について、その値の次、あるいは前の値を使って、表現を変換することができます。 例えば、整数の範囲型[4,8](3,9)は同じ値の集合を意味しますが、これがnumericの範囲型であったならそうではありません。

A discrete range type should have a <firstterm>canonicalization</firstterm> function that is aware of the desired step size for the element type. The canonicalization function is charged with converting equivalent values of the range type to have identical representations, in particular consistently inclusive or exclusive bounds. If a canonicalization function is not specified, then ranges with different formatting will always be treated as unequal, even though they might represent the same set of values in reality. 離散的な範囲型はその要素型で使いたいステップのサイズを認識する正規化関数を持つべきです。 正規化関数は同等な値の範囲型を、同一の表現に、特に、閉じた境界、開いた境界について一定の形式に変換します。 正規化関数が指定されない場合、異なる形式の範囲は必ず等しくないものとして扱われます。これは例え、それらが現実的に同じ値の集合であったとしても、等しくないとされます。

The built-in range types <type>int4range</type>, <type>int8range</type>, and <type>daterange</type> all use a canonical form that includes the lower bound and excludes the upper bound; that is, <literal>[)</literal>. User-defined range types can use other conventions, however. 組み込みの範囲型であるint4rangeint8range、およびdaterangeはいずれも閉じた下限値と開いた上限値、つまり[)の正規化形式を使います。 しかし、ユーザ定義の範囲型はこれとは別の方式を使うことができます。

8.17.8. 新しい範囲型の定義 #

<title>Defining New Range Types</title>

Users can define their own range types. The most common reason to do this is to use ranges over subtypes not provided among the built-in range types. For example, to define a new range type of subtype <type>float8</type>: 独自の範囲型を定義することもできます。 もっともありそうな理由は、組み込みの範囲型では、その派生元型についての範囲型が提供されていない、ということでしょう。 例えば、float8を派生元型とする新しい範囲型を定義するには次のようにします。

CREATE TYPE floatrange AS RANGE (
    subtype = float8,
    subtype_diff = float8mi
);

SELECT '[1.234, 5.678]'::floatrange;

Because <type>float8</type> has no meaningful <quote>step</quote>, we do not define a canonicalization function in this example. float8には意味のあるステップがないので、この例では正規化関数を定義していません。

When you define your own range you automatically get a corresponding multirange type. 独自の範囲を定義すると、対応する多重範囲型が自動的に取得されます。

Defining your own range type also allows you to specify a different subtype B-tree operator class or collation to use, so as to change the sort ordering that determines which values fall into a given range. 独自の範囲型を定義すると、派生元型とは異なるB-tree演算子クラスや照合順を指定でき、どの値が指定の範囲に入るかを決定するソート順を変更することもできます。

If the subtype is considered to have discrete rather than continuous values, the <command>CREATE TYPE</command> command should specify a <literal>canonical</literal> function. The canonicalization function takes an input range value, and must return an equivalent range value that may have different bounds and formatting. The canonical output for two ranges that represent the same set of values, for example the integer ranges <literal>[1, 7]</literal> and <literal>[1, 8)</literal>, must be identical. It doesn't matter which representation you choose to be the canonical one, so long as two equivalent values with different formattings are always mapped to the same value with the same formatting. In addition to adjusting the inclusive/exclusive bounds format, a canonicalization function might round off boundary values, in case the desired step size is larger than what the subtype is capable of storing. For instance, a range type over <type>timestamp</type> could be defined to have a step size of an hour, in which case the canonicalization function would need to round off bounds that weren't a multiple of an hour, or perhaps throw an error instead. 派生元型が、連続的ではなく離散的な値を持つと考えられる場合は、CREATE TYPEコマンドでcanonical(正規化)関数を指定する必要があります。 正規化関数は、範囲の値を入力として受け取り、それと同等な範囲の値を返さなければなりません。戻り値は、入力値とは異なる境界値と形式になっているかもしれません。 同じ値の集合を表す範囲、例えば、整数の範囲である[1, 7][1, 8)の正規化出力は、同一である必要があります。 異なる形式の同等な値が、いつでも同じ形式の同じ値に変換されるのであれば、正規化出力の形式は何であってもかまいません。 正規化関数は、閉じた境界、開いた境界の形式を調整するだけではありません。派生元型が格納できるよりも大きなサイズのステップを使いたい場合は境界値を丸めることもあります。 例えばtimestampの範囲型をステップのサイズを1時間として定義することができます。このとき、正規化関数は1時間の倍数になっていない境界値を丸める必要があります。あるいは、その代わりにエラーを投げることもできます。

In addition, any range type that is meant to be used with GiST or SP-GiST indexes should define a subtype difference, or <literal>subtype_diff</literal>, function. (The index will still work without <literal>subtype_diff</literal>, but it is likely to be considerably less efficient than if a difference function is provided.) The subtype difference function takes two input values of the subtype, and returns their difference (i.e., <replaceable>X</replaceable> minus <replaceable>Y</replaceable>) represented as a <type>float8</type> value. In our example above, the function <function>float8mi</function> that underlies the regular <type>float8</type> minus operator can be used; but for any other subtype, some type conversion would be necessary. Some creative thought about how to represent differences as numbers might be needed, too. To the greatest extent possible, the <literal>subtype_diff</literal> function should agree with the sort ordering implied by the selected operator class and collation; that is, its result should be positive whenever its first argument is greater than its second according to the sort ordering. また、GiSTまたはSP-GiSTインデックスと一緒に使われる範囲型は、派生元型の差分、つまりsubtype_diff関数を定義すべきです。 (そのインデックスはsubtype_diffがなくても機能しますが、差分関数が提供されている時に比べると、あまり効果的でないことが多いでしょう。) 派生元型の差分関数は、2つの派生元型の入力値をとり、その差分(つまり、X引くY)をfloat8型の値として返します。 上の例では、通常のfloat8のマイナス演算子が呼び出す関数float8miを使うことができますが、それ以外の派生元型では何らかの型変換が必要となるでしょう。 差分をいかにして数字で表現するかについて、創造的な発想も必要になるかもしれません。 可能な限りにおいて、subtype_diff関数は、選択した演算子クラスと照合順が示唆するソート順と矛盾しないようにすべき、つまり、ソート順で、1番目の引数が2番目の引数より上に来る場合は、必ず差分関数の結果は正になるべきです。

A less-oversimplified example of a <literal>subtype_diff</literal> function is: subtype_diff関数の単純化されすぎていない例を以下に示します。

CREATE FUNCTION time_subtype_diff(x time, y time) RETURNS float8 AS
'SELECT EXTRACT(EPOCH FROM (x - y))' LANGUAGE sql STRICT IMMUTABLE;

CREATE TYPE timerange AS RANGE (
    subtype = time,
    subtype_diff = time_subtype_diff
);

SELECT '[11:10, 23:00]'::timerange;

See <xref linkend="sql-createtype"/> for more information about creating range types. 範囲型の作成について、より詳細な情報はCREATE TYPEを参照してください。

8.17.9. インデックス #

<title>Indexing</title>

GiST and SP-GiST indexes can be created for table columns of range types. GiST indexes can be also created for table columns of multirange types. For instance, to create a GiST index: 範囲型のテーブル列にGiSTおよびSP-GiSTインデックスを作成することができます。 GiSTインデックスは、多重範囲型のテーブル列に対しても作成できます。 例えば、GiSTインデックスを作成するには、

CREATE INDEX reservation_idx ON reservation USING GIST (during);

A GiST or SP-GiST index on ranges can accelerate queries involving these range operators: <literal>=</literal>, <literal>&amp;&amp;</literal>, <literal>&lt;@</literal>, <literal>@&gt;</literal>, <literal>&lt;&lt;</literal>, <literal>&gt;&gt;</literal>, <literal>-|-</literal>, <literal>&amp;&lt;</literal>, and <literal>&amp;&gt;</literal>. A GiST index on multiranges can accelerate queries involving the same set of multirange operators. A GiST index on ranges and GiST index on multiranges can also accelerate queries involving these cross-type range to multirange and multirange to range operators correspondingly: <literal>&amp;&amp;</literal>, <literal>&lt;@</literal>, <literal>@&gt;</literal>, <literal>&lt;&lt;</literal>, <literal>&gt;&gt;</literal>, <literal>-|-</literal>, <literal>&amp;&lt;</literal>, and <literal>&amp;&gt;</literal>. See <xref linkend="range-operators-table"/> for more information. 範囲型に関するGiSTあるいはSP-GiSTインデックスがあると、以下の範囲演算子を含む検索を高速に実行できます。 =&&<@@><<>>-|-&<、および&>。 多重範囲型に関するGiSTインデックスは、同じ多重範囲演算子のセットを含む問い合わせを高速にできます。 範囲型に関するGiSTインデックスと多重範囲型に関するGiSTインデックスは、以下の範囲型から多重範囲型へ、および多重範囲型から範囲型への演算子を含む問い合わせを高速にできます。 &&<@@><<>>-|-&<、および&>。 より詳細な情報は表 9.55を参照してください。

In addition, B-tree and hash indexes can be created for table columns of range types. For these index types, basically the only useful range operation is equality. There is a B-tree sort ordering defined for range values, with corresponding <literal>&lt;</literal> and <literal>&gt;</literal> operators, but the ordering is rather arbitrary and not usually useful in the real world. Range types' B-tree and hash support is primarily meant to allow sorting and hashing internally in queries, rather than creation of actual indexes. さらに、範囲型のテーブル列にB-treeおよびハッシュインデックスを作ることもできます。 これらのインデックスについては、基本的に、等値演算のみが有効な範囲の演算です。 範囲の値についてB-treeのソート順が、<および>演算子について定義されていますが、現実にはこの順序はあまり意味がなく、有効ではありません。 範囲型のB-treeとハッシュのサポートは実際にインデックスを作ることよりも、むしろ、検索時に内部的にソートやハッシュをできるようにするのが主な目的です。

8.17.10. 範囲の制約 #

<title>Constraints on Ranges</title>

While <literal>UNIQUE</literal> is a natural constraint for scalar values, it is usually unsuitable for range types. Instead, an exclusion constraint is often more appropriate (see <link linkend="sql-createtable-exclude">CREATE TABLE ... CONSTRAINT ... EXCLUDE</link>). Exclusion constraints allow the specification of constraints such as <quote>non-overlapping</quote> on a range type. For example: UNIQUEはスカラー値には自然な制約ですが、範囲型には通常は適当ではありません。 代わりに排他(exclude)制約を使うことの方が適切なことが多いです(CREATE TABLE ... CONSTRAINT ... EXCLUDEを参照してください)。 排他制約により、範囲型について重なりがないなどといった制約を指定することができます。 例えば、

CREATE TABLE reservation (
    during tsrange,
    EXCLUDE USING GIST (during WITH &&)
);

That constraint will prevent any overlapping values from existing in the table at the same time: この制約は、テーブル上で重なりのある値が同時に存在することを防ぎます。

INSERT INTO reservation VALUES
    ('[2010-01-01 11:30, 2010-01-01 15:00)');
INSERT 0 1

INSERT INTO reservation VALUES
    ('[2010-01-01 14:45, 2010-01-01 15:45)');
ERROR:  conflicting key value violates exclusion constraint "reservation_during_excl"
DETAIL:  Key (during)=(["2010-01-01 14:45:00","2010-01-01 15:45:00")) conflicts
with existing key (during)=(["2010-01-01 11:30:00","2010-01-01 15:00:00")).

You can use the <link linkend="btree-gist"><literal>btree_gist</literal></link> extension to define exclusion constraints on plain scalar data types, which can then be combined with range exclusions for maximum flexibility. For example, after <literal>btree_gist</literal> is installed, the following constraint will reject overlapping ranges only if the meeting room numbers are equal: btree_gistの拡張を使って通常のスカラーのデータ型について排他制約を定義することができます。 これをさらに範囲の排他と組み合わせることで大きな柔軟性を得ることができます。 例えば、btree_gistをインストールした時、次の制約は範囲の重なりについて、会議室の部屋番号も同じ時にのみ拒絶します。

CREATE EXTENSION btree_gist;
CREATE TABLE room_reservation (
    room text,
    during tsrange,
    EXCLUDE USING GIST (room WITH =, during WITH &&)
);

INSERT INTO room_reservation VALUES
    ('123A', '[2010-01-01 14:00, 2010-01-01 15:00)');
INSERT 0 1

INSERT INTO room_reservation VALUES
    ('123A', '[2010-01-01 14:30, 2010-01-01 15:30)');
ERROR:  conflicting key value violates exclusion constraint "room_reservation_room_during_excl"
DETAIL:  Key (room, during)=(123A, ["2010-01-01 14:30:00","2010-01-01 15:30:00")) conflicts
with existing key (room, during)=(123A, ["2010-01-01 14:00:00","2010-01-01 15:00:00")).

INSERT INTO room_reservation VALUES
    ('123B', '[2010-01-01 14:30, 2010-01-01 15:30)');
INSERT 0 1