RefLib

Reference library for AI

Back

postgresql_16:3.1.2.10 Collation Expressions

PostgreSQL 16 > The SQL Language > SQL Syntax > Value Expressions > Collation Expressions

The COLLATE clause overrides the collation of an expression. It is appended to the expression it applies to: *expr* COLLATE *collation* where *collation* is a possibly schema-qualified identifier. The COLLATE clause binds tighter than operators; parentheses can be used when necessary.

If no collation is explicitly specified, the database system either derives a collation from the columns involved in the expression, or it defaults to the default collation of the database if no column is involved in the expression.

The two common uses of the COLLATE clause are overriding the sort order in an ORDER BY clause, for example: SELECT a, b, c FROM tbl WHERE ... ORDER BY a COLLATE "C"; and overriding the collation of a function or operator call that has locale-sensitive results, for example: SELECT * FROM tbl WHERE a > 'foo' COLLATE "C"; Note that in the latter case the COLLATE clause is attached to an input argument of the operator we wish to affect. It doesn't matter which argument of the operator or function call the COLLATE clause is attached to, because the collation that is applied by the operator or function is derived by considering all arguments, and an explicit COLLATE clause will override the collations of all other arguments. (Attaching non-matching COLLATE clauses to more than one argument, however, is an error. For more details see (see postgresql_16:4.9.2).) Thus, this gives the same result as the previous example: SELECT * FROM tbl WHERE a COLLATE "C" > 'foo'; But this is an error: SELECT * FROM tbl WHERE (a > 'foo') COLLATE "C"; because it attempts to apply a collation to the result of the > operator, which is of the non-collatable data type boolean.

Back