SQL predicate LIKE operator and wildcard percent sign %, underscore _, brackets []

  1. When SQL wants to search a row where a certain text appears in a table, you cannot use simple comparison operators. For example, to find the row containing the word "water" in the selected column, you need to use the wildcard search mode, you must use LIKE operator.
  2. Technically speaking, LIKE is not an operator, but a predicate.
  3. LIKE can only be used for wildcard searches in text fields (strings).
  4. Wildcards and their functions

Percent sign (%) wildcard
character means to find any number of occurrences of any character

SELECT prod_id,prod_name
FROM Products
WHERE prod_name LIKE 'Fish%';

The underscore (_) wildcard is
similar to %, but is limited to one character.

SELECT prod_id, prod_name
FROM Products
WHERE product_name LIKE '__ inch teddy bear';

Can find the line containing inch teddy bear, but the string must be two characters before it, because two underscores are applied. _ Always matches exactly one character, no more or no less.
Square brackets ([]) wildcards are
used to specify a character set and must match a character at a specified position.

SELECT cust_contact
FROM Customers
WHERE cust_contact LIKE '[JM]%'
ORDER BY cust_contact;

Square brackets intelligently match a single character, [JM] means to match any character in J or M, that is, in this example, return the line whose name starts with J or M.
This wildcard can be negated with ^.

SELECT cust_contact
FROM Customers
WHERE cust_contact LIKE '[^JM]%'
ORDER BY cust_contact;

Indicates to return the line where the name does not start with J or M.
This blog is referenced from the fifth edition of "SQL Must Know and Know".

Guess you like

Origin blog.csdn.net/qq_43511299/article/details/114093463