Languages
[Edit]
EN

MySQL - Find rows that contain substring

0 points
Created by:
Dirask Community
6240

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

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