Why does TINYINT(1) function as a boolean but INT(1) does not?

后端 未结 5 1233
无人共我
无人共我 2020-12-08 22:21

Why does TINYINT(1) work as a boolean? The way I understood the official docs, the (1) should mean it has a display width of 1, so if I store 56 in

5条回答
  •  感动是毒
    2020-12-08 23:09

    TINYINT columns can store numbers from -128 to 127.

    TINYINT(1) is a bit weird though. It is (perhaps because it is supposed to act as a BOOLEAN datatype), returns only 0 and 1 in some context, while it still keeps the stored (-128 to 127) values.

    (Correction: I only see this weird behaviour in SQL-Fiddle and not when accessing MySQL locally so it may well be a SQL-Fiddle quirkiness, possibly related to the quivalence with BOOLEAN) and not a MySQL problem.

    See the SQL-Fiddle

    CREATE TABLE test
    ( i TINYINT(1)
    ) ;
    
    INSERT INTO test 
      (i)
    VALUES
      (0),  (1), (6), (120), (-1) ;
    

    Where we get (only in SQL-Fiddle, not if we access MySQL otherwise!):

    SELECT i
    FROM test ;
    
      i
    -----
      0
      1
      1
      1
      1
    

    but:

    SELECT CAST(i AS SIGNED) i2
    FROM test ;
    
      i2
    -----
       0
       1
       6
     120
      -1
    

提交回复
热议问题