Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I search substring in database?

Tags:

sql

mysql

I have two columns in my database table :

-------------------------------
name            | address
-------------------------------
raj kumar       | park street    
yogin patel     | ghari chowk 
raju singh      | sultan ganj

I would like to retrieve a row containing sultan ganj, but by mistake I search for sultanganj (no space between words). What query will I use in order to get the correct result?

like image 702
user3717804 Avatar asked Jun 11 '26 09:06

user3717804


2 Answers

You can REPLACE all spaces in the field address with empty strings and compare them with sultanganj:

SELECT * 
FROM `table`
WHERE REPLACE(`address`, ' ', '') = 'sultanganj'

This will return you :

-------------------------
    name   |   address
-------------------------
raju singh | sultan ganj
like image 76
potashin Avatar answered Jun 12 '26 23:06

potashin


Just do like below using REPLACE function to replace the extra space in value

select name, address
from yourtable
where replace(address,' ','') = 'sultanganj'

EDIT:

You can use the same query in answer except that change the WHERE condition to be like where address like '%park%' or address like '%road%'. This way it will match all address which contains either the word park or road or both (example: parkroad,parkstreet,HellRoad,Heavenpark etc).

select name, address
from yourtable
where address like '%park%' or address like '%road%'
like image 33
Rahul Avatar answered Jun 13 '26 00:06

Rahul