// conversion reference

SQL COLLATE clause

x COLLATE utf8mb4_bin changes how x is compared right there (case-sensitive equality, custom ordering) without changing the value or the column.

カテゴリ
Conversion
Returns
same type as the expression
In this category
22 of 39

構文

expression COLLATE collation_name

エンジンサポート

エンジンSupportメモ
SQL Server はい Supported under this name.
PostgreSQL はい Supported under this name.
MySQL はい Supported under this name.
SQLite Different name or syntax built-in collations only: BINARY, NOCASE, RTRIM
Oracle Different name or syntax 12.2+ supports expression COLLATE; NLSSORT is the older route

例

SQL Server

SELECT name FROM users
ORDER BY name COLLATE Latin1_General_CS_AS;

MySQL

SELECT * FROM users
WHERE name = 'matt' COLLATE utf8mb4_bin;

SQLite

SELECT * FROM users ORDER BY name COLLATE NOCASE;

知っておくと便利なこと

  • COLLATE changes comparison semantics, not the value: 'MATT' = 'matt' is true under a case-insensitive collation (_CI on SQL Server, _ci on MySQL) and false under _CS or _bin.
  • PostgreSQL's default collations are already case-sensitive, so 'a' = 'A' is false without any COLLATE. Case-insensitive matching there needs a nondeterministic ICU collation, ILIKE or lower() on both sides.
  • Collation names never port: SQL Server's Windows collations, MySQL's utf8mb4_* and PostgreSQL's libc/ICU names are unrelated vocabularies with overlapping intent.
  • COLLATE inside a WHERE on an indexed column can prevent index use on MySQL and SQL Server; set the collation at column level when one rule should always apply.
  • SQLite ships only BINARY, NOCASE and RTRIM, and NOCASE folds ASCII letters only: 'É' and 'é' still differ. Anything else needs a collation registered by the application.

Questions about COLLATE

How do I make one comparison case-sensitive?

Add a case-sensitive collation to the expression: utf8mb4_bin (MySQL), Latin1_General_CS_AS (SQL Server), COLLATE BINARY (SQLite), BINARY via COLLATE or NLSSORT (Oracle). PostgreSQL is case-sensitive by default. It affects only that comparison.

Does COLLATE work on any expression?

Yes: a column, a literal or a computed string. But applying it in a predicate against an indexed column can cost you the index; prefer column-level collation for standing rules.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.