@@ -1100,6 +1100,61 @@ SELECT concat_values('|', 1, 4, 2);
1100
1100
</screen>
1101
1101
</para>
1102
1102
</sect2>
1103
+
1104
+ <sect2>
1105
+ <title><acronym>SQL</acronym> Functions with Collations</title>
1106
+
1107
+ <indexterm>
1108
+ <primary>collation</>
1109
+ <secondary>in SQL functions</>
1110
+ </indexterm>
1111
+
1112
+ <para>
1113
+ When a SQL function has one or more parameters of collatable data types,
1114
+ a collation is identified for each function call depending on the
1115
+ collations assigned to the actual arguments, as described in <xref
1116
+ linkend="collation">. If a collation is successfully identified
1117
+ (i.e., there are no conflicts of implicit collations among the arguments)
1118
+ then all the collatable parameters are treated as having that collation
1119
+ implicitly. This will affect the behavior of collation-sensitive
1120
+ operations within the function. For example, using the
1121
+ <function>anyleast</> function described above, the result of
1122
+ <programlisting>
1123
+ SELECT anyleast('abc'::text, 'ABC');
1124
+ </programlisting>
1125
+ will depend on the database's default collation. In <literal>C</> locale
1126
+ the result will be <literal>ABC</>, but in many other locales it will
1127
+ be <literal>abc</>. The collation to use can be forced by adding
1128
+ a <literal>COLLATE</> clause to any of the arguments, for example
1129
+ <programlisting>
1130
+ SELECT anyleast('abc'::text, 'ABC' COLLATE "C");
1131
+ </programlisting>
1132
+ Alternatively, if you wish a function to operate with a particular
1133
+ collation regardless of what it is called with, insert
1134
+ <literal>COLLATE</> clauses as needed in the function definition.
1135
+ This version of <function>anyleast</> would always use <literal>en_US</>
1136
+ locale to compare strings:
1137
+ <programlisting>
1138
+ CREATE FUNCTION anyleast (VARIADIC anyarray) RETURNS anyelement AS $$
1139
+ SELECT min($1[i] COLLATE "en_US") FROM generate_subscripts($1, 1) g(i);
1140
+ $$ LANGUAGE SQL;
1141
+ </programlisting>
1142
+ But note that this will throw an error if applied to a non-collatable
1143
+ data type.
1144
+ </para>
1145
+
1146
+ <para>
1147
+ If no common collation can be identified among the actual arguments,
1148
+ then a SQL function treats its parameters as having their data types'
1149
+ default collation (which is usually the database's default collation,
1150
+ but could be different for parameters of domain types).
1151
+ </para>
1152
+
1153
+ <para>
1154
+ The behavior of collatable parameters can be thought of as a limited
1155
+ form of polymorphism, applicable only to textual data types.
1156
+ </para>
1157
+ </sect2>
1103
1158
</sect1>
1104
1159
1105
1160
<sect1 id="xfunc-overload">
0 commit comments