Skip to content
Advertisement

SQL Merge the row into new column

I have a table named Addresses.

The columns are:

Property | Road | Town | Borough | District | Postcode

There is no data in Property as of yet as I will update it manually later. The rest of the columns does hold data though.

However I need to merge Road, Town, Borough, District and Postcode into a new column named Full Address.

So for example

Property |    Road     |     Town     |  Borough  |  District  | Postcode | Full Address
  NULL     London Road      London       Enfield      North      EN16 5FD   NULL, London Road, London, Enfield, North, EN16 5FD

If you can see the “Full Address” column has taken everything from the same row and added it into the row itself.

How would I be able to do this within SQL?

Advertisement

Answer

You want string concatenation. Many databases support concat_ws():

update mytable
set full_address = concat_ws(', ', 
    property,
    road,
    town,
    borough,
    district,
    postcode
);

The behavior on concat_ws() as regard to null values varies across databases. Some will return a null value if any value in the list is null; in that case, you might want to surround nullable columns in the list with coalesce(), as in coalesce(property, '').

If your database does not support group_concat(), then use the regular string concatenation operator; in standard SQL, that’s ||:

    property    || ', '
    || road     || ', '
    || town     || ', '
    || borough  || ', '
    || district || ', '
    || postcode

Finally: it is not necessarily a good idea to store this derived information. Instead, you can use a computed column or a view:

create view myview as
select t.*,
    concat_ws(', ', 
        property,
        road,
        town,
        borough,
        district,
        postcode
    ) as full_address
from mytable t
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement