0

[beginner]

I have a table that looks like this:

colA    colB
1       <null>
2       <null>
3       <null>

colB is the new empty column I added to the table. colA is varchar and colB is double precision data type (float).

I want to update colB with a colA multiplied by 2.

New table should look like this:

colA    colB
1       2
2       4
3       6

When I go to update colB like so:

update tablename set colB = colA * 2

I get error:

Invalid operation: Invalid input syntax for type numeric

Ive tried to work around this with solutions like this:

update tablename set colB = COALESCE(colA::numeric::text,'') * 2

but get the same error.

In a select statement on the same table, this works on colA which is varchar:

select colA * 2 from tablename

How can I update a column with mathematical operations with different datatype reference columns? I cant update datatype for colA.

RustyShackleford
  • 3,462
  • 9
  • 40
  • 81

3 Answers3

2

I suppose that Laurenz Albe is correct and there are non-numeric values in col_a

So UPDATE must be guarded:

UPDATE T
SET col_b = 
  CASE
     WHEN col_a ~'^([0-9]+\.?[0-9]*|\.[0-9]+)$' THEN col_a::numeric *2
  END ;
-- or this way
UPDATE T
SET col_b = col_a::numeric *2
WHERE
      col_a ~'^([0-9]+\.?[0-9]*|\.[0-9]+)$' ;

Look at fiddle: https://www.db-fiddle.com/f/4wFynf9WiEuiE499XMcsCT/1

Recipes for "isnumeric" you can get here: isnumeric() with PostgreSQL

Alex Yu
  • 3,412
  • 1
  • 25
  • 38
1

There is a value in the string column that is not a valid number. You will have to fix the data or exclude certain rows with a WHERE condition.

If you say that running the query from your client works, that leads me to suspect that your client doesn't actually execute the whole query, but slaps a LIMIT on it (some client tools do that).

The following query will have to process all rows and should fail:

SELECT colA * 2 AS double
FROM tablename
ORDER BY double;
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
0
update tablename set colB = colA::numeric * 2
Sergey Zaykov
  • 523
  • 2
  • 9