MySQL STRCMP() Function
In MySQL, the STRCMP() function compares two strings and returns the result of the comparison. The function compares two strings based on the collation of the strings.
STRCMP() Syntax
Here is the syntax of MySQL STRCMP() function:
STRCMP(str1, str2)
Parameters
str1- Required. A string to be compared.
str2- Required. Another string to be compared.
Return value
The STRCMP(str1, str2) function returns the result of comparing two strings.
- If
str1equalsstr2, this function will return0. - If
str1is less thanstr2, this function will return-1. - If
str1is greater thanstr2, this function will return1. - The function will return
NULLif any of the arguments areNULL.
STRCMP() Examples
Here are some examples of MySQL STRCMP() function.
SELECT
STRCMP('hello', 'hello'),
STRCMP('hello1', 'hello'),
STRCMP('hello', 'hello1'),
STRCMP('hello', 'world'),
STRCMP(NULL, NULL)\G
STRCMP('hello', 'hello'): 0
STRCMP('hello1', 'hello'): 1
STRCMP('hello', 'hello1'): -1
STRCMP('hello', 'world'): -1
STRCMP(NULL, NULL): NULLThe STRCMP() function compares two strings based on the collation of the strings. Let’s look at the following example:
SET @s1 = _utf8mb4 'x' COLLATE utf8mb4_0900_ai_ci;
SET @s2 = _utf8mb4 'X' COLLATE utf8mb4_0900_ai_ci;
SET @s3 = _utf8mb4 'x' COLLATE utf8mb4_0900_as_cs;
SET @s4 = _utf8mb4 'X' COLLATE utf8mb4_0900_as_cs;
SELECT STRCMP(@s1, @s2), STRCMP(@s3, @s4);
+------------------+------------------+
| STRCMP(@s1, @s2) | STRCMP(@s3, @s4) |
+------------------+------------------+
| 0 | -1 |
+------------------+------------------+Here:
- The collation (
utf8mb4_0900_ai_ci) of@s1and@s2is case-insensitive, soSTRCMP(@s1, @s2)returns0. - The collation (
utf8mb4_0900_as_cs) of@s1and@s2is case-insensitive, soSTRCMP(@s1, @s2)returns-1.