Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Combine Two Columns in Select Statement

If I have a column that is Address1 and Address2 in my database, how do I combine those columns so that I could perform operations on it only in my select statement, I will still leave them separate in the database. I would like to be able to do this

WHERE completeaddress LIKE '%searchstring%' 

Where completedaddress is the combination of Address1 and Address2. searchstring would be like the data they searched for. So if they had '123 Center St' in Address1 and 'Apt 3B' in Address2, how would I have it select it if the searchstring was 'Center St 3B' Is this possible with SQL?

like image 579
atrljoe Avatar asked Mar 09 '11 14:03

atrljoe


People also ask

How do I concatenate two column values in SQL?

MySQL CONCAT() Function The CONCAT() function adds two or more expressions together. Note: Also look at the CONCAT_WS() function.

How do I merge columns in SQL?

try to use coalesce() and concat() to combine columns in the SQL query. Eg: 1, vishnu, 9961907453, 91 will return phone number as +919961907453. You can use the following query to get the above result. Highly active question.


2 Answers

I think this is what you are looking for -

select Address1+Address2 as CompleteAddress from YourTable where Address1+Address2 like '%YourSearchString%' 

To prevent a compound word being created when we append address1 with address2, you can use this -

select Address1 + ' ' + Address2 as CompleteAddress from YourTable  where Address1 + ' ' + Address2 like '%YourSearchString%' 

So, '123 Center St' and 'Apt 3B' will not be '123 Center StApt 3B' but will be '123 Center St Apt 3B'.

like image 102
pavanred Avatar answered Sep 23 '22 22:09

pavanred


In MySQL you can use:

SELECT CONCAT(Address1, " ", Address2) WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B") 

The SOUNDEX function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.

like image 37
anothershrubery Avatar answered Sep 21 '22 22:09

anothershrubery