I have a table of cars in my Postgres database, but a created the price column with varchar.
I want to convert this type to numeric or integer.
I have a table of cars in my Postgres database, but a created the price column with varchar.
I want to convert this type to numeric or integer.
You can change the table definition with ALTER TYPE
, but you'll need a USING clause with your particular conversion. Related:
If your data sample tells the full story, this should work:
ALTER TABLE tbl
ALTER COLUMN price TYPE numeric USING right(price, -1)::numeric
right(price, -1)
trims the first character, which is always $
in your sample. Remaining leading and trailing white space is no problem. Related:
For anything else, adapt the expression.
The operation triggers a table rewrite, taking an exclusive lock on the table for the duration.
I chose numeric
to cover fractional digits. See: