[sql] Extract number from string with Oracle function

I need to create an Oracle DB function that takes a string as parameter. The string contains letters and numbers. I need to extract all the numbers from this string. For example, if I have a string like RO1234, I need to be able to use a function, say extract_number('RO1234'), and the result would be 1234.

To be even more precise, this is the kind of SQL query which this function would be used in.

SELECT DISTINCT column_name, extract_number(column_name) 
FROM table_name
WHERE extract_number(column_name) = 1234;

QUESTION: How do I add a function like that to my Oracle database, in order to be able to use it like in the example above, using any of Oracle SQL Developer or SQLTools client applications?

This question is related to sql oracle oracle11g oracle-sqldeveloper sqltools

The answer is


You'd use REGEXP_REPLACE in order to remove all non-digit characters from a string:

select regexp_replace(column_name, '[^0-9]', '')
from mytable;

or

select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;

Of course you can write a function extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.

create function extract_number(in_number varchar2) return varchar2 is
begin
  return regexp_replace(in_number, '[^[:digit:]]', '');
end; 

You can use regular expressions for extracting the number from string. Lets check it. Suppose this is the string mixing text and numbers 'stack12345overflow569'. This one should work:

select regexp_replace('stack12345overflow569', '[[:alpha:]]|_') as numbers from dual;

which will return "12345569".

also you can use this one:

select regexp_replace('stack12345overflow569', '[^0-9]', '') as numbers,
       regexp_replace('Stack12345OverFlow569', '[^a-z and ^A-Z]', '') as characters
from dual

which will return "12345569" for numbers and "StackOverFlow" for characters.


If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr function like this:

regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')

This works for me, I only need first numbers in string:

TO_NUMBER(regexp_substr(h.HIST_OBSE, '\.*[[:digit:]]+\.*[[:digit:]]*'))

the field had the following string: "(43 Paginas) REGLAS DE PARTICIPACION".

result field: 43


Questions with sql tag:

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database Export result set on Dbeaver to CSV How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? #1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’ MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server IF EXISTS THEN 1 ELSE 2 How to add a boolean datatype column to an existing table in sql? Presto SQL - Converting a date string to date format What is the meaning of <> in mysql query? Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Convert timestamp to date in Oracle SQL #1292 - Incorrect date value: '0000-00-00' Postgresql tables exists, but getting "relation does not exist" when querying SQL query to check if a name begins and ends with a vowel Find the number of employees in each department - SQL Oracle Error in MySQL when setting default value for DATE or DATETIME Drop view if exists Could not find server 'server name' in sys.servers. SQL Server 2014 How to create a Date in SQL Server given the Day, Month and Year as Integers TypeError: tuple indices must be integers, not str Select Rows with id having even number SELECT list is not in GROUP BY clause and contains nonaggregated column IN vs ANY operator in PostgreSQL How to insert date values into table Error related to only_full_group_by when executing a query in MySql How to select the first row of each group? Connecting to Microsoft SQL server using Python eloquent laravel: How to get a row count from a ->get() How to execute raw queries with Laravel 5.1? In Oracle SQL: How do you insert the current date + time into a table? Extract number from string with Oracle function Rebuild all indexes in a Database SQL: Two select statements in one query DB2 SQL error sqlcode=-104 sqlstate=42601 What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types How to run .sql file in Oracle SQL developer tool to import database? Concatenate columns in Apache Spark DataFrame How Stuff and 'For Xml Path' work in SQL Server? Fatal error: Call to a member function query() on null

Questions with oracle tag:

concat yesterdays date with a specific time ORA-28001: The password has expired how to modify the size of a column How to create a blank/empty column with SELECT query in oracle? Find the number of employees in each department - SQL Oracle Query to display all tablespaces in a database and datafiles When or Why to use a "SET DEFINE OFF" in Oracle Database How to insert date values into table error: ORA-65096: invalid common user or role name in oracle In Oracle SQL: How do you insert the current date + time into a table? Extract number from string with Oracle function How to run .sql file in Oracle SQL developer tool to import database? How to kill all active and inactive oracle sessions for user What does it mean when the size of a VARCHAR2 in Oracle is declared as 1 byte? How to subtract hours from a date in Oracle so it affects the day also Why does Oracle not find oci.dll? Oracle SQL - DATE greater than statement How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1 How do I view the Explain Plan in Oracle Sql developer? Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA How to change Oracle default data pump directory to import dumpfile? How can you tell if a value is not numeric in Oracle? Why do I get PLS-00302: component must be declared when it exists? Split function in oracle to comma separated values with automatic sequence DATEDIFF function in Oracle How can I solve ORA-00911: invalid character error? sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again How do I resolve this "ORA-01109: database not open" error? ORA-01653: unable to extend table by in tablespace ORA-06512 How to Select Top 100 rows in Oracle? How to determine tables size in Oracle Split String by delimiter position using oracle SQL ORA-28000: the account is locked error getting frequently Oracle Add 1 hour in SQL Oracle listener not running and won't start PLS-00428: an INTO clause is expected in this SELECT statement ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend? What is the max size of VARCHAR2 in PL/SQL and SQL? How to configure Glassfish Server in Eclipse manually Oracle query to identify columns having special characters The listener supports no services ORA-00907: missing right parenthesis NLS_NUMERIC_CHARACTERS setting for decimal copy from one database to another using oracle sql developer - connection failed Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition Equivalent function for DATEADD() in Oracle Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection? BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Questions with oracle11g tag:

