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

4.1. 字句の構造 #

<title>Lexical Structure</title>

SQL input consists of a sequence of <firstterm>commands</firstterm>. A command is composed of a sequence of <firstterm>tokens</firstterm>, terminated by a semicolon (<quote>;</quote>). The end of the input stream also terminates a command. Which tokens are valid depends on the syntax of the particular command. SQLの入力は、ひと続きのコマンドからなります。 コマンドはトークンが繋がったもので構成され、最後はセミコロン(;)で終わります。 入力ストリームの終了もやはりコマンドを終わらせます。 どのトークンが有効かは特定のコマンドの構文によります。

A token can be a <firstterm>key word</firstterm>, an <firstterm>identifier</firstterm>, a <firstterm>quoted identifier</firstterm>, a <firstterm>literal</firstterm> (or constant), or a special character symbol. Tokens are normally separated by whitespace (space, tab, newline), but need not be if there is no ambiguity (which is generally only the case if a special character is adjacent to some other token type). トークンはキーワード識別子引用符で囲まれた識別子リテラル(もしくは定数)、特別な文字シンボルです。 トークンは通常空白(スペース、タブ、改行)で区切られますが、曖昧さがなければ(一般的には特別な文字が他のトークン型と隣接している場合のみ)必要ありません。

For example, the following is (syntactically) valid SQL input: 例えば、以下のものは(構文的に)正しいSQLの入力です。

SELECT * FROM MY_TABLE;
UPDATE MY_TABLE SET A = 5;
INSERT INTO MY_TABLE VALUES (3, 'hi there');

This is a sequence of three commands, one per line (although this is not required; more than one command can be on a line, and commands can usefully be split across lines). この例は1行に1つのコマンドを記述した、3つのコマンドが連続しています(必ずしも1つのコマンドを1行で書く必要はありません。 1行に複数のコマンドを入力することも可能ですし、1つのコマンドを複数行に分けて記述することも可能です)。

Additionally, <firstterm>comments</firstterm> can occur in SQL input. They are not tokens, they are effectively equivalent to whitespace. さらに、入力されたSQLにコメントが付いていても構いません。 コメントはトークンではなく、その効果は空白と同じです。

The SQL syntax is not very consistent regarding what tokens identify commands and which are operands or parameters. The first few tokens are generally the command name, so in the above example we would usually speak of a <quote>SELECT</quote>, an <quote>UPDATE</quote>, and an <quote>INSERT</quote> command. But for instance the <command>UPDATE</command> command always requires a <token>SET</token> token to appear in a certain position, and this particular variation of <command>INSERT</command> also requires a <token>VALUES</token> in order to be complete. The precise syntax rules for each command are described in <xref linkend="reference"/>. SQL構文は、どのトークンがコマンドを識別し、どれがオペランドでどれがパラメータかに関してはさほど首尾一貫していません。 最初のいくつかのトークンは一般にコマンド名です。 したがって、上記の例においてSELECTUPDATEINSERTコマンドについて通常説明することになります。 しかし、例えばUPDATEコマンドでは、SETトークンが特定の位置に常に記述されなければなりませんし、この例で使われているINSERTコマンドを完結するためにはVALUESトークンが必要です。 それぞれのコマンドの正確な構文規則はパート VIで説明されています。

4.1.1. 識別子とキーワード #

<title>Identifiers and Key Words</title>

Tokens such as <token>SELECT</token>, <token>UPDATE</token>, or <token>VALUES</token> in the example above are examples of <firstterm>key words</firstterm>, that is, words that have a fixed meaning in the SQL language. The tokens <token>MY_TABLE</token> and <token>A</token> are examples of <firstterm>identifiers</firstterm>. They identify names of tables, columns, or other database objects, depending on the command they are used in. Therefore they are sometimes simply called <quote>names</quote>. Key words and identifiers have the same lexical structure, meaning that one cannot know whether a token is an identifier or a key word without knowing the language. A complete list of key words can be found in <xref linkend="sql-keywords-appendix"/>. 上記の例に出てくるSELECTUPDATE、もしくはVALUESのようなトークンは、キーワードの一例です。 キーワードとは、SQL言語で決まった意味を持っている単語です。 MY_TABLEトークンやAトークンは識別子の一例です。 これらは、使われるコマンドによって、テーブル、列、他のデータベースオブジェクトの名前を識別します。 したがって、単に名前と呼ばれることもあります。 キーワードと識別子は同じ字句の構造を持つため、言語を知らなくてはトークンが識別子なのかキーワードなのかわからないということになります。 全てのキーワードのリストは付録Cにあります。

SQL identifiers and key words must begin with a letter (<literal>a</literal>-<literal>z</literal>, but also letters with diacritical marks and non-Latin letters) or an underscore (<literal>_</literal>). Subsequent characters in an identifier or key word can be letters, underscores, digits (<literal>0</literal>-<literal>9</literal>), or dollar signs (<literal>$</literal>). Note that dollar signs are not allowed in identifiers according to the letter of the SQL standard, so their use might render applications less portable. The SQL standard will not define a key word that contains digits or starts or ends with an underscore, so identifiers of this form are safe against possible conflict with future extensions of the standard. SQL識別子とキーワードは、文字(azおよび発音区別符号付き文字と非Latin文字)、アンダースコア(_)で始まらなければいけません。 識別子またはキーワードの中で続く文字は、文字、アンダースコア、数字(09)あるいはドル記号($)を使用できます。 標準SQLの記述に従うと、ドル記号は識別子内では使用できないことに注意してください。 ですから、これを使用するとアプリケーションの移植性は低くなる可能性があります。 標準SQLでは、数字を含む、あるいはアンダースコアで始まったり終わったりするキーワードは定義されていません。 したがって、この形式の識別子は標準の今後の拡張と競合する可能性に対して安全です。

The system uses no more than <symbol>NAMEDATALEN</symbol>-1 bytes of an identifier; longer names can be written in commands, but they will be truncated. By default, <symbol>NAMEDATALEN</symbol> is 64 so the maximum identifier length is 63 bytes. If this limit is problematic, it can be raised by changing the <symbol>NAMEDATALEN</symbol> constant in <filename>src/include/pg_config_manual.h</filename>. システムはNAMEDATALEN-1バイトより長い識別子を使いません。 より長い名前をコマンドで書くことはできますが、短く切られてしまいます。 デフォルトではNAMEDATALENは64なので、識別子は最長で63バイトです。 この制限が問題になる場合は、src/include/pg_config_manual.h内のNAMEDATALEN定数の値を変更して増やすことができます。

