What's the difference between "VARCHAR BINARY" and "VARBINARY" in MySQL?

Clarence picture Clarence · Mar 27, 2015 · Viewed 9.4k times · Source

I've created the following test table:

CREATE TABLE t (
   a VARCHAR(32) BINARY,
   b VARBINARY(32)
);

INSERT INTO t (a, b) VALUES ( 'test    ', 'test    ');
INSERT INTO t (a, b) VALUES ( 'test    \0', 'test    \0');

But this query indicated no difference between the two types:

SELECT a, LENGTH(a), HEX(a), b, LENGTH(b), HEX(b) FROM t;

a          LENGTH(a)  HEX(a)              b          LENGTH(b)  HEX(b)              
---------  ---------  ------------------  ---------  ---------  --------------------
test               8  7465737420202020    test               8  7465737420202020    
test               9  746573742020202000  test               9  746573742020202000  

Answer

Jean-François Savard picture Jean-François Savard · Mar 27, 2015

Here are the difference I was able to find reading the documentation :

VARCHAR BINARY

  • The BINARY attribute cause the binary collation for the column character set to be used, and the column itself contains nonbinary character strings rather than binary byte strings.
  • When BINARY values are stored, they are right-padded with the pad value to the specified length.
  • You should consider the preceding padding and stripping characteristics carefully if you plan to use the BINARY data type for storing binary data and you require that the value retrieved be exactly the same as the value stored.

VARBINARY

  • If strict SQL mode is not enabled and you try to assign a value that exceeds the column's maximum length, the value is truncated to fit and a warning is generated.
  • There is no padding on insert, and no bytes are stripped on select. All bytes are significant in comparisons.
  • Utilisation is preferable when the value retrieved must be the same as the value specified for storage with no padding.