Skip to content
Advertisement

Select rows with at least one instance of the where condition

I am new to SQL. I have the following query that selects all rows with at least one 1.

select * from numbers where n1 = '1' OR n2 = '1' 

How do I select rows with at least one 1 and one 2?

For example, if my table is like so –

n1 n2
1  1 
1  1
1  2
1  1
2  1
2  2

I would want the following output because these are the only two rows with at least one 1 and one 2.

n1 n2
1  2
2  1

I cannot do the following because this will also select rows with only one’s and only two’s.

select * from numbers where n1 = '1' OR n2 = '1' OR n1 = '2' OR n2 = '2'`

Advertisement

Answer

You could just describe the two possible combinations, like:

select * 
from numbers 
where (n1 = 1 and n2 = 2) or (n1 = 2 and n2 = 1) 

Assuming that 1 and 2 are the only possible values, as shown in your sample data, then this would also work:

where least(n1, n2) = 1 and greatest(n1, n2) = 2

Under the same assumption, better yet (as commented by Jonnix):

where n1 + n2 = 3
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement