简体   繁体   中英

Oracle SQL — “not in” missing some rows?

I have a very simple query to find some values that are in one table, but not another.

select * from my_table were my_value in
   ('one','two','hello','blue')
and my_value not in
   (select my_value from my_table_2)

This returns two rows -- the rows of my_table with 'one' and 'two'.

But, then I ran this:

select * from my_table_2 where my_value in ('one','two')

and was shocked to discover that this returned two rows in my_table_2, with values of 'one' and 'two.'

The "not in" is getting 99% of the right things, but randomly missing a few values. What is the cause of this?

EDIT: Sorry, typo. Fixed it.

My bet is that my_table2 contains NULL values in the my_value column. NOT IN doesn't work as you might expect if your column contains NULL values, see Techrepublic article on EXISTS / IN and NULL values

I'd use NOT EXISTS in that case, should work as expected.

The cause of this issue was the difference in column types between the two tables.

my_table was using varchar2(10), but my_table_2 was using char(10). As a result, my_table_2 is actually returning what's in my_table_1, plus some spaces. Interestingly, even though 'apple', for example, would be 'apple ', select my_value from my_table_2 where my_value = 'apple' does return the row.

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