Lesson

MySQL STRCMP() Function

10 min reading
Free Course

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: 0 if equal, -1 if expr1 < expr2, 1 if expr1 > expr2, or NULL if either expression is NULL.

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 SPACE collations (utf8mb4_general_ci) ignore trailing spaces, returning 0 for STRCMP('abc', 'abc '). MySQL 8.0's default NO PAD collation (utf8mb4_0900_ai_ci) treats 'abc ' as greater and returns -1.
  • Assuming STRCMP() is always case-sensitive: Under _ci collations, 'apple' and 'APPLE' return 0. Add COLLATE utf8mb4_0900_as_cs or BINARY for strict case ordering.
  • NULL propagation: Unlike the NULL-safe <=> operator, STRCMP(NULL, NULL) returns NULL, not 0.

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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum