Friday, December 20, 2024

MySQL STRCMP() Function

 The STRCMP() function in MySQL is used to compare two strings. It returns an integer value based on the comparison:

  • 0: if the two strings are equal.
  • >0: if the first string is greater than the second string.
  • <0: if the first string is less than the second string.

Syntax:

STRCMP(string1, string2)

Parameters:

  • string1: The first string to be compared.
  • string2: The second string to be compared.

Example:

  1. Equal strings:

    SELECT STRCMP('apple', 'apple');
    -- Output: 0
    
  2. First string is greater:

    SELECT STRCMP('banana', 'apple');
    -- Output: >0
    
  3. First string is less:

    SELECT STRCMP('apple', 'banana');
    -- Output: <0
    

Usage:

  • You can use STRCMP() in a WHERE clause or in other conditional logic to compare strings.

Example in WHERE clause:

SELECT * FROM products WHERE STRCMP(product_name, 'Laptop') = 0;
-- This will return all rows where product_name is exactly 'Laptop'

Note that the comparison is case-sensitive. If you need a case-insensitive comparison, you can use COLLATE with STRCMP() to adjust the collation.

No comments:

Post a Comment