Wild Characters in SQL

Underscore (_):

  • Matches any single character within a string.
  • Example: SELECT * FROM Customers WHERE City LIKE 'New_ork'; would match "New York".

2. Percentage Sign (%):

  • Matches any sequence of zero or more characters.
  • Example: SELECT * FROM Products WHERE ProductName LIKE '%book%'; would match "notebook", "textbook", "ebook", etc.

3. Square Brackets ([]):

  • Define a character class, matching any single character within the brackets.
  • Example: SELECT * FROM Employees WHERE Email LIKE '[aeiou]%@example.com'; would match email addresses starting with a vowel.
  • To match a literal hyphen or closing square bracket, place it at the beginning of the character class (e.g., [-] for a hyphen).

4. Caret (^) within Square Brackets:

  • Negates the character class, matching any single character not within the brackets.
  • Example: SELECT * FROM Products WHERE ProductCode NOT LIKE '[A-Z]%'; would match codes not starting with uppercase letters.

5. ESCAPE Clause:

  • Defines an escape character to treat wildcards literally.
  • Example: SELECT * FROM Users WHERE UserID LIKE '123\%456' ESCAPE '\'; would match the literal string "123%456".

Additional Notes:

  • Wild characters are primarily used with the LIKE operator for pattern matching.
  • The LIKE operator is case-insensitive in most SQL dialects, but some allow specifying case-sensitivity.
  • Wildcards can be combined for complex patterns (e.g., %[a-z]% matches any string containing at least one lowercase letter).
  • Usage and behavior of wild characters might vary slightly across different SQL dialects.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了