LIKE and ILIKE Clause in SQL

LIKE and ILIKE Clause in SQL

The LIKE and ILIKE clauses in SQL are used for pattern matching in string data.

  • LIKE: Performs case-sensitive matching.

  • ILIKE: Performs case-insensitive matching (commonly used in databases like PostgreSQL).


Key Points

  1. Pattern Matching:
    Both LIKE and ILIKE use wildcard characters (% and _) to define patterns:

    • %: Matches zero or more characters.

    • _: Matches exactly one character.

  2. Case Sensitivity:

    • LIKE is case-sensitive, meaning it distinguishes between uppercase and lowercase letters.

    • ILIKE is case-insensitive, meaning it treats uppercase and lowercase letters as the same.


Syntax

Basic Syntax

SELECT column1, column2, ...
FROM table_name
WHERE column_name [NOT] LIKE pattern;

Using ILIKE

SELECT column1, column2, ...
FROM table_name
WHERE column_name [NOT] ILIKE pattern;

Example

Using LIKE for Case-Sensitive Matching

SELECT first_name, last_name
FROM employees
WHERE first_name LIKE 'A%';
  • Retrieves employees whose first_name starts with 'A'.

Using ILIKE for Case-Insensitive Matching

SELECT first_name, last_name
FROM employees
WHERE first_name ILIKE 'a%';
  • Retrieves employees whose first_name starts with 'A' or 'a'.

Using _ for Single Character Matching

SELECT product_name
FROM products
WHERE product_name LIKE '_pple';
  • Finds products like "Apple," "Xpple," etc., where the second to fifth characters match.

Using Wildcards in the Middle or End

SELECT email
FROM users
WHERE email LIKE '%@gmail.com';
  • Retrieves all email addresses ending with "@gmail.com".

Using NOT LIKE

SELECT first_name, last_name
FROM employees
WHERE last_name NOT LIKE '%son';
  • Finds employees whose last name does not end with 'son'.

When to Use LIKE and ILIKE

  • Use LIKE for case-sensitive searches when precision matters.

  • Use ILIKE for case-insensitive searches, especially in user-facing applications.

  • Ideal for scenarios involving partial text search or pattern matching.

Note: The performance of LIKE and ILIKE can degrade for complex patterns or large datasets without proper indexing.