0

I am new to writing postgres queries, I am stuck at a problem where the price is a string having $ prefix, I want to change the data type of column price to float and update the values by removing the $ prefix. Can someone help me do that?

bootcamp=# SELECT * FROM car;
 id |  make   |        model        |   price
----+---------+---------------------+-----------
  1 | Ford    | Explorer Sport Trac | $92075.96
  2 | GMC     | Safari              | $81521.80
  3 | Mercury | Grand Marquis       | $64391.84
(3 rows)

bootcamp=# \d car
                                   Table "public.car"
 Column |         Type          | Collation | Nullable |             Default
--------+-----------------------+-----------+----------+---------------------------------
 id     | bigint                |           | not null | nextval('car_id_seq'::regclass)
 make   | character varying(50) |           | not null |
 model  | character varying(50) |           | not null |
 price  | character varying(50) |           | not null |

Thanks

2 Answers 2

1

You can cleanup the string while altering the table:

alter table car
   alter column price type numeric using substr(price, 2)::numeric;
Sign up to request clarification or add additional context in comments.

Comments

1

First you have to disable safe update mode to update without WHERE clause:

SET SQL_SAFE_UPDATES=0;

Then remove '$' from all rows:

UPDATE car SET price = replace(price, '$', '');

Then change the column type:

 ALTER TABLE car ALTER COLUMN price TYPE your_desired_type;

If you want to enable safe update mode again:

SET SQL_SAFE_UPDATES=1;

1 Comment

Thanks, Danial, for the SET SQL_SAFE_UPDATES thing, anyways I got an error while altering the column data type column "price" cannot be cast automatically to type numeric, which is resolved by @a_horse_with_no_name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.