Search code examples
mysqlsqlunicodecollationunicode-normalization

Hmm, why finding by '2' or '2' return the same record?


forgive my newbie question, but why finding by '2' or '2' in Mysql returns the same record?

For example:

Say I have a record with string field named 'slug', and the value is '2'. And the following SQLs returns same record.

SELECT * From articles WHERE slug='2'  
SELECT * From articles WHERE slug='2' 

Solution

  • It has to do with the collation of your database:

    mysql> SHOW VARIABLES LIKE 'collation_%';
    +----------------------+-------------------+
    | Variable_name        | Value             |
    +----------------------+-------------------+
    | collation_connection | latin1_swedish_ci |
    | collation_database   | latin1_swedish_ci |
    | collation_server     | latin1_swedish_ci |
    +----------------------+-------------------+
    3 rows in set (0.00 sec)
    
    mysql> SELECT '2'='2';
    +-----------+
    | '2'='2' |
    +-----------+
    |         0 |
    +-----------+
    1 row in set (0.00 sec)
    
    mysql> SET NAMES 'utf8' COLLATE 'utf8_unicode_ci';
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> SELECT '2'='2';
    +-----------+
    | '2'='2' |
    +-----------+
    |         1 |
    +-----------+
    1 row in set (0.00 sec)