Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Oracle SQL: Trying to search values containing number but exclude some of the records

Have a table containing address details with Cities for which some contain numbers that indicate the City district:

ID CITY COUNTRY
1 Praha 4 CZE
2 Dublin 1 GBR
3 Budapest 3 HUN
4 Dublin GBR
5 Praha 7 CZE
6 Budapest HUN

Would like to extract all Cities that contain numbers but excluding Praha.

Tried a combination of WHERE with LIKE and NOT LIKE or != as well as subquery excluding Praha or entire Country ‘CZE’ but always end up with all the values containing numbers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!

>Solution :

You can use:

SELECT *
FROM   table_name
WHERE  REGEXP_LIKE(city, '\s+\d+$')
AND    city NOT LIKE 'Praha%'

Or, from Oracle 12, without (slow) regular expressions:

SELECT *
FROM   table_name
WHERE  TO_NUMBER(
         SUBSTR(city, INSTR(city, ' ', -1))
         DEFAULT NULL ON CONVERSION ERROR
       ) IS NOT NULL
AND    city NOT LIKE 'Praha%'

Which, for the sample data:

CREATE TABLE table_name (ID, CITY, COUNTRY) AS
SELECT 1, 'Praha 4',    'CZE' FROM DUAL UNION ALL
SELECT 2, 'Dublin 1',   'GBR' FROM DUAL UNION ALL
SELECT 3, 'Budapest 3', 'HUN' FROM DUAL UNION ALL
SELECT 4, 'Dublin',     'GBR' FROM DUAL UNION ALL
SELECT 5, 'Praha 7',    'CZE' FROM DUAL UNION ALL
SELECT 6, 'Budapest',   'HUN' FROM DUAL;

Both output:

ID CITY COUNTRY
2 Dublin 1 GBR
3 Budapest 3 HUN

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading