Wednesday, December 18, 2024

SQL LIKE Operator

 The LIKE operator in SQL is used in a WHERE clause to search for a specified pattern in a column. It is typically used with wildcard characters to filter records based on pattern matching.

Wildcard Characters in SQL:

  1. %: Represents zero, one, or multiple characters.
  2. _: Represents a single character.

Syntax

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

Examples

1. Match Strings Starting with a Specific Character

SELECT * FROM employees WHERE name LIKE 'A%';

This query finds all names that start with "A."


2. Match Strings Ending with a Specific Character

SELECT * FROM employees WHERE name LIKE '%n';

This query finds all names that end with "n."


3. Match Strings Containing a Specific Sequence

SELECT * FROM employees WHERE name LIKE '%an%';

This query finds all names containing "an."


4. Match Strings of a Specific Length

SELECT * FROM employees WHERE name LIKE '___';

This query finds all names that are exactly three characters long.


5. Case Sensitivity

  • In most databases, the LIKE operator is case-insensitive (e.g., MySQL).
  • To perform a case-sensitive match in databases like MySQL, use the BINARY keyword:
SELECT * FROM employees WHERE name LIKE BINARY 'A%';

Advanced Patterns

Escape Characters

To search for special characters like % or _, use an escape character:

SELECT * FROM employees WHERE job_title LIKE '50\%%' ESCAPE '\';

This query finds job titles that include "50%".


Combining with Other Conditions

SELECT * FROM employees WHERE name LIKE 'A%' AND age > 30;

This query finds names starting with "A" where the age is greater than 30.

No comments:

Post a Comment