Rob Mattes
Rob Mattes

Reputation: 13

NOT LIKE failing to exclude results SQL in query

I'm using a WHERE clause to exclude certain records from my query results.

where pv_table.docindex1 IS NULL AND
  pv_table.docindex2 IS NULL AND
  (data_file.vendornumber NOT IN (00550, 00510)
   OR data_file.invoicenumber NOT LIKE 'REB0000%')

This WHERE clause is successful in eliminating records with values 00550 and 00510 in the file.vendornumber column, but it is still including records that start with 'REB0000%' in the file.invoicenumber column in the query results.

Is there something wrong with my order of operations or my syntax using NOT LIKE ?

Upvotes: 1

Views: 348

Answers (4)

Meower68
Meower68

Reputation: 1009

I think you're getting your AND and OR mixed up.

I'm thinking what you what is:

  1. vendornumber not in this set AND
  2. invoicenumber not like this

There are two ways to accomplish this

  1. change your OR to an AND, as multiple other people have suggested
  2. modify your where clause as follows:

    where pv_table.docindex1 IS NULL and pv_table.docindex2 IS NULL and not ( data_file.vendornumber in (00550, 00510) OR data_file.invoicenumber like 'REB0000%' )

Boolean algebra says that (NOT a AND NOT b) = NOT(a OR B). Both of my suggestions should give you the same result. Which one is easier to read ... debatable.

Upvotes: 0

CBS
CBS

Reputation: 50

Use 'AND' instead of 'OR'

where pv_table.docindex1 IS NULL and pv_table.docindex2 IS NULL and 
  (data_file.vendornumber not in (00550, 00510) AND data_file.invoicenumber not like 'REB0000%')

Upvotes: 1

JohnHC
JohnHC

Reputation: 11195

When using a WHERE NOT with multiple exclusion conditions, you need to use AND, not OR

Example

ColumnA
1
2
3
4
5

select ColumnA
from MyTable
where ColumnA = 1
or ColumnA = 5

If I reverse this with where ColumnA <> 1 or ColumnA <> 5, then 1 <> 5 and 5 <> 1, so both appear in the results.

So when we make a statement with a where not, we use AND to list the things we want to exclude

Upvotes: 2

Denis Kuratovich
Denis Kuratovich

Reputation: 287

You use OR in the condition, that is why you have records that start with 'REB0000%':

data_file.vendornumber not in (00550, 00510) OR data_file.invoicenumber not like 'REB0000%'

If you want to exclude it you need to use AND instead of

Upvotes: 1

Related Questions