MySQL STRCMP Function | Compare Two Strings

MySQL STRCMP is an inbuilt Function in MySQL. It compares two strings and returns 0 if both of them are the same. Also, it returns -1 if the first string is smaller than the second and returns 1 on the other way round according to the sort order. In this article, we will discuss the MySQL STRCMP Function. Also, we will discuss a few examples of using it.

Note: It is frequently misunderstood that the function compares on the basis of length of strings. However, it compares on the sort order and not their length. Hence for example, z > a.

Syntax

STRCMP (string1, string2)

Parameters

The MySQL STRCMP Function expects two parameters. You need to pass both the strings you want to compare. Also, both the parameters are mandatory. The description of the parameters is as follows:

  • string1: The first string for comparison.
  • string2: The second string for comparison.

Return Value

The function returns the following:

  • 0, if string1 = string2.
  • -1, if string1 < string2 according to the sort order.
  • 1 if string1 > string2 according to the sort order.
MySQL STRCMP Function Diagram

Examples

Let’s discuss a few examples of using the function.

Example 1: Equal Strings

mysql> SELECT STRCMP("Equal String", "Equal String") as compare;
+---------+
| compare |
+---------+
|       0 |
+---------+

The function returns 0 when both strings are equal.

Example 2: First String Smaller in Sort Order

mysql> SELECT STRCMP('az', 'z');
+-------------------+
| STRCMP('az', 'z') |
+-------------------+
|                -1 |
+-------------------+

When the first string is smaller in sort order, MySQL STRCMP Function returns -1. Observe in the example that the function compares on the sort order and not on the length of the strings.

Example 3: First String Bigger in Sort Order

Similarly, the function returns 1 when the first string is bigger in sort order than the second.

mysql> SELECT STRCMP('z', 'abcz');
+---------------------+
| STRCMP('z', 'abcz') |
+---------------------+
|                   1 |
+---------------------+

Conclusion

In conclusion, we discussed the MySQL STRCMP Function. It compares two strings and returns 0 when both are equal. Also, the comparison is done on the basis of sort order. You can read more about it on MySQL Official Documentation. Also, you can learn about more MySQL String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *