postgresql_16:6.6.3.6 Collation of PL/pgSQL Variables
PostgreSQL 16 > Server Programming > PL/pgSQL — SQL Procedural Language > Declarations > Collation of PL/pgSQL Variables
When a PL/pgSQL function has one or more parameters of collatable data types, a collation is identified for each function call depending on the collations assigned to the actual arguments, as described in (see postgresql_16:4.9.2). If a collation is successfully identified (i.e., there are no conflicts of implicit collations among the arguments) then all the collatable parameters are treated as having that collation implicitly. This will affect the behavior of collation-sensitive operations within the function. For example, consider CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$ BEGIN RETURN a < b; END; $$ LANGUAGE plpgsql; SELECT less_than(text_field_1, text_field_2) FROM table1; SELECT less_than(text_field_1, text_field_2 COLLATE "C") FROM table1; The first use of less_than will use the common collation of text_field_1 and text_field_2 for the comparison, while the second use will use C collation.
Furthermore, the identified collation is also assumed as the collation of any local variables that are of collatable types. Thus this function would not work any differently if it were written as CREATE FUNCTION less_than(a text, b text) RETURNS boolean AS $$ DECLARE local_a text := a; local_b text := b; BEGIN RETURN local_a < local_b; END; $$ LANGUAGE plpgsql;
If there are no parameters of collatable data types, or no common collation can be identified for them, then parameters and local variables use the default collation of their data type (which is usually the database's default collation, but could be different for variables of domain types).
A local variable of a collatable data type can have a different collation associated with it by including the COLLATE option in its declaration, for example DECLARE local_a text COLLATE "en_US"; This option overrides the collation that would otherwise be given to the variable according to the rules above.
Also, of course explicit COLLATE clauses can be written inside a function if it is desired to force a particular collation to be used in a particular operation. For example, CREATE FUNCTION less_than_c(a text, b text) RETURNS boolean AS $$ BEGIN RETURN a < b COLLATE "C"; END; $$ LANGUAGE plpgsql; This overrides the collations associated with the table columns, parameters, or local variables used in the expression, just as would happen in a plain SQL command.