Skip to content
Advertisement

How to combine multiple columns into one?

I have the following example table:

| name   | email1          | email2            | email3         | 
.................................................................
| John   | john@gmail.com  | john@hotmail.com  | john@yahoo.com |
| Jane   | jane@gmail.com  | NULL              | NULL           |

I need a query to combine the email columns in the way that the result would look like this, ignoring the nulls:

| name   | email            |
.............................
| John   | john@gmail.com   |
| John   | john@hotmail.com | 
| John   | john@yahoo.com   |
| Jane   | jane@gmail.com   |

How can I do this?

Advertisement

Answer

You can use a lateral join:

select t.name, v.email
from t cross join lateral
     (values (email1), (email2), (email3)) v(email)
where v.email is not null;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement