What is the usage of binary in MySQL?
In MySQL, BINARY is both a data type and an operator.
- Binary data type allows you to store binary data such as images, audio, videos, etc. You can specify the maximum length of the binary data to be stored using BINARY(n), where n is an integer. If no length is specified, it defaults to 1. For example, BINARY(10) will store up to 10 bytes of binary data.
- Operator: The BINARY operator is used to compare if two binary strings are equal. It is case sensitive and compares based on byte order, meaning even if strings look the same, if their byte order is different, they will be considered unequal. The = or <=> operators can be used to perform binary comparisons. For example, ‘hello’ = BINARY ‘HELLO’ will return False, while ‘hello’ <=> BINARY ‘HELLO’ will return True.
Here are some examples of using BINARY:
- Create a table that includes binary data.
CREATE TABLE images (
id INT PRIMARY KEY,
data BINARY(100)
);
- Insert binary data:
INSERT INTO images (id, data) VALUES (1, X'1234567890');
- Compare binary strings.
SELECT * FROM images WHERE data = BINARY X'1234567890';
Please note that due to BINARY being case-sensitive and comparing in byte order, it is important to consider the case and byte order of data when using it.