LIKE运算符基础及精准5字符客户姓名查询语句咨询
Hey there! Let's walk through the LIKE operator basics and nail the query for finding customers with exactly 5-letter names.
The LIKE operator in SQL is used to match string patterns in columns. It relies on two key wildcards for most common use cases:
%: Matches any sequence of characters (including zero characters). For example,'Sam%'would match "Sam", "Sammy", "Samuel", etc._: Matches exactly one single character. This is the wildcard we'll use for your specific requirement.
Some databases also support additional wildcards like [] (matches any single character within the brackets) or [^] (matches any single character not in the brackets), but they're less universal across all SQL dialects.
To find names that are precisely 5 characters long, we use five _ wildcards—each one represents one letter in the name, with no extra characters allowed before or after.
Here's the standard SQL query for this:
SELECT customer_name FROM customers WHERE customer_name LIKE '_____'; -- 5 underscores total
Key Notes:
- Skip the
%wildcards here! Using'%_____'would match names that end with 5 characters (like "Alexandra"), and'_____%'would match names that start with 5 characters (like "Robert"). Only the five underscores with no other wildcards ensures an exact 5-character match. - Case sensitivity: Most databases (like MySQL) are case-insensitive by default for LIKE matches. If you need to enforce case-sensitive matching (e.g., only match "Smith" not "smith"), you can use database-specific functions. For example, in MySQL:
In PostgreSQL, you'd use theSELECT customer_name FROM customers WHERE BINARY customer_name LIKE '_____';LIKEoperator with a case-sensitive collation, or the~regex operator for stricter control.
If you already wrote a query using five underscores, you're on the right track! If you used other wildcards, adjusting to the above should give you the exact results you need.
内容的提问来源于stack exchange,提问作者Abdulrahman Samhoury




