Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL combine two columns into one column

Tags:

sql

mysql

People also ask

How do I combine values from two columns into one in SQL?

SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`; Using * means, in your results you want all the columns of the table. In your case * will also include FIRSTNAME . You are then concatenating some columns and using alias of FIRSTNAME .

How do I combine two columns of the same table in SQL?

The following example shows how to concatenate three different columns: (SELECT id, email1 AS email FROM customer) UNION (SELECT id, email2 AS email FROM customer) UNION (SELECT id, email3 AS email FROM customer) ORDER BY id, email; As you can see, it's important that all the queries return the same columns.


My guess is that you are using MySQL where the + operator does addition, along with silent conversion of the values to numbers. If a value does not start with a digit, then the converted value is 0.

So try this:

select concat(column1, column2)

Two ways to add a space:

select concat(column1, ' ', column2)
select concat_ws(' ', column1, column2)

Try this, it works for me

select (column1 || ' '|| column2) from table;

It's work for me

SELECT CONCAT(column1, ' ' ,column2) AS newColumn;

This is the only solution that would work for me, when I required a space in between the columns being merged.

select concat(concat(column1,' '), column2)

If you are Working On Oracle Then:

SELECT column1 || column2 AS column3
FROM table;

OR

If You Are Working On MySql Then:

SELECT Concat(column1 ,column2) AS column3
FROM table;

For the MySQL fans out there, I like the IFNULL() function. Other answers here suggest similar functionality with the ISNULL() function in some implementations. In my situation, I have a column of descriptions which is NOT NULL, and a column of serial numbers which may be NULL This is how I combined them into one column:

SELECT CONCAT(description,IFNULL(' SN: ', serial_number),'')) FROM my_table;

My results suggest that the results of concatenating a string with NULL results in a NULL. I have been getting the alternative value in those cases.