w3resource

MySQL STRCMP() function

STRCMP() function

MySQL strcmp() function is used to compare two strings. It returns 0 if both of the strings are same and returns -1 when the first argument is smaller than the second according to the defined order and 1 when the second one is smaller the first one.

This function is useful in -

  • String comparison: Compare two strings and determine their relationship based on their lexicographical order.
  • Sorting: STRCMP() is often used for sorting. Using STRCMP(), you can sort data ascending or descending based on their lexicographical order.

Syntax:

STRCMP (expr1, expr2)

Argument:

Name Description
expr1 First string for comparison.
expr2 Second string for comparison.

Syntax Diagram:

MySQL STRCMP() Function - Syntax Diagram

MySQL Version: 8.0

Example : MySQL STRCMP() function

In the MySQL statement stated below, using the STRCMP() function, two strings are compared, and since it is found that the strings are same, it returns 0.

Code:

SELECT STRCMP('mytesttext', 'mytesttext');

Output:

mysql> SELECT STRCMP('mytesttext', 'mytesttext');
+------------------------------------+
| STRCMP('mytesttext', 'mytesttext') |
+------------------------------------+
|                                  0 | 
+------------------------------------+
1 row in set (0.01 sec)

MySQL STRCMP() function with unmatched strings

The MySQL statement stated below, using the STRCMP() function to compare two strings and returns -1 according to the default comparison behavior

Code:

SELECT STRCMP('mytesttext', 'mytest_text');

Output:

mysql> SELECT STRCMP('mytesttext', 'mytest_text');
+-------------------------------------+
| STRCMP('mytesttext', 'mytest_text') |
+-------------------------------------+
|                                  -1 | 
+-------------------------------------+
1 row in set (0.00 sec)

Video Presentation:

All String Functions (Slides presentation)

Previous: SPACE
Next: SUBSTR



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mysql/string-functions/mysql-strcmp-function.php