Can it be verified in DB if it is equal to a string?

2

I am trying to verify in a field of a mysqli table if it is = an exact string.

That is:

 $consulta = "SELECT count(*) as total FROM productos WHERE productos.stock = 'si' ";

Is it well formulated?

    
asked by Juan 22.01.2018 в 17:14
source

1 answer

3

Depends on how your column is:

► If the column stock is case insensitive (ci)

The query:

SELECT count(*) as total FROM productos WHERE productos.stock = 'si' 

It will count in the columns whose values are:

  • yes
  • YES
  • sI
  • yes
  • ... and any other stranger if

► If the column stock is NOT case insensitive (ci)

It will only count when the value is:

  • yes

It will not even tell you if the value is: SI or Si or sI .

Proof of concept

We are going to do some tests with code.

VIEW DEMO IN REXTESTER

1. COLLATE with case insensitive (ci) in CREATE TABLE :

   /*Ejemplo de case insensitive en el CREATE*/
    CREATE TABLE IF NOT EXISTS tabla_ci_20180122 
    (
        id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
        texto VARCHAR(25)

    )COLLATE utf8_spanish_ci, ENGINE=INNODB;


    INSERT INTO tabla_ci_20180122 (texto)
        VALUES 
        ('si'),('SI'),('sí'),('sï'),('no')
    ;

   SELECT COUNT(*) total FROM tabla_ci_20180122 WHERE texto='si';

Exit:

total
4

2. COLLATE case sensitive (cs) in CREATE TABLE

The same previous data is used.

   /*Ejemplo de cs en el CREATE*/
   CREATE TABLE IF NOT EXISTS tabla_no_ci_20180122 
    (
        id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
        texto VARCHAR(25)

    )COLLATE latin1_general_cs, ENGINE=INNODB;


    INSERT INTO tabla_no_ci_20180122 (texto)
        VALUES 
        ('si'),('SI'),('sí'),('sï'),('no')    
    ;

   SELECT COUNT(*) total FROM tabla_no_ci_20180122 WHERE texto='si';   

Exit:

total
1

3. COLLATE of the table by default, and a column with cs explicitly

The COLLATE can be set for the entire table, but some columns can have their own COLLATE , different from the table.

   /*Ejemplo de una tabla con COLLATE mixto: se establece una columna cs explícitamente*/ 
   CREATE TABLE IF NOT EXISTS tabla_mixta_20180122 
    (
        id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
        texto_ci VARCHAR(25),
        texto_no_ci VARCHAR(25) COLLATE latin1_general_cs

    ) ENGINE=INNODB;    

    INSERT INTO tabla_mixta_20180122 (texto_ci, texto_no_ci)
        VALUES 
        ('si','si'),('SI','SI'),('sí','sí'),('sï','sï'),('no','no')
    ;

Test ( case insensitive column):

SELECT COUNT(*) mixta_ci FROM tabla_mixta_20180122 WHERE texto_ci='si';  

Result:

mixta_ci
4

Test (column case sensitive ):

SELECT COUNT(*) mixta_no_ci FROM tabla_mixta_20180122 WHERE texto_no_ci='si';

Result:

mixta_no_ci
1
    
answered by 22.01.2018 / 17:22
source