// strings reference

SQL STRCMP function

Three-way comparison: negative when the first sorts first, 0 on equality, positive otherwise. Case sensitivity comes from the collation, not the function.

Категория
Strings
Returns
integer
In this category
83 of 172

Синтаксис

STRCMP(string1, string2)

Поддержка движка

ДвижокSupportЗаметки
SQL Server Not built in No built-in equivalent.
PostgreSQL Not built in No built-in equivalent.
MySQL Да Supported under this name.
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

Примеры

MySQL

SELECT STRCMP('apple', 'banana') AS c;  -- -1

MySQL

SELECT STRCMP('apple', 'Apple') AS c;  -- 0 under a _ci collation

Полезно знать

  • Collation-driven: under a _ci collation STRCMP('apple', 'Apple') is 0; under utf8mb4_bin it is 1, because 'a' (97) sorts after 'A' (65). The function adds no case rules of its own.
  • NULL if either argument is NULL; it never treats NULL as a sortable value.
  • Other engines build it with CASE WHEN a < b THEN -1 WHEN a = b THEN 0 ELSE 1 END, or skip it and ORDER BY, which needs no helper.
  • Useful as a sort key expression and in CASE ranges; for matching, = and < already follow the same collation.

Questions about STRCMP

Is STRCMP case-sensitive?

Only if the collation is: _ci collations treat 'apple' and 'Apple' as equal (returns 0), _bin collations order them apart. The collation decides, not the function.

What is the SQL Server equivalent?

None by name; the idiom is CASE WHEN a < b THEN -1 WHEN a = b THEN 0 ELSE 1 END, which follows the column collation the same way STRCMP does.

Why use STRCMP instead of < and =?

It yields one sortable integer, handy as an expression in ORDER BY, CASE and application-style three-way logic, where operators would need three branches.

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: MySQL.

// 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.