Skip to content

BINARY

Function Description

The BINARY() function is a function that converts values ​​into binary strings. It is often used to compare text or character data, treating strings as binary data rather than plain character data. This allows binary comparison of character data without being affected by character sets or encodings.

The BINARY() function implements binary comparison of character data and is used to handle case-sensitive string comparisons and other scenarios.

Grammar Structure

> BINARY value
Parameters Description
value Required parameters. The value to be converted.

Example

CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, password VARCHAR(100) NOT NULL);

INSERT INTO users (username, password) VALUES ('JohnDoe', 'Abcd123'), ('AliceSmith', 'Efgh456'), ('BobJohnson', 'ijkl789');

-- Password verification is performed using the BINARY() operator. The BINARY password = 'Abcd123' section treats the password value as a binary string. This comparison is case-sensitive. If the entered password matches the record in the database, the query returns the corresponding user id and username, otherwise the empty result will be returned.
mysql> SELECT id, username FROM users WHERE username = 'JohnDoe' AND BINARY password = 'Abcd123';
+------+--------------+
| id | username |
+------+--------------+
| 1 | JohnDoe |
+------+--------------+
1 row in set (0.00 sec)

mysql> SELECT id, username FROM users WHERE username = 'JohnDoe' AND BINARY password = 'abcd123';
Empty set (0.00 sec)