简体   繁体   中英

Oracle SQL — find the values NOT in a table

Take this table WORDS

WORD
Hello
Aardvark
Potato
Dog
Cat

And this list:

('Hello', 'Goodbye', 'Greetings', 'Dog')

How do I return a list of words that AREN'T in the words table, but are in my list?

If I have a table that "contains all possible words", I can do:

SELECT * from ALL_WORDS_TABLE
where word in ('Hello', 'Goodbye', 'Greetings', 'Dog')
and word not in 
(SELECT word from WORDS
where word in ('Hello', 'Goodbye', 'Greetings', 'Dog')
);

However I do not have such a table. How else can this be done?

Also, constructing a new table is not an option because I do not have that level of access.

Instead of hard coding the list values into rows, use DBMS_DEBUG_VC2COLL to dynamically convert your delimited list into rows, then use the MINUS operator to eliminate rows in the second query that are not in the first query:

select column_value 
from table(sys.dbms_debug_vc2coll('Hello', 'Goodbye', 'Greetings', 'Dog'))
minus
select word
from words;

You can turn your list into a view like this:

select 'Hello' as word from dual
union all
select 'Goodbye' from dual
union all
select 'Greetings' from dual
union all
select 'Dog' from dual

Then you can select from that:

select * from
(
    select 'Hello' as word from dual
    union all
    select 'Goodbye' from dual
    union all
    select 'Greetings' from dual
    union all
    select 'Dog' from dual
)
where word not in (select word from words);

Possibly not as neat a solution as you might have hoped for...

You say you don't have sufficient privileges to create tables, so presumably you can't create types either - but if you can find a suitable type "lying around" in your database you can do this:

select * from table (table_of_varchar2_type('Hello','Goodbye','Greetings','Dog'))
where column_value not in (select word from words);

Here table_of_varchar2_type is imagined to be the name of a type that is defined like:

create type table_of_varchar2_type as table of varchar2(100);

One such type you are likely to be able to find is SYS.KU$_VCNT which is a TABLE OF VARCHAR2(4000).

Try this solution :

SELECT
 a.word
FROM
(
 SELECT 'Hello' word FROM DUAL UNION
 SELECT 'Goodbye' word FROM DUAL UNION
 SELECT 'Greetings' word FROM DUAL UNION
 SELECT 'Dog' word FROM DUAL
) a
LEFT JOIN ALL_WORDS_TABLE t ON t.word = a.word
WHERE
 t.word IS NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM