LIKE operator is used to filter data based on some specific pattern.
It is used with the WHERE clause and searches for a particular pattern in a column.
Common use: Searching & filtering data to show in tables
Syntax: SELECT * FROM table_name WHERE column_name LIKE 'pattern’
The LIKE command is not used alone i.e., it uses some special characters (wildcard characters) to specify a pattern.
Wildcard Characters
1. The percent sign (%)
Meaning: It matches zero, one, or multiple characters (capital or small) or numbers.
Examples:
- ‘T%’ will find all strings starting with ‘T’ and having any number of other characters after it.
- ‘%T’ will find all strings ending with ‘T’ and having any number of other characters before it.
- ‘%tjwebdev%’ will find all strings having ‘tjwebdev’ at any position.
- ‘T%J’ will find all strings starting with ‘T’ and ending with ‘J’.
Syntax: SELECT * FROM table_name WHERE column_name LIKE 'T%’
2. The underscore sign (_)
Meaning: It represents a single character or number.
Example:
- ‘_’ will find all strings having only one character (any).
- ‘__’ will find all strings having only two characters(any).
- ‘T_’ will find all strings having two characters with ‘T’ as the first character and the second character can be anything.
Syntax: SELECT * FROM table_name WHERE column_name LIKE 'T_’
Combining Wildcard Example
- ‘_t%’ will find all strings with ‘t’ at second position
- ‘t_%’ will find all strings starting with ‘t’ and has at least two characters.
Syntax: SELECT * FROM table_name WHERE column_name LIKE 't_%’
Just use the wildcards and create patterns!