MySQL STRCMP() Function
The MySQL STRCMP() function checks whether two strings are the same using the current character set. Based on the value of string1 and string2, the function returns the following:
- Returns -1, if string1 is smaller than string2.
- Returns 0, if string1 and string2 are the same.
- Returns 1, if string1 is larger than string2.
Syntax
STRCMP(string1, string2)
Parameters
string1 |
Required. Specify the first string to be compared. |
string2 |
Required. Specify the second string to be compared. |
Return Value
Returns the following value:
- Returns -1, if string1 is smaller than string2.
- Returns 0, if string1 and string2 are the same.
- Returns 1, if string1 is larger than string2.
Example 1:
The example below shows the usage of STRCMP() function.
mysql> SELECT STRCMP('Hello', 'Hello'); Result: 0 mysql> SELECT STRCMP('Hello', 'World'); Result: -1 mysql> SELECT STRCMP('World', 'Hello'); Result: 1 mysql> SELECT STRCMP('HELLO', 'hello'); Result: 0
Example 2:
Consider a database table called Employee with the following records:
EmpID | FirstName | LastName |
---|---|---|
1 | John | Smith |
2 | Marry | Knight |
3 | Jo | Williams |
4 | Kim | Fischer |
5 | Ramesh | Gupta |
6 | Huang | Zhang |
In the query below, the STRCMP() function is used to compare the records of column FirstName and column LastName.
SELECT *, STRCMP(FirstName, LastName) AS STRCMP_Value FROM Employee;
This will produce the result as shown below:
EmpID | FirstName | LastName | STRCMP_Value |
---|---|---|---|
1 | John | Smith | -1 |
2 | Marry | Knight | 1 |
3 | Jo | Williams | -1 |
4 | Kim | Fischer | 1 |
5 | Ramesh | Gupta | 1 |
6 | Huang | Zhang | -1 |
❮ MySQL Functions