EN
MySQL - Find rows that contain substring
0
points
In this article, we would like to show you how to find rows that contain substring in MySQL.
Quick solution:
SELECT *
FROM `table_name`
WHERE `column_name`
LIKE '%pattern%';
Where in the pattern:
%
- matches 0 or more characters (0, 1, 2, 3, ...),_
- matches any single character (requires in_
place some character).
Practical example
To show how to find rows that contain substring, we will use the following users
table:
Note:
At the end of this article you can find database preparation SQL queries.
Example 1
In this example, we will select rows where the name
column value contains 'endo
' substring.
Query:
SELECT *
FROM `users`
WHERE `name`
LIKE '%endo%';
Result:
Example 2
In this example, we will select rows where the name
column value contains 'oh
' substring with only one letter before the substring, and one letter after it.
Query:
SELECT *
FROM `users`
WHERE `name`
LIKE '_oh_';
Result:
Database preparation
create_tables.sql
file:
CREATE TABLE `users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
`surname` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
);
insert_data.sql
file:
INSERT INTO `users`
( `name`, `surname`)
VALUES
('John', 'Stewart'),
('Chris', 'Brown'),
('Kate', 'Lewis'),
('Ailisa', 'Gomez'),
('Gwendolyn', 'James'),
('Simon', 'Collins'),
('Taylor', 'Martin'),
('Andrew', 'Thompson');