Home > Database > Mysql Tutorial > How Can I Perform Case-Sensitive String Comparisons in MySQL Queries?

How Can I Perform Case-Sensitive String Comparisons in MySQL Queries?

Patricia Arquette
Release: 2025-01-21 07:13:12
Original
310 people have browsed it

How Can I Perform Case-Sensitive String Comparisons in MySQL Queries?

Achieving Case-Sensitive String Comparisons in MySQL

Standard MySQL string comparisons are typically case-insensitive. This can be problematic when precise matching is required. Fortunately, MySQL provides a simple method to enforce case sensitivity in your queries.

Implementing Case-Sensitive Queries in MySQL

The BINARY keyword is the key to performing case-sensitive string comparisons. Here's the syntax:

<code class="language-sql">SELECT * FROM `table` WHERE BINARY `column` = 'value';</code>
Copy after login

Let's illustrate with an example:

Imagine a table structured like this:

<code class="language-sql">CREATE TABLE `test` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `test` (`name`) VALUES ('John'), ('JOHN'), ('JoHn');</code>
Copy after login

A query without BINARY would match all three entries:

<code class="language-sql">SELECT * FROM `test` WHERE `name` = 'john';</code>
Copy after login

However, by adding BINARY, the query becomes case-sensitive, returning only the exact match:

<code class="language-sql">SELECT * FROM `test` WHERE BINARY `name` = 'john';</code>
Copy after login

This technique ensures accurate case-sensitive comparisons, eliminating potential errors caused by case-insensitive matching.

The above is the detailed content of How Can I Perform Case-Sensitive String Comparisons in MySQL Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template