PostgreSQL convert a string with commas into an integer - postgresql

I want to convert a column of type "character varying" that has integers with commas to a regular integer column.
I want to support numbers from '1' to '10,000,000'.
I've tried to use: to_number(fieldname, '999G999G999'), but it only works if the format matches the exact length of the string.
Is there a way to do this that supports from '1' to '10,000,000'?

select replace(fieldname,',','')::numeric ;
To do it the way you originally attempted, which is not advised:
select to_number( fieldname,
regexp_replace( replace(fieldname,',','G') , '[0-9]' ,'9','g')
);
The inner replace changes commas to G. The outer replace changes numbers to 9. This does not factor in decimal or negative numbers.

You can just strip out the commas with the REPLACE() function:
CREATE TABLE Foo
(
Test NUMERIC
);
insert into Foo VALUES (REPLACE('1,234,567', ',', '')::numeric);
select * from Foo; -- Will show 1234567

You can replace the commas by an empty string as suggested, or you could use to_number with the FM prefix, so the query would look like this:
SELECT to_number(my_column, 'FM99G999G999')

There are things to take note:
When using function REPLACE("fieldName", ',', '') on a table, if there are VIEW using the TABLE, that function will not work properly. You must drop the view to use it.

Related

Redshift how to split a stringified array into separate parts

Say I have a varchar column let's say religions that looks like this: ["Christianity", "Buddhism", "Judaism"] (yes it has a bracket in the string) and I want the string (not array) split into multiple rows like "Christianity", "Buddhism", "Judaism" so it can be used in a WHERE clause.
Eventually I want to use the results of the query in a where clause like this:
SELECT ...
FROM religions
WHERE name in
(
<this subquery>
)
How can one do this?
You can use the function JSON_PARSE to convert the varchar string into an array. Then you can use the strategy described in Convert varchar array to rows in redshift - Stack Overflow to convert the array to separate rows.
You can do the following.
Create a temporary table with sequence of numbers
Using the sequence and split_part function available in redshift, you can split the values based on the numbers generated in the temporary table by doing a cross join.
To replace the double quote and square brackets, you can use the regexp_replace function in Redshift.
create temp table seq as
with recursive numbers(NUMBER) as
(
select 1 UNION ALL
select NUMBER + 1 from numbers where NUMBER < 28
)
select * from numbers;
select regexp_replace(split_part(val,',',seq.number),'[]["]','') as value
from
(select '["christianity","Buddhism","Judaism"]' as val) -- You can select the actual column from the table here.
cross join
seq
where seq.number <= regexp_count(val,'[,]')+1;

how to cast varchar with 3 numbers after comma to float type PostgreSQL

I have a varchar type where each value looks like
539,000
153,300
55,300
752,500
4410,000
I need change column type with number format
I tried use to_number but it is not working
In case your text representation is a German decimal value (comma is decimal separator):
demo:db<>fiddle
Replace comma with dot and simply cast into float:
SELECT replace('123,456', ',', '.')::float
In case the comma separates the thousand groups you need to use the G formatter, which describes this:
demo:db<>fiddle
SELECT to_number('123,456', 'FM999G999')
FM supresses leading blanks and zeros, so even smaller number would work:
SELECT to_number('56', 'FM999G999')
Make sure you have German numeric configuration set and use to_number:
SHOW lc_numeric;
lc_numeric
------------
de_DE.utf8
(1 row)
SELECT to_number('539,000', '99999D000');
to_number
-----------
539.000
(1 row)
You can alter like this
ALTER COLUMN my_column TYPE float USING replace(my_column, ',','.')::float
https://dbfiddle.uk/?rdbms=postgres_10&fiddle=2ff308849d986d26637a011102bb752c

pgSQL: select first occurrence of the number inside a string

String contains numeric and alphabetic data. what is the way to pick up only number? for example:
for the string "abc-123a-66" select should return "123"
You could use regexp_matches
CREATE table foo (
test VARCHAR);
INSERT INTO foo VALUES('abc-123a-66');
SELECT (regexp_matches(test, '\d+'))[1] FROM foo;
Example at SQLFiddle
In PostgreSQL this can be done with:
SELECT regexp_matches(regexp_replace(whatever_columnn,'\D*',''),'\d+') FROM whatever_table;
The first function (regexp_replace) deletes every non digit from the beginning of the string, the second (regexp_matches) extracts one or more occurrences of any digit from the output of the first function.

Set numeric column to equal formatted varchar currency column in PostgreSQL

I have a VARCHAR(1000) column of prices with dollar signs (e.g. $100) and I have created a new NUMERIC(15,2) column, which I'd like to set equal to the prices in the VARCHAR column.
This is what worked for me in MySQL:
UPDATE product_table
SET cost = REPLACE(REPLACE(price, '$', ''), ',','');
but in PostgreSQL it throws an error:
ERROR: column "cost" is of type numeric but expression is of type character
LINE 2: SET cost = REPLACE(REPLACE(price, '$', ''), ',','');
^
HINT: You will need to rewrite or cast the expression.
I tried to follow the hint and tried some Google searches for examples, but my small brain hasn't been able to figure it out.
In PostgreSQL you can do this in one swoop, rather than replacing '$' and ',' s in separate calls:
UPDATE product_table
SET cost = regexp_replace(price, '[$,]', '', 'g')::numeric(15,2);
In regexp_replace the pattern [$,] means to replace either of '$' or ',' with the replace string (the empty string '' in this case), and the 'g' flag indicates that all such patterns need to be replaced.
Then you need to cast the resulting string to a numeric(15,2) value.
Simply cast the result of REPLACE with cast .. as numeric.
Try this:
UPDATE product_table
SET cost = CAST(REPLACE(REPLACE(price, '$', ''), ',','') AS NUMERIC);
I wouldn't suggest having this table structure though, because it can lead to anomalies (cost value doesn't reflect the price value).

Split a column value into two columns in a SELECT?

I have a string value in a varchar column. It is a string that has two parts. Splitting it before it hits the database is not an option.
The column's values look like this:
one_column:
'part1 part2'
'part1 part2'
So what I want is a a result set that looks like:
col1,col2:
part1,part2
part1,part2
How can I do this in a SELECT statement? I found a pgsql function to split the string into an array but I do not know how to get it into two columns.
select split_part(one_column, ' ', 1) AS part1,
split_part(one_column, ' ', 2) AS part2 ...