Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to check if a certain row has 2 words

Tags:

sql

mysql

How to return rows where a column has 2 words (that is, strings separated by a space) in it?

It must be purely using SQL.

SELECT * FROM table WHERE name (has 2 strings in it);
like image 878
Jordy Avatar asked Mar 05 '15 14:03

Jordy


2 Answers

I dont know the names when querying. Its a big dataset. I only have to check if the name contains a spacebar basically (from a comment).

If you want to distinguish names that have two parts from one-part and three-plus-part names, you can use regular expression:

SELECT * FROM my_table WHERE name REGEXP '^[^ ]+[ ]+[^ ]+$'

This regular expression matches when the entire string consists of two non-empty parts containing no spaces, with one or more space separating them.

like image 195
Sergey Kalinichenko Avatar answered Sep 28 '22 06:09

Sergey Kalinichenko


This perfectly works for me

You can use 'AND' condition and Like Operator with wildcards (%).

SELECT * FROM table_name WHERE name LIKE '%Word1%' AND name LIKE '%Word2%'
like image 27
Avidan Avatar answered Sep 28 '22 06:09

Avidan