Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Search exact word from string

Tags:

mysql

I want to search exact word from string like

id  Description
1   This is nice pen looking good
2   This is nice pendrive looking good

Search String : pen

My Current query

SELECT * FROM `table` WHERE Description like '%pen%';

Above Query return both record but I want Only first record. Because pen word exact match with my search string.

Expected Output

1   This is nice pen looking good

Demo

like image 926
Sadikhasan Avatar asked Feb 04 '17 05:02

Sadikhasan


People also ask

How do I find a specific word in MySQL?

LOCATE() function MySQL LOCATE() returns the position of the first occurrence of a string within a string. Both of these strings are passed as arguments. An optional argument may be used to specify from which position of the string (i.e. string to be searched) searching will start.

How do I find a specific string in MySQL?

MySQL LOCATE() Function The LOCATE() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0. This function performs a case-insensitive search. Note: This function is equal to the POSITION() function.

What is full-text search in MySQL?

A full-text index in MySQL is an index of type FULLTEXT . Full-text indexes can be used only with InnoDB or MyISAM tables, and can be created only for CHAR , VARCHAR , or TEXT columns.

How do I search for something in MySQL?

Find data across a MySQL connection by using the text search feature on any number of tables and schemas. From the schema tree, select the tables, schemas, or both to search and then right-click the highlighted items and click Search Data Table from the context menu.


2 Answers

Try using regular expressions:

SELECT 
    *
FROM
    `table`
WHERE
    Description regexp '(^|[[:space:]])pen([[:space:]]|$)';

Demo

Or using word boundaries:

SELECT 
    *
FROM
    `table`
WHERE
    Description regexp '[[:<:]]pen[[:>:]]';
like image 89
Gurwinder Singh Avatar answered Sep 28 '22 08:09

Gurwinder Singh


You can use REGEXP and the [[:<:]] and [[:>:]] word boundary markers:

SELECT
    *
FROM
    `table`
WHERE
    Description REGEXP '[[:<:]]pen[[:>:]]';

SQL Fiddle Demo

like image 36
Faisal Avatar answered Sep 28 '22 08:09

Faisal