MySQL STRCMP() Function
MySQL STRCMP() Function
The STRCMP() function compares two strings lexicographically using the active collation and returns a three-way integer result: -1, 0, or 1. It mirrors C's strcmp pattern inside SQL expressions.
Syntax
STRCMP(expr1, expr2)
- expr1: First string to compare.
- expr2: Second string to compare.
- Return value:
0if equal,-1ifexpr1 < expr2,1ifexpr1 > expr2, orNULLif either expression isNULL.
Because STRCMP() follows collation rules rather than raw ASCII byte values, case sensitivity and trailing spaces depend on your table or session collation.
Practical Example
Suppose you want to classify order codes in demo_orders alphabetically relative to 'ORD-500' and verify whether stored status values match 'shipped'.
SELECT
order_id,
order_code,
status,
STRCMP(order_code, 'ORD-500') AS code_vs_500,
STRCMP(status, 'SHIPPED') AS status_match
FROM demo_orders
ORDER BY order_id;
| order_id | order_code | status | code_vs_500 | status_match |
|---|---|---|---|---|
| 1 | ORD-320 | shipped | -1 | 0 |
| 2 | ORD-500 | pending | 0 | -1 |
| 3 | ORD-840 | NULL | 1 | NULL |
In row 1, STRCMP('shipped', 'SHIPPED') returns 0 under the default case-insensitive utf8mb4_0900_ai_ci collation.
Common Mistakes & NULL Behavior
- Trailing spaces under NO PAD vs. PAD SPACE collations: Older
PAD SPACEcollations (utf8mb4_general_ci) ignore trailing spaces, returning0forSTRCMP('abc', 'abc '). MySQL 8.0's defaultNO PADcollation (utf8mb4_0900_ai_ci) treats'abc 'as greater and returns-1. - Assuming STRCMP() is always case-sensitive: Under
_cicollations,'apple'and'APPLE'return0. AddCOLLATE utf8mb4_0900_as_csorBINARYfor strict case ordering. - NULL propagation: Unlike the NULL-safe
<=>operator,STRCMP(NULL, NULL)returnsNULL, not0.
Frequently Asked Questions
What does STRCMP() return when comparing numbers stored as strings?
It compares character by character, so STRCMP('100', '20') returns -1 because '1' comes before '2' alphabetically.
When is STRCMP() better than regular <, =, > operators?
STRCMP() packs all three outcomes (-1, 0, 1) into a single column value, avoiding a multi-branch CASE expression.
What happens if one argument is an empty string?
Any non-empty string sorts after '', so STRCMP('', 'a') returns -1.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.