LIKE operator in mysql workbench

  • The `LIKE` operator in MySQL Workbench is used to perform pattern matching within string values. It's primarily used in the `WHERE` clause of a `SELECT` query to retrieve rows that match a specified pattern. The `LIKE` operator is commonly used with wildcard characters to find strings that partially match the given pattern.
Here's a detailed explanation of how the `LIKE` operator works, along with examples:
  • Basic Syntax:


    SELECT columns
    FROM table
    WHERE column LIKE pattern;

Wildcards:

  • '%' (Percent sign): Represents zero, one, or multiple characters.
  • '_' (Underscore): Represents a single character.
Examples:
  • Wildcard at the End: To find all rows where a column starts with a specific string:


    SELECT * FROM products WHERE product_name LIKE 'Apple%';

  • Wildcard at the Beginning: To find all rows where a column ends with a specific string:


    SELECT * FROM customers WHERE email LIKE '%gmail.com';

  • Wildcard on Both Sides: To find all rows where a column contains a specific string:


    SELECT * FROM employees WHERE first_name LIKE '%son%';

  • Single Character Matching: To find all rows where a column has a specific character in a specific position:


    SELECT * FROM products WHERE product_code LIKE 'A_';

  • Negation with NOT LIKE: To find all rows that do not match a specific pattern:


    SELECT * FROM customers WHERE email NOT LIKE '%hotmail.com';

  • Case-Insensitive Matching: By default, `LIKE` performs case-insensitive matching. To perform case-sensitive matching, use the `BINARY` keyword:


    SELECT * FROM users WHERE BINARY username LIKE 'Admin%';

  • Escaping Wildcards: If you need to match actual percent signs (`%`) or underscores (`_`), you can use the `ESCAPE` keyword:


    SELECT * FROM text_data WHERE text_content LIKE '%\%%' ESCAPE '\';

  • The `LIKE` operator is a powerful tool for searching and filtering strings based on patterns. By using wildcards and combining them creatively, you can perform complex searches to retrieve the data you need from your database. Remember that while `LIKE` is useful, it can impact performance for large datasets due to its pattern matching nature.

No comments:

Post a Comment