Kevin Meredith
Kevin Meredith

Reputation: 41939

Understanding Postgres Query

Regarding the difference between...

select * from table_a where id != 30 and name != 'Kevin';

and

select * from table_a where id != 30 or name != 'Kevin';

First one means, "select all rows from table_a where the id is not 30 and the name is not Kevin".

So {Id, Name} row of {30, 'Bill'} would be returned from this first query.

But, the second one means, "select all rows from table_a where the id is not 30 or the name is not 'Kevin'".

So the above {30, 'Bill'} would not be returned from this second query.

Is that right?

Upvotes: 0

Views: 58

Answers (4)

rzcs
rzcs

Reputation: 51

Quick logic expression transformation tip:

NOT (A AND B) == NOT A OR NOT B

NOT (A OR B) == NOT A AND NOT B

Upvotes: 0

Houari
Houari

Reputation: 5651

Recap:

A   B   not(A)  not(B)      AND     OR
1   1   0         0         0       0
1   0   0         1         0       1
0   1   1         0         0       1
0   0   1         1         1       1

So, the two query's will return the same rows only if:

1- id=30 and name='Kevin'

or

2- id!=30 and name!='Kevin'

Upvotes: 0

Erwin Brandstetter
Erwin Brandstetter

Reputation: 659317

select * from table_a where id != 30 and name != 'Kevin';

So {Id, Name} row of {30, 'Bill'} would be returned from this first query.

No, it wouldn't.

select * from table_a where id != 30 or name != 'Kevin';

So the above {30, 'Bill'} would not be returned from this second query.

No, it would. You have the logic backwards. Just try it.

Upvotes: 2

David Aldridge
David Aldridge

Reputation: 52396

Nope. The second query means "select all rows where the id is not 30 or the name is not 'Kevin'", hence a name of 'Bill' qualifies the record for inclusion in the query.

Upvotes: 0

Related Questions