Convert timestamp to date in Oracle SQL Query to display all tablespaces in a database and datafiles Oracle Installer:[INS-13001] Environment does not meet minimum requirements Forgot Oracle username and password, how to retrieve? Extract number from string with Oracle function How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1 Add days Oracle SQL How to determine tables size in Oracle ORA-28000: the account is locked error getting frequently Oracle listener not running and won't start How to calculate difference between two dates in oracle 11g SQL PLS-00428: an INTO clause is expected in this SELECT statement Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET The listener supports no services NLS_NUMERIC_CHARACTERS setting for decimal copy from one database to another using oracle sql developer - connection failed Oracle SqlDeveloper JDK path Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection? BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed Default Values to Stored Procedure in Oracle How to call Oracle MD5 hash function? How to find the users list in oracle 11g db? How to find schema name in Oracle ? when you are connected in sql session using read only user Nth max salary in Oracle How to echo text during SQL script execution in SQLPLUS PL/SQL ORA-01422: exact fetch returns more than requested number of rows Could not load file or assembly "Oracle.DataAccess" or one of its dependencies How to create a new schema/new user in Oracle Database 11g? How to move table from one tablespace to another in oracle 11g The network adapter could not establish the connection - Oracle 11g Oracle SQL query for Date format How to update cursor limit for ORA-01000: maximum open cursors exceed SQL Error: ORA-00942 table or view does not exist Grant SELECT on multiple tables oracle how to determine size of tablespace oracle 11g ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client Difference between number and integer datatype in oracle dictionary views Is it possible to use "return" in stored procedure? IO Error: The Network Adapter could not establish the connection Error while trying to retrieve text for error ORA-01019 How to get the last row of an Oracle a table Display names of all constraints for a table in Oracle SQL java.sql.SQLException: Missing IN or OUT parameter at index:: 1 Oracle pl-sql escape character (for a " ' ") MAX(DATE) - SQL ORACLE SQL to add column and comment in table in single command Using SQL LOADER in Oracle to import CSV file ORA-12514 TNS:listener does not currently know of service requested in connect descriptor How can I select from list of values in Oracle Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

Questions with oracle-sqldeveloper tag:

how to modify the size of a column How to create a blank/empty column with SELECT query in oracle? Extract number from string with Oracle function How to run .sql file in Oracle SQL developer tool to import database? SQL Developer with JDK (64 bit) cannot find JVM How do I view the Explain Plan in Oracle Sql developer? NLS_NUMERIC_CHARACTERS setting for decimal copy from one database to another using oracle sql developer - connection failed Oracle SqlDeveloper JDK path Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection? org.hibernate.QueryException: could not resolve property: filename The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program Directly export a query to CSV using SQL Developer Spool Command: Do not output SQL statement to file Creating a new database and new connection in Oracle SQL Developer How do I change the default schema in sql developer? Oracle SQL Developer spool output? How to extract week number in sql Oracle SQL Developer: Unable to find a JVM Vendor code 17002 to connect to SQLDeveloper Display all views on oracle database SQL Developer is returning only the date, not the time. How do I fix this? how to set auto increment column with sql developer How do I declare and use variables in PL/SQL like I do in T-SQL? How to create a new database after initally installing oracle database 11g Express Edition? How to Query Database Name in Oracle SQL Developer? How to increase buffer size in Oracle SQL Developer to view all records? SQL Error: ORA-00922: missing or invalid option How copy data from Excel to a table using Oracle SQL Developer How can I set a custom date time format in Oracle SQL Developer? Printing the value of a variable in SQL Developer How can I change the language (to english) in Oracle SQL Developer? Oracle SQL Developer and PostgreSQL How can I insert into a BLOB column from an insert statement in sqldeveloper? Explicitly set column value to null SQL Developer How to generate an entity-relationship (ER) diagram using Oracle SQL Developer Oracle SQL Developer - tables cannot be seen How to enter special characters like "&" in oracle database? How to export query result to csv in Oracle SQL Developer? How to Execute SQL Server Stored Procedure in SQL Developer? Run Stored Procedure in SQL Developer? How to check compiler log in sql developer? How can I use Oracle SQL developer to run stored procedures? CLEAR SCREEN - Oracle SQL Developer shortcut? Changing password with Oracle SQL Developer Where to get this Java.exe file for a SQL Developer installation How to export data with Oracle SQL Developer? How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago' Use tnsnames.ora in Oracle SQL Developer Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

Questions with sqltools tag:

Extract number from string with Oracle function