Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return only numeric values from column - Postgresql

I have several values in my name column within the contacts table similar to this one:

test 3100509 DEMO NPS

I want to return only the numeric piece of each value from name.

I tried this:

select substring(name FROM '^[0-9]+|.*') from contacts

But that doesn't do it.

Any thoughts on how to strip all characters that are not numeric from the returned values?

like image 986
Luigi Avatar asked Feb 21 '14 22:02

Luigi


People also ask

How do I get just the numeric value in SQL?

The ISNUMERIC() function tests whether an expression is numeric. This function returns 1 if the expression is numeric, otherwise it returns 0.

How do I change data to numeric in PostgreSQL?

Use the :: operator to convert strings containing numeric values to the DECIMAL data type. In our example, we converted the string ' 5800.79 ' to 5800.79 (a DECIMAL value). This operator is used to convert between different data types. It's very popular within PostgreSQL.

Is Numeric in Postgres?

PostgreSQL supports the NUMERIC type for storing numbers with a very large number of digits. Generally NUMERIC type are used for the monetary or amounts storage where precision is required. Syntax: NUMERIC(precision, scale) Where, Precision: Total number of digits.


2 Answers

If you want to extract the numeric values with decimal point than use this

select NULLIF(regexp_replace(name, '[^0-9.]*','','g'), '')::numeric from contacts
like image 135
Nouman Bhatti Avatar answered Sep 24 '22 15:09

Nouman Bhatti


select regexp_replace(name , '[^0-9]*', '', 'g') from contacts;

This should do it. It will work even if you have more than one numeric sequences in the name.

Example:

create table contacts(id int, name varchar(200));

insert into contacts(id, name) values(1, 'abc 123 cde 555 mmm 999');

select regexp_replace(name , '[^0-9]*', '', 'g') from contacts;
like image 27
peter.petrov Avatar answered Sep 25 '22 15:09

peter.petrov