Search code examples
postgresqlmac-address

PostgreSQL 9.3: Migrate text column to macaddr type


I have a table with a text column representing a MAC address, but I want to use the macaddr type instead. So, I tried:

alter table mytable alter column mac_column type macaddr;

And got this error

ERROR:  column "mac_column" cannot be cast automatically to type macaddr
HINT:  Specify a USING expression to perform the conversion.

But I don't know what to use as USING expression:

alter table mytable alter column mac_column type macaddr using(????????)

What should I use as USING expression?

Many thanks in advance


Solution

  • You can’t simply change the data type because data is already there in the column. Since the data is of type String PostgreSQL can't expect it as macaddr though you entered valid String representation of the macaddr. So now, as PostgreSQL suggested you can use the ‘USING’ expression to cast your data into macaddr.

    ALTER TABLE mytable ALTER COLUMN mac_column TYPE macaddr USING(mac_column::macaddr)