Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two columns in one column

Tags:

sql

mysql

I have column 1 and column 2, and want to combine them into column 3 of the same table. If the column 2 is null then display column 1 value, if column 1 is null, them display column 2 data. If both of them are null, then display null. I tried two things:

1) using CONCAT SELECT CONCAT(Column1, Column2) AS Column3 FROM TEST_ATTRIBUTES.

It just merges the columns only when both of them are not null. otherwise it just prins null.

2) using (column1 + column 2).

SELECT (Column1 + Column2) AS Column3 FROM TEST_ATTRIBUTES.

doesn't show desired output.

I'm writing this code in java. Thanks

like image 349
ArmMiner Avatar asked Apr 17 '13 14:04

ArmMiner


People also ask

How do I put multiple columns under one column in Excel?

You can combine two or more table cells located in the same row or column into a single cell. For example, you can merge several cells horizontally to create a table heading that spans several columns. Select the cells that you want to merge. Under Table Tools, on the Layout tab, in the Merge group, click Merge Cells.

How do I combine multiple columns?

To unmerge cells immediately after merging them, press Ctrl + Z. Otherwise do this: Click the merged cell and click Home > Merge & Center. The data in the merged cell moves to the left cell when the cells split.


1 Answers

use COALESCE(), this doesn't concatenate but returns the first non-null value from the list.

SELECT Column1, 
       Column2, 
       COALESCE(Column1, Column2) AS Column3 
FROM   TEST_ATTRIBUTES
  • SQLFiddle Demo

if there are chances that both of them are null,

SELECT Column1, 
       Column2, 
       IF(Column1 IS NULL AND Column2 IS NULL, NULL, CONCAT(COALESCE(Column1,''), COALESCE(Column2,''))) AS Column3 
FROM   TEST_ATTRIBUTES
  • SQLFiddle Demo
like image 104
John Woo Avatar answered Oct 13 '22 21:10

John Woo