SHA() method giving different result for same value of binary with different sizes.
- Created a table, columns with X1 binary(1), X2 binary(10) size.
CREATE TABLE TEST_binary10_2 ( PK bigint NOT NULL, VERSION int NOT NULL, X1 binary(1) DEFAULT NULL, X2 binary(10) DEFAULT NULL, PRIMARY KEY (
PK
));
- Inserted same text for both the columns.
insert into TEST_binary10_2 values(2, 1, 3, 3);
- Tried to retrieve SHA() for both, it returns different value even though it is same value.
SELECT PK, X1, X2, SHA(X1), SHA(X2) FROM TEST_binary10_2;
Result: you can observe SHA(X1) and SHA(X2) is different even though X1, and X2 contains same string. I want to know the reason and a solution.
2
Answers
You probably want
VARBINARY
instead ofBINARY
.https://dev.mysql.com/doc/refman/8.0/en/binary-varbinary.html
You’re comparing
3
against3
. If you look closely, you can see this in your output screenshot; the X2 column is much wider than it has to be, whereas all the other columns fit their (visible) contents.Try this:
This shows that the two binary strings are not the same because
BINARY(10)
they have different lengths. The latter column is bound to be a 10-byte string of bytes, because theBINARY
type is fixed length, and it will pad with zeroes if necessary.