Key words and unquoted identifiers are case-insensitive. Therefore: キーワードと引用符付きでない識別子は大文字と小文字を区別しません。 したがって、

UPDATE MY_TABLE SET A = 5;

can equivalently be written as: は、以下の文と同じ意味になります。

uPDaTE my_TabLE SeT a = 5;

A convention often used is to write key words in upper case and names in lower case, e.g.: 慣習的によく使われる方法では、キーワードを大文字で、名前を小文字で書きます。 例えば下記のようになります。

UPDATE my_table SET a = 5;

There is a second kind of identifier: the <firstterm>delimited identifier</firstterm> or <firstterm>quoted identifier</firstterm>. It is formed by enclosing an arbitrary sequence of characters in double-quotes (<literal>"</literal>). <!&#45;- " font-lock mania &#45;-> A delimited identifier is always an identifier, never a key word. So <literal>"select"</literal> could be used to refer to a column or table named <quote>select</quote>, whereas an unquoted <literal>select</literal> would be taken as a key word and would therefore provoke a parse error when used where a table or column name is expected. The example can be written with quoted identifiers like this: 識別子には副次的な種類もあります。 区切り識別子あるいは引用符付き識別子です。 任意の文字の連なりを二重引用符(")で囲んだものです。 " フォントロック狂 区切り識別子は常に識別子であって、キーワードではありません。 ですから、"select"selectという名前の列あるいはテーブルを問い合わせるために使えますが、引用符の付かないselectはキーワードとして理解されるので、テーブルもしくは列名が期待される部分では解析エラーを起こします。 引用符付き識別子は下記の例のように書くことができます。

UPDATE "my_table" SET "a" = 5;

Quoted identifiers can contain any character, except the character with code zero. (To include a double quote, write two double quotes.) This allows constructing table or column names that would otherwise not be possible, such as ones containing spaces or ampersands. The length limitation still applies. 引用符付き識別子は、コード0の文字以外であればどのような文字でも使えます (二重引用符を含めたい場合は、二重引用符を2つ入力します)。 これにより、空白やアンパサンド(&)を含むテーブル名や列名など、この方法がなければ作れないような名前のものを作ることが可能になります。 この場合においても長さの制限は適用されます。

Quoting an identifier also makes it case-sensitive, whereas unquoted names are always folded to lower case. For example, the identifiers <literal>FOO</literal>, <literal>foo</literal>, and <literal>"foo"</literal> are considered the same by <productname>PostgreSQL</productname>, but <literal>"Foo"</literal> and <literal>"FOO"</literal> are different from these three and each other. (The folding of unquoted names to lower case in <productname>PostgreSQL</productname> is incompatible with the SQL standard, which says that unquoted names should be folded to upper case. Thus, <literal>foo</literal> should be equivalent to <literal>"FOO"</literal> not <literal>"foo"</literal> according to the standard. If you want to write portable applications you are advised to always quote a particular name or never quote it.) 引用符が付かない名前は常に小文字に解釈されますが、識別子を引用符で囲むことによって大文字と小文字が区別されます。 例えば、識別子FOOfoo"foo"PostgreSQLによれば同じものとして解釈されますが、"Foo""FOO"は、これら3つとも、またお互いに違ったものとして解釈されます (PostgreSQLが引用符の付かない名前を小文字として解釈することは標準SQLと互換性がありません。標準SQLでは引用符の付かない名前は大文字に解釈されるべきだとされています。 したがって標準SQLによれば、foo"FOO"と同じであるべきで、"foo"とは異なるはずなのです。 もし移植可能なアプリケーションを書きたいならば、特定の名前は常に引用符で囲むか、あるいはまったく囲まないかのいずれかに統一することをお勧めします。)

A variant of quoted identifiers allows including escaped Unicode characters identified by their code points. This variant starts with <literal>U&amp;</literal> (upper or lower case U followed by ampersand) immediately before the opening double quote, without any spaces in between, for example <literal>U&amp;"foo"</literal>. (Note that this creates an ambiguity with the operator <literal>&amp;</literal>. Use spaces around the operator to avoid this problem.) Inside the quotes, Unicode characters can be specified in escaped form by writing a backslash followed by the four-digit hexadecimal code point number or alternatively a backslash followed by a plus sign followed by a six-digit hexadecimal code point number. For example, the identifier <literal>"data"</literal> could be written as 引用符付き識別子には異形があり、コード番号で識別されるエスケープされたUnicode文字を含むことができます。 この異形は、U&(大文字または小文字のUの後にアンパサンド)で始まり、その直後に空白を間に入れずに二重引用符を続けます。 例えば、U&"foo"となります。 (これにより演算子&との不明確性が生じることに注意してください。 この問題を回避するには空白を演算子の前後に入れます。) 引用符の中で、Unicode文字はバックスラッシュとそれに続く4桁16進数の文字コード番号で、またはもう1つの方法として、バックスラッシュに続いてプラス符号、そして続いた6桁16進数の文字コード番号によりエスケープ形式で指定されます。 例えば、識別子"data"は次のように書くことができます。

U&"d\0061t\+000061"

The following less trivial example writes the Russian word <quote>slon</quote> (elephant) in Cyrillic letters: 次の少し意味のある例はロシア語のslon(象)をキリル文字で書いたものです。

U&"\0441\043B\043E\043D"

If a different escape character than backslash is desired, it can be specified using the <literal>UESCAPE</literal><indexterm><primary>UESCAPE</primary></indexterm> clause after the string, for example: バックスラッシュ以外のエスケープ文字を使用したい場合、文字列の後にUESCAPE句を使用して指定できます。例をあげます。

U&"d!0061t!+000061" UESCAPE '!'

The escape character can be any single character other than a hexadecimal digit, the plus sign, a single quote, a double quote, or a whitespace character. Note that the escape character is written in single quotes, not double quotes, after <literal>UESCAPE</literal>. エスケープ文字には、16進表記用の文字、プラス記号、単一引用符、二重引用符、空白文字以外の任意の単一文字を使用できます。 エスケープ文字はUESCAPEの後に二重引用符ではなく単一引用符で記述していることに注意してください。

To include the escape character in the identifier literally, write it twice. 識別子内にエスケープ文字をそのまま含めるためには、それを2つ記述してください。

Either the 4-digit or the 6-digit escape form can be used to specify UTF-16 surrogate pairs to compose characters with code points larger than U+FFFF, although the availability of the 6-digit form technically makes this unnecessary. (Surrogate pairs are not stored directly, but are combined into a single code point.) U+FFFFより大きなコードポイントを持つ文字を構成するUTF-16サロゲートペアを指定するために、4桁と6桁の形式のどちらかを使用できますが、技術的には6桁形式の機能によりこれは不要になります。 (サロゲートペアは直接格納されるわけではなく、一つのコードポイントに結合されます。)

If the server encoding is not UTF-8, the Unicode code point identified by one of these escape sequences is converted to the actual server encoding; an error is reported if that's not possible. サーバ符号化方式がUTF-8でない場合、このエスケープシーケンスの1つで指定されたUnicodeコードポイントは実際のサーバ符号化方式へと変換されます。それが可能でない場合にはエラーが報告されます。

4.1.2. 定数 #

<title>Constants</title>

There are three kinds of <firstterm>implicitly-typed constants</firstterm> in <productname>PostgreSQL</productname>: strings, bit strings, and numbers. Constants can also be specified with explicit types, which can enable more accurate representation and more efficient handling by the system. These alternatives are discussed in the following subsections. PostgreSQLには、3つの暗黙に型付けされる定数があります。 文字列、ビット文字列、そして数字です。 定数は明示的な型で指定することもでき、その場合はシステムによる、より正確な表現と効率の良い操作が可能になります。 こうした他の方法については後ほど説明します。

4.1.2.1. 文字列定数 #

<title>String Constants</title>

A string constant in SQL is an arbitrary sequence of characters bounded by single quotes (<literal>'</literal>), for example <literal>'This is a string'</literal>. To include a single-quote character within a string constant, write two adjacent single quotes, e.g., <literal>'Dianne''s horse'</literal>. Note that this is <emphasis>not</emphasis> the same as a double-quote character (<literal>"</literal>). <!&#45;- font-lock sanity: " &#45;-> SQLにおける文字列定数は、単一引用符(')で括られた任意の文字の並びです。 例えば、'This is a string'です。 文字列定数内に単一引用符を含めるには、2つ続けて単一引用符を記述します。 例えば、'Dianne''s horse'です。 二重引用符(")とは同一ではない点に注意してください。 font-lock sanity: "

Two string constants that are only separated by whitespace <emphasis>with at least one newline</emphasis> are concatenated and effectively treated as if the string had been written as one constant. For example: 2つの文字列定数が、少なくとも1つの改行を含んだ空白のみで区切られている場合は、2つの定数は連結され、実質的に1つの定数として書かれたように処理されます。 例を示します。

SELECT 'foo'
'bar';

is equivalent to: は、

SELECT 'foobar';

but: と同じです。しかし、

SELECT 'foo'      'bar';

is not valid syntax. (This slightly bizarre behavior is specified by <acronym>SQL</acronym>; <productname>PostgreSQL</productname> is following the standard.) は有効な構文ではありません (このちょっとした奇妙な振舞いはSQLで決められているもので、PostgreSQLではこの標準に従っています)。

4.1.2.2. C形式エスケープでの文字列定数 #

<title>String Constants with C-Style Escapes</title>

<productname>PostgreSQL</productname> also accepts <quote>escape</quote> string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter <literal>E</literal> (upper or lower case) just before the opening single quote, e.g., <literal>E'foo'</literal>. (When continuing an escape string constant across lines, write <literal>E</literal> only before the first opening quote.) Within an escape string, a backslash character (<literal>\</literal>) begins a C-like <firstterm>backslash escape</firstterm> sequence, in which the combination of backslash and following character(s) represent a special byte value, as shown in <xref linkend="sql-backslash-table"/>. PostgreSQLでは、また、エスケープ文字列定数を受け付けます。 これは標準SQLの拡張です。 エスケープ文字列定数は、E(大文字でも小文字でもかまいません)を開始単一引用符の直前に記述することで指定されます。 例えばE'foo'です。 (複数行に渡るエスケープ文字列定数では、最初の開始引用符の前にのみEを記述してください。) エスケープ文字列の中では、バックスラッシュ文字(\)によりC言語のようなバックスラッシュシーケンスが開始し、その中でバックスラッシュとそれに続く文字の組み合わせが(表 4.1で示したように)特別なバイト値を表現します。

表4.1 バックスラッシュエスケープシーケンス

<title>Backslash Escape Sequences</title>
バックスラッシュエスケープシーケンス解釈
\b後退
\f改ページ
\n改行
\r復帰
\tタブ
\o, \oo, \ooo (o = 0–7) 8進数バイト値
\xh, \xhh (h = 0–9, A–F) 16進数バイト値
\uxxxx, \Uxxxxxxxx (x = 0–9, A–F) 16もしくは32ビットの16進数 Unicode 文字値

Any other character following a backslash is taken literally. Thus, to include a backslash character, write two backslashes (<literal>\\</literal>). Also, a single quote can be included in an escape string by writing <literal>\'</literal>, in addition to the normal way of <literal>''</literal>. バックスラッシュの後のそのほかの全ての文字はそのまま扱われます。 従って、バックスラッシュ文字を含ませるときは2つのバックスラッシュ(\\)を記載します。 同時に、エスケープ文字列の中では、単一引用符を、通常の方法の''に加え、\'としても含めることができます。

It is your responsibility that the byte sequences you create, especially when using the octal or hexadecimal escapes, compose valid characters in the server character set encoding. A useful alternative is to use Unicode escapes or the alternative Unicode escape syntax, explained in <xref linkend="sql-syntax-strings-uescape"/>; then the server will check that the character conversion is possible. 特に8進数や16進数エスケープを用いて作成されるバイトシーケンスが、サーバ文字セット符号化方式において有効な文字で構成されていることはコードを書く人の責任です。 便利な代替手段は、Unicodeエスケープか、4.1.2.3で説明するもう一つのUnicodeエスケープ構文を代わりとして使用することです。そうすればサーバが文字変換を可能か検査するでしょう。

注意

If the configuration parameter <xref linkend="guc-standard-conforming-strings"/> is <literal>off</literal>, then <productname>PostgreSQL</productname> recognizes backslash escapes in both regular and escape string constants. However, as of <productname>PostgreSQL</productname> 9.1, the default is <literal>on</literal>, meaning that backslash escapes are recognized only in escape string constants. This behavior is more standards-compliant, but might break applications which rely on the historical behavior, where backslash escapes were always recognized. As a workaround, you can set this parameter to <literal>off</literal>, but it is better to migrate away from using backslash escapes. If you need to use a backslash escape to represent a special character, write the string constant with an <literal>E</literal>. 設定パラメータstandard_conforming_stringsoffの場合、PostgreSQLはバックスラッシュエスケープを通常の文字列定数とエスケープ文字列定数の両方で認識します。 しかし、PostgreSQL9.1からデフォルトはonになりました。これはバックスラッシュエスケープがエスケープ文字列定数でのみ認識されます。 この振る舞いはSQL標準仕様に即していますが、バックスラッシュエスケープを常に認識するという歴史的な動作に依存しているアプリケーションは動作しなくなるでしょう。 回避策として、このパラメータをoffにすることはできますが、バックスラッシュエスケープの使用を避けるよう移植するのが良いでしょう。 特殊文字を表現するためにバックスラッシュを使用する必要がある場合、Eをつけて文字列定数を記述してください。

In addition to <varname>standard_conforming_strings</varname>, the configuration parameters <xref linkend="guc-escape-string-warning"/> and <xref linkend="guc-backslash-quote"/> govern treatment of backslashes in string constants. standard_conforming_stringsの他に、設定パラメータescape_string_warningおよびbackslash_quoteが文字列定数内のバックスラッシュの動作を決定します。

The character with the code zero cannot be in a string constant. コードゼロの文字は文字列定数の中に入れられません。

4.1.2.3. Unicodeエスケープがある文字列定数 #

<title>String Constants with Unicode Escapes</title>

<productname>PostgreSQL</productname> also supports another type of escape syntax for strings that allows specifying arbitrary Unicode characters by code point. A Unicode escape string constant starts with <literal>U&amp;</literal> (upper or lower case letter U followed by ampersand) immediately before the opening quote, without any spaces in between, for example <literal>U&amp;'foo'</literal>. (Note that this creates an ambiguity with the operator <literal>&amp;</literal>. Use spaces around the operator to avoid this problem.) Inside the quotes, Unicode characters can be specified in escaped form by writing a backslash followed by the four-digit hexadecimal code point number or alternatively a backslash followed by a plus sign followed by a six-digit hexadecimal code point number. For example, the string <literal>'data'</literal> could be written as PostgreSQLは同時に、文字コード番号で任意のUnicode文字を指定可能な文字列に対するもう一つのエスケープ構文を提供します。 Unicodeエスケープ文字列定数は、U&(大文字・小文字のUの後にアンパサンド)で始まり、その直後に、空白を間にはさまず、開始引用符が続きます。 例えば、U&'foo'となります。 (これにより演算子&との曖昧性が生じることに注意してください。 この問題を回避するには空白を演算子の前後に入れます。) 引用符の中で、Unicode文字はバックスラッシュとそれに続く4桁16進数の文字コード番号で、またはもう1つの方法として、バックスラッシュに続いてプラス符号、そして続いた6桁16進数の文字コード番号によりエスケープ形式で指定されます。 例えば、文字列'data'は次のように書かれます。

U&'d\0061t\+000061'

The following less trivial example writes the Russian word <quote>slon</quote> (elephant) in Cyrillic letters: 次の少し意味のある例はロシア語のslon(象)をキリル文字で書いたものです。

U&'\0441\043B\043E\043D'

If a different escape character than backslash is desired, it can be specified using the <literal>UESCAPE</literal><indexterm><primary>UESCAPE</primary></indexterm> clause after the string, for example: バックスラッシュ以外のエスケープ文字を使用したい場合、文字列の後にUESCAPE句を使用して指定できます。例をあげます。

U&'d!0061t!+000061' UESCAPE '!'

The escape character can be any single character other than a hexadecimal digit, the plus sign, a single quote, a double quote, or a whitespace character. エスケープ文字には、16進表記用の文字、プラス記号、単一引用符、二重引用符、空白文字以外の任意の単一文字を使用できます。

To include the escape character in the string literally, write it twice. 識別子内にエスケープ文字をそのまま含めるためには、それを2つ記述してください。

Either the 4-digit or the 6-digit escape form can be used to specify UTF-16 surrogate pairs to compose characters with code points larger than U+FFFF, although the availability of the 6-digit form technically makes this unnecessary. (Surrogate pairs are not stored directly, but are combined into a single code point.) U+FFFFより大きなコードポイントを持つ文字を構成するUTF-16サロゲートペアを指定するために、4桁と6桁の形式のどちらかを使用できますが、技術的には6桁形式の機能によりこれは不要になります。 (サロゲートペアは直接格納されるわけではなく、一つのコードポイントに結合されます。)

If the server encoding is not UTF-8, the Unicode code point identified by one of these escape sequences is converted to the actual server encoding; an error is reported if that's not possible. サーバ符号化方式がUTF-8でない場合、このエスケープシーケンスの1つで指定されたUnicodeコードポイントは実際のサーバ符号化方式へと変換されます。それが可能でない場合にはエラーが報告されます。

Also, the Unicode escape syntax for string constants only works when the configuration parameter <xref linkend="guc-standard-conforming-strings"/> is turned on. This is because otherwise this syntax could confuse clients that parse the SQL statements to the point that it could lead to SQL injections and similar security issues. If the parameter is set to off, this syntax will be rejected with an error message. また、文字列定数に対するユニコードエスケープ構文は設定パラメータstandard_conforming_stringsが有効なときのみ動作します。 そうでないとこの構文は、SQL文を構文解釈するクライアントを混乱させ、SQLインジェクションや、それに類似したセキュリティ問題に繋がることさえあるからです。 パラメータがoffに設定されていれば、この構文はエラーメッセージを出して拒絶されます。

4.1.2.4. ドル記号で引用符付けされた文字列定数 #

<title>Dollar-Quoted String Constants</title>

While the standard syntax for specifying string constants is usually convenient, it can be difficult to understand when the desired string contains many single quotes, since each of those must be doubled. To allow more readable queries in such situations, <productname>PostgreSQL</productname> provides another way, called <quote>dollar quoting</quote>, to write string constants. A dollar-quoted string constant consists of a dollar sign (<literal>$</literal>), an optional <quote>tag</quote> of zero or more characters, another dollar sign, an arbitrary sequence of characters that makes up the string content, a dollar sign, the same tag that began this dollar quote, and a dollar sign. For example, here are two different ways to specify the string <quote>Dianne's horse</quote> using dollar quoting: 文字列定数の標準の構文はたいていの場合便利ですが、対象とする文字列内に多くの単一引用符があると、それらを全て二重にしなければなりませんので理解しづらくなります。 こうした状況においても問い合わせの可読性をより高めるためにPostgreSQLは、ドル引用符付けという他の文字列定数の指定方法を提供します。 ドル引用符付けされた文字列定数は、ドル記号($)、省略可能な0個以上の文字からなるタグ、ドル記号、文字列定数を構成する任意の文字の並び、ドル記号、この引用符付けの始めに指定したものと同じタグ、ドル記号から構成されます。 例えば、Dianne's horseという文字列をドル引用符付けを使用して指定する方法を、以下に2つ示します。

$$Dianne's horse$$
$SomeTag$Dianne's horse$SomeTag$

Notice that inside the dollar-quoted string, single quotes can be used without needing to be escaped. Indeed, no characters inside a dollar-quoted string are ever escaped: the string content is always written literally. Backslashes are not special, and neither are dollar signs, unless they are part of a sequence matching the opening tag. ドル引用符付けされた文字列の内側では、単一引用符をエスケープすることなく使用できることを理解してください。 実際には、ドル引用符付けされた文字列の内側の文字はまったくエスケープが必要なく、文字列定数はすべてそのまま記述できます。 その並びが開始タグに一致しない限り、バックスラッシュもドル記号も特別なものではありません。

It is possible to nest dollar-quoted string constants by choosing different tags at each nesting level. This is most commonly used in writing function definitions. For example: 各入れ子レベルに異なるタグを付けることで、ドル引用符付けされた文字列を入れ子にできます。 これは、関数定義を作成する時に非常によく使用されます。 以下に例を示します。

$function$
BEGIN
    RETURN ($1 ~ $q$[\t\r\n\v\\]$q$);
END;
$function$

Here, the sequence <literal>$q$[\t\r\n\v\\]$q$</literal> represents a dollar-quoted literal string <literal>[\t\r\n\v\\]</literal>, which will be recognized when the function body is executed by <productname>PostgreSQL</productname>. But since the sequence does not match the outer dollar quoting delimiter <literal>$function$</literal>, it is just some more characters within the constant so far as the outer string is concerned. ここで、$q$[\t\r\n\v\\]$q$は、ドル引用符付けされた[\t\r\n\v\\]リテラル文字列を表し、PostgreSQLがこの関数本体を実行する時に認識されます。 しかし、この並びは、外側のドル引用符用の区切り文字$function$に一致しませんので、外側の文字列を対象としている場合は単なる文字の並びとなります。

The tag, if any, of a dollar-quoted string follows the same rules as an unquoted identifier, except that it cannot contain a dollar sign. Tags are case sensitive, so <literal>$tag$String content$tag$</literal> is correct, but <literal>$TAG$String content$tag$</literal> is not. もしあれば、ドル引用符付けされた文字列のタグは、引用符付けされていない識別子と同じ規則に従います。 ただし、タグにドル記号を含めることはできません。 タグは大文字小文字を区別します。 したがって、$tag$String content$tag$は正しいのですが、$TAG$String content$tag$は間違いです。

A dollar-quoted string that follows a keyword or identifier must be separated from it by whitespace; otherwise the dollar quoting delimiter would be taken as part of the preceding identifier. キーワードや識別子の後にドル引用符付けされた文字列を続ける場合は、空白でそれを区切らなければなりません。 さもないと、ドル引用符の区切り文字は、直前の識別子の一部として解釈されます。

Dollar quoting is not part of the SQL standard, but it is often a more convenient way to write complicated string literals than the standard-compliant single quote syntax. It is particularly useful when representing string constants inside other constants, as is often needed in procedural function definitions. With single-quote syntax, each backslash in the above example would have to be written as four backslashes, which would be reduced to two backslashes in parsing the original string constant, and then to one when the inner string constant is re-parsed during function execution. ドル引用符付けは、標準SQLで定義されていません。 しかし、複雑な文字列リテラルを記述する場合は標準準拠の単一引用符構文よりも便利なことがよくあります。 特に、他の定数の内部に文字列定数を記述するような場合は役に立ちます。 こうした状況は手続き関数の定義でよく必要とされます。 単一引用符構文では、上の例のバックスラッシュはそれぞれ、4個のバックスラッシュで記述しなければなりません。 この4つのバックスラッシュは、元の文字列定数を解析する際に2つに減少され、そして、関数を実行する際に内部の文字列定数が再解析され1つに減少します。

4.1.2.5. ビット文字列定数 #

<title>Bit-String Constants</title>

Bit-string constants look like regular string constants with a <literal>B</literal> (upper or lower case) immediately before the opening quote (no intervening whitespace), e.g., <literal>B'1001'</literal>. The only characters allowed within bit-string constants are <literal>0</literal> and <literal>1</literal>. ビット文字列定数はB(大文字もしくは小文字)が始まりの引用符の前に付いている(間に空白はありません)通常の文字列定数のように見えます。 例えばB'1001'のようになります。 ビット文字列定数の中で許可される文字は01のみです。

Alternatively, bit-string constants can be specified in hexadecimal notation, using a leading <literal>X</literal> (upper or lower case), e.g., <literal>X'1FF'</literal>. This notation is equivalent to a bit-string constant with four binary digits for each hexadecimal digit. その他にも、ビット文字列定数はX'1FF'といった具合に、先頭にX(大文字または小文字)を使用して16進表記で指定することもできます。 この表記は、各16進数値をそれぞれ4つの2進数値に置き換えたビット文字列定数と同等です。

Both forms of bit-string constant can be continued across lines in the same way as regular string constants. Dollar quoting cannot be used in a bit-string constant. どちらの形式のビット文字列定数でも、通常の文字列定数と同じように複数行にわたって続けて書くことができます。 ドル引用符付けはビット文字列定数で使用できません。

4.1.2.6. 数値定数 #

<title>Numeric Constants</title>

Numeric constants are accepted in these general forms: 数値定数は下記の一般的な形で受け付けられます。

digits
digits.[digits][e[+-]digits]
[digits].digits[e[+-]digits]
digitse[+-]digits

where <replaceable>digits</replaceable> is one or more decimal digits (0 through 9). At least one digit must be before or after the decimal point, if one is used. At least one digit must follow the exponent marker (<literal>e</literal>), if one is present. There cannot be any spaces or other characters embedded in the constant, except for underscores, which can be used for visual grouping as described below. Note that any leading plus or minus sign is not actually considered part of the constant; it is an operator applied to the constant. ここでdigitsは1つ以上の10進数字(0〜9)です。 小数点を使用する場合は、少なくとも1つの数字が小数点の前か後になくてはなりません。 指数記号eの付く形式を使う場合にはeの後に少なくとも1つの数字がなければいけません。 以下に示す視覚的なグループ化のために使われるアンダースコア以外には、空白や他の文字は、定数の中に埋め込むことはできません。 プラスまたはマイナスの符号を先頭につけても、定数の一部とはみなされないことに注意してください。 これらの符号は定数に適用される演算子とみなされます。

These are some examples of valid numeric constants: 下記は有効な数値定数のいくつかの例です。


42
3.5
4.
.001
5e2
1.925e-3

Additionally, non-decimal integer constants are accepted in these forms: さらに、以下の形式で非10進整数定数を受け入れます。

0xhexdigits
0ooctdigits
0bbindigits

where <replaceable>hexdigits</replaceable> is one or more hexadecimal digits (0-9, A-F), <replaceable>octdigits</replaceable> is one or more octal digits (0-7), and <replaceable>bindigits</replaceable> is one or more binary digits (0 or 1). Hexadecimal digits and the radix prefixes can be in upper or lower case. Note that only integers can have non-decimal forms, not numbers with fractional parts. ここで、hexdigitsは1つ以上の16進数(0-9、A-F)、octdigitsは1つ以上の8進数(0-7)、bindigitsは1つ以上の2進数(0または1)です。 16進数と基数のプレフィックスは、大文字または小文字で指定できます。 小数部のある数字ではなく、整数のみが非10進形式になることに注意してください。

These are some examples of valid non-decimal integer constants: 以下に、有効な非10進整数定数の例を示します。


0b100101
0B10011001
0o273
0O755
0x42f
0XFFFF

For visual grouping, underscores can be inserted between digits. These have no further effect on the value of the constant. For example: 視覚的なグループ化のために、数字の間にアンダースコアを挿入できます。 これらは、定数の値にさらなる影響を与えません。 例:


1_500_000_000
0b10001000_00000000
0o_1_755
0xFFFF_FFFF
1.618_034

Underscores are not allowed at the start or end of a numeric constant or a group of digits (that is, immediately before or after the decimal point or the exponent marker), and more than one underscore in a row is not allowed. 数値定数または数値グループの先頭または末尾にアンダースコアを使用できません(つまり、小数点や指数記号の直前または直後にアンダースコアを使用できません)し、複数のアンダースコアを続けて使用することもできません。

A numeric constant that contains neither a decimal point nor an exponent is initially presumed to be type <type>integer</type> if its value fits in type <type>integer</type> (32 bits); otherwise it is presumed to be type <type>bigint</type> if its value fits in type <type>bigint</type> (64 bits); otherwise it is taken to be type <type>numeric</type>. Constants that contain decimal points and/or exponents are always initially presumed to be type <type>numeric</type>. 小数点も指数も含まない数値定数の場合、まずその値がinteger型(32ビット)に収まればinteger型であるとみなされます。 そうでない場合、bigint型(64ビット)で収まればbigint型とみなされます。 どちらでもない場合は、numeric型とみなされます。 定数が小数点または指数あるいはその両方を含む場合は、常に最初にnumeric型であるとみなされます。

The initially assigned data type of a numeric constant is just a starting point for the type resolution algorithms. In most cases the constant will be automatically coerced to the most appropriate type depending on context. When necessary, you can force a numeric value to be interpreted as a specific data type by casting it.<indexterm><primary>type cast</primary></indexterm> For example, you can force a numeric value to be treated as type <type>real</type> (<type>float4</type>) by writing: 数値定数に最初に割り振られるデータ型は、型解決アルゴリズムの開始点に過ぎません。 ほとんどの場合、定数は文脈に基づいて自動的に最も適切な型に変換されます。 必要であれば、特定のデータ型にキャストして、数値がそのデータ型として解釈されるように強制できます。 例えば、以下のようにして数値をreal型(float4)として処理できます。


REAL '1.23'  &#45;- string style
1.23::REAL   &#45;- PostgreSQL (historical) style

REAL '1.23'  -- 文字列書式
1.23::REAL   -- (歴史的な)PostgreSQL書式

These are actually just special cases of the general casting notations discussed next. 実のところ、これらは以下で説明する一般的なキャスト記法の特別な場合です。

4.1.2.7. 他の型の定数 #

<title>Constants of Other Types</title>

A constant of an <emphasis>arbitrary</emphasis> type can be entered using any one of the following notations: 任意の型の定数は下記の表記のいずれかを使って入力できます。

type 'string'
'string'::type
CAST ( 'string' AS type )

The string constant's text is passed to the input conversion routine for the type called <replaceable>type</replaceable>. The result is a constant of the indicated type. The explicit type cast can be omitted if there is no ambiguity as to the type the constant must be (for example, when it is assigned directly to a table column), in which case it is automatically coerced. 文字列定数のテキストはtypeと呼ばれる型の入力変換ルーチンへと渡されます。 結果は指示された型の定数です。 明示的な型キャストは、定数がどの型でなければならないかについて曖昧な点がなければ(例えば定数が直接テーブル列に代入されている場合)省略しても構いません。 その場合自動的に型強制されます。

The string constant can be written using either regular SQL notation or dollar-quoting. 文字列定数は通常のSQL記法でもドル引用符付けでも記述できます。

It is also possible to specify a type coercion using a function-like syntax: 関数のような構文を使って型強制を指定することも可能です。

typename ( 'string' )

but not all type names can be used in this way; see <xref linkend="sql-syntax-type-casts"/> for details. しかし、全ての型の名前でこの方法は使用できるというわけではありません。 詳細は4.2.9を参照してください。

The <literal>::</literal>, <literal>CAST()</literal>, and function-call syntaxes can also be used to specify run-time type conversions of arbitrary expressions, as discussed in <xref linkend="sql-syntax-type-casts"/>. To avoid syntactic ambiguity, the <literal><replaceable>type</replaceable> '<replaceable>string</replaceable>'</literal> syntax can only be used to specify the type of a simple literal constant. Another restriction on the <literal><replaceable>type</replaceable> '<replaceable>string</replaceable>'</literal> syntax is that it does not work for array types; use <literal>::</literal> or <literal>CAST()</literal> to specify the type of an array constant. ::CAST()や関数呼び出し構文は、4.2.9で説明する通り、任意の式の実行時の型変換を指定するために使うこともできます。 構文的なあいまいさをなくすために、type 'string'という形式は単なるリテラル定数を指定する場合にのみ使うことができます。 この他type 'string'構文には、配列型では動作しないという制限があります。 配列型の定数の型を指定する場合は::CAST()を使用してください。

The <literal>CAST()</literal> syntax conforms to SQL. The <literal><replaceable>type</replaceable> '<replaceable>string</replaceable>'</literal> syntax is a generalization of the standard: SQL specifies this syntax only for a few data types, but <productname>PostgreSQL</productname> allows it for all types. The syntax with <literal>::</literal> is historical <productname>PostgreSQL</productname> usage, as is the function-call syntax. CAST()構文はSQLに従っています。 type 'string'構文は、標準を一般化したものです。 SQLでは、この構文を数個のデータ型でのみ規定しています。 しかし、PostgreSQLではすべての型で使用できます。 ::付きの構文は、歴史的にPostgreSQLで使用されてきました。 関数呼び出し構文も同じく歴史的に使用されているものです。

4.1.3. 演算子 #

<title>Operators</title>

An operator name is a sequence of up to <symbol>NAMEDATALEN</symbol>-1 (63 by default) characters from the following list: 演算子はNAMEDATALEN-1(デフォルトは63)までの長さの、以下に示すリストに含まれる文字の並びです。


+ - * / < > = ~ ! @ # % ^ & | ` ?

There are a few restrictions on operator names, however: しかし、演算子の名前にはいくつかの制約があります。

  • <literal>&#45;-</literal> and <literal>/*</literal> cannot appear anywhere in an operator name, since they will be taken as the start of a comment. --/*は演算子名の中に使うことができません。 なぜならこれらはコメントの始まりと解釈されるからです。

  • A multiple-character operator name cannot end in <literal>+</literal> or <literal>-</literal>, unless the name also contains at least one of these characters: 複数文字の演算子名は、その名前が少なくとも下記の文字の1つ以上を含まない限り、+-で終わることができません。


    ~ ! @ # % ^ & | ` ?

    For example, <literal>@-</literal> is an allowed operator name, but <literal>*-</literal> is not. This restriction allows <productname>PostgreSQL</productname> to parse SQL-compliant queries without requiring spaces between tokens. 例えば、@-は演算子名として認められていますが、*-は認められていません。 この制限によりPostgreSQLは、SQLに準拠する問い合わせをトークン同士の間に空白を要求せず、解析できます。

When working with non-SQL-standard operator names, you will usually need to separate adjacent operators with spaces to avoid ambiguity. For example, if you have defined a prefix operator named <literal>@</literal>, you cannot write <literal>X*@Y</literal>; you must write <literal>X* @Y</literal> to ensure that <productname>PostgreSQL</productname> reads it as two operator names not one. 非SQL標準の演算子名を使う場合、通常は曖昧さを回避するために、隣り合った演算子を空白で区切る必要があります。 例えば@という前置演算子を定義した場合、X*@Yとは書けません。 PostgreSQLがこれを確実に1つではなく2つの演算子名として解釈できるように、X* @Yと書く必要があります。

4.1.4. 特殊文字 #

<title>Special Characters</title>

Some characters that are not alphanumeric have a special meaning that is different from being an operator. Details on the usage can be found at the location where the respective syntax element is described. This section only exists to advise the existence and summarize the purposes of these characters. 英数字ではないいくつかの文字は、演算子であることとは異なる特殊な意味を持っています。 使用方法の詳細はそれぞれの構文要素についてのところで説明します。 本節では、単にその存在を知らせ、これらの文字の目的をまとめるに留めます。

  • A dollar sign (<literal>$</literal>) followed by digits is used to represent a positional parameter in the body of a function definition or a prepared statement. In other contexts the dollar sign can be part of an identifier or a dollar-quoted string constant. 直後に数字が続くドル記号($)は、関数定義の本体またはプリペアド文中の位置パラメータを表すために使われます。 他の文脈ではドル記号は識別子名の一部であるかもしれませんし、ドル引用符付けされた文字列定数の一部であるかもしれません。

  • Parentheses (<literal>()</literal>) have their usual meaning to group expressions and enforce precedence. In some cases parentheses are required as part of the fixed syntax of a particular SQL command. 括弧(())は、通常通り式をまとめ優先するという意味を持ちます。 場合によっては括弧は、特定のSQLコマンドの固定構文の一部として要求されることがあります。

  • Brackets (<literal>[]</literal>) are used to select the elements of an array. See <xref linkend="arrays"/> for more information on arrays. 大括弧([])は、配列要素を選択するために使われます。 配列に関する詳しい情報は8.15を参照してください。

  • Commas (<literal>,</literal>) are used in some syntactical constructs to separate the elements of a list. カンマ(,)は、リストの要素を区切るために構文的構成体で使われることがあります。

  • The semicolon (<literal>;</literal>) terminates an SQL command. It cannot appear anywhere within a command, except within a string constant or quoted identifier. セミコロン(;)は、SQLコマンドの終わりを意味します。 文字列定数または引用符付き識別子以外では、コマンドの途中では使うことができません。

  • The colon (<literal>:</literal>) is used to select <quote>slices</quote> from arrays. (See <xref linkend="arrays"/>.) In certain SQL dialects (such as Embedded SQL), the colon is used to prefix variable names. コロン(:)は、配列から一部分を取り出すために使われます (8.15を参照してください)。 いくつかのSQL方言(埋め込みSQLなど)では、コロンは変数名の接頭辞として使われます。

  • The asterisk (<literal>*</literal>) is used in some contexts to denote all the fields of a table row or composite value. It also has a special meaning when used as the argument of an aggregate function, namely that the aggregate does not require any explicit parameter. アスタリスク(*)は、いくつかの文脈において、テーブル行や複合型の全てのフィールドを表現するために使用されます。 また、集約関数の引数として使われる場合も特殊な、つまり、その集約が明示的なパラメータをまったく必要としないという意味を持ちます。

  • The period (<literal>.</literal>) is used in numeric constants, and to separate schema, table, and column names. ピリオド(.)は数値定数の中で使われます。 また、スキーマ名、テーブル名、列名を区切るためにも使われます。

4.1.5. コメント #

<title>Comments</title>

A comment is a sequence of characters beginning with double dashes and extending to the end of the line, e.g.: コメントは二重ハイフンで始まる文字の並びで、行の終わりまで続きます。 例えば以下のようになります。


&#45;- This is a standard SQL comment

-- これは標準SQLのコメントです

Alternatively, C-style block comments can be used: 他にも、C言語様式のブロックコメントも使用できます。


/* multiline comment
 * with nesting: /* nested block comment */

/* ネストされた複数行にわたる
 * コメント /* ネストされたブロックコメント */
 */

where the comment begins with <literal>/*</literal> and extends to the matching occurrence of <literal>*/</literal>. These block comments nest, as specified in the SQL standard but unlike C, so that one can comment out larger blocks of code that might contain existing block comments. コメントは/*で始まり、対応する*/で終わります。 これらのブロックコメントはC言語とは異なり、標準SQLで規定されているように入れ子にできます。 したがって、既存のブロックコメントを含む可能性のある大きなコードのブロックをコメントアウトできます。

A comment is removed from the input stream before further syntax analysis and is effectively replaced by whitespace. コメントは、その後の構文解析が行われる前に入力ストリームから取り去られ、事実上、空白で置き換えられます。

4.1.6. 演算子の優先順位 #

<title>Operator Precedence</title>

<xref linkend="sql-precedence-table"/> shows the precedence and associativity of the operators in <productname>PostgreSQL</productname>. Most operators have the same precedence and are left-associative. The precedence and associativity of the operators is hard-wired into the parser. Add parentheses if you want an expression with multiple operators to be parsed in some other way than what the precedence rules imply. 表 4.2は、PostgreSQLの演算子の優先順位と結合性を示しています。 ほとんどの演算子は同じ優先順位を持ち、左結合します。 演算子の優先順位と結合性はパーサに組み込まれています。 複数の演算子のある式を優先順位の規則が意味するのとは異なる順序で解析したい場合には、括弧で囲ってください。

表4.2 演算子の優先順位(高いものから低いものへ)

<title>Operator Precedence (highest to lowest)</title>
演算子/要素結合性説明
.テーブル/列名の区切り文字
::PostgreSQL方式の型キャスト
[ ]配列要素選択
+ -単項加算、単項減算
^累乗
* / %掛け算、割り算、剰余
+ -加算、減算
(その他の演算子)その他全ての組み込み、あるいはユーザ定義の演算子
BETWEEN IN LIKE ILIKE SIMILAR 範囲内に包含、集合の要素、文字列の一致
< > = <= >= <>  比較演算子
IS ISNULL NOTNULL IS TRUEIS FALSEIS NULLIS DISTINCT FROM、その他
NOT論理否定
AND論理積
OR論理和

Note that the operator precedence rules also apply to user-defined operators that have the same names as the built-in operators mentioned above. For example, if you define a <quote>+</quote> operator for some custom data type it will have the same precedence as the built-in <quote>+</quote> operator, no matter what yours does. 演算子優先順位の規則は、上記で触れた組み込み演算子と同じ名前を持つユーザ定義演算子にも当てはまります。 例えばもし+演算子をある独自のデータ型に定義すると、新しい演算子が何をするかにかかわらず、+組み込み演算子と同じ優先順位を持つようになります。

When a schema-qualified operator name is used in the <literal>OPERATOR</literal> syntax, as for example in: 次の例のように、OPERATOR構文でスキーマで修飾された演算子名を使用する場合、

SELECT 3 OPERATOR(pg_catalog.+) 4;

the <literal>OPERATOR</literal> construct is taken to have the default precedence shown in <xref linkend="sql-precedence-table"/> for <quote>any other operator</quote>. This is true no matter which specific operator appears inside <literal>OPERATOR()</literal>. OPERATOR構文は、表 4.2その他の演算子で示されているデフォルトの優先順位を持つとみなされます。 これは、OPERATOR()にどの特定の演算子が入る場合でも変わりません。

注記

<productname>PostgreSQL</productname> versions before 9.5 used slightly different operator precedence rules. In particular, <token>&lt;=</token> <token>&gt;=</token> and <token>&lt;&gt;</token> used to be treated as generic operators; <literal>IS</literal> tests used to have higher priority; and <literal>NOT BETWEEN</literal> and related constructs acted inconsistently, being taken in some cases as having the precedence of <literal>NOT</literal> rather than <literal>BETWEEN</literal>. These rules were changed for better compliance with the SQL standard and to reduce confusion from inconsistent treatment of logically equivalent constructs. In most cases, these changes will result in no behavioral change, or perhaps in <quote>no such operator</quote> failures which can be resolved by adding parentheses. However there are corner cases in which a query might change behavior without any parsing error being reported. 9.5より前のPostgreSQLのバージョンでは少し異なる演算子優先順位規則を使っていました。 特に<=>=<>は一般的な演算子として扱われていました。ISテストは高い優先順位を持つとして使われていました。NOT BETWEENとそれに関係する構文は振る舞いが一貫しておらず、BETWEENではなくNOTの優先順位を持つと見なされる場合がありました。 標準SQLにより準拠し、論理的に等しい構文の一貫しない扱いから来る混乱を減らすように、これらの規則は変更されました。 ほとんどの場合、これらの変更により振る舞いが変わることはないでしょうし、もし変わっても恐らくno such operatorで失敗になるくらいでしょう。後者は括弧を追加することで解決できるでしょう。 しかしながら、稀に問い合わせがパースエラーを返すことなく振る舞いを変える場合があります。