Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SELECT AS combine two columns into one

Tags:

sql

mysql

Using this solution, I tried to use COALESCE as part of a MySQL query that outputs to a csv file using SELECT As to name the column names when exporting the data.

SELECT FirstName AS First_Name      , LastName AS Last_Name      , ContactPhoneAreaCode1      , ContactPhoneNumber1      , COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone    FROM TABLE1 

I wanted 3 columns: First_Name, Last_Name and Contact_Phone

I am getting 5 columns: First_Name, Last_Name, ContactPhoneAreaCode1, ContactPhoneNumber1 and Contact_Phone

How do I hide the merging of ContactPhoneAreaCode1, ContactPhoneNumber1 into a single column for Contact_Phone from within the query?

like image 653
Rocco The Taco Avatar asked Sep 17 '13 21:09

Rocco The Taco


People also ask

How do I combine two columns into a single column in SQL?

SELECT COALESCE(column1,'') + COALESCE(column2,'') FROM table1. For this example, if column1 is NULL , then the results of column2 will show up, instead of a simple NULL .

How do I SELECT two columns in MySQL?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.


2 Answers

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name      , LastName AS Last_Name      , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone    FROM TABLE1 

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name      , LastName AS Last_Name      , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone    FROM TABLE1 

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

like image 192
raina77ow Avatar answered Oct 25 '22 23:10

raina77ow


You don't need to list ContactPhoneAreaCode1 and ContactPhoneNumber1

SELECT FirstName AS First_Name,  LastName AS Last_Name,  COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone  FROM TABLE1 
like image 20
sung Avatar answered Oct 26 '22 00:10

sung