Languages
[Edit]
EN

MySQL - Find rows that contain substring

0 points
Created by:
WGates
412

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:

MySQL - example data used to find rows that contain substring
MySQL - example data used to find rows that contain substring

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:

MySQL - find rows that contain substring - result
MySQL - find rows that contain substring -  Gwendolyn example 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:

MySQL - find rows that contain substring - John example result
MySQL - find rows that contain substring - John example 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');

Related posts

Alternative titles

  1. MySQL - Select rows containing string
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join