Cesar Bielich
Cesar Bielich

Reputation: 4945

using AND or OR function after/before a BETWEEN in mysql

I am using a query like

WHERE this.ID BETWEEN 1 AND 11

but I want to add another ID to this like

WHERE this.ID BETWEEN 1 AND 11 AND this.ID = 22

or even

WHERE this.ID = 22 AND this.ID BETWEEN 1 AND 11

This causes an error.

Am I stuck with using WHERE this.ID >= 1 AND this.ID <= 11 AND this.ID = 22? Is there an easier way to do this?

Upvotes: 1

Views: 576

Answers (2)

Nishant Nair
Nishant Nair

Reputation: 2007

I have tried it on my shell

SELECT * FROM tablename WHERE (id BETWEEN 1 AND 2) or (ID = 3)

This gives result with no error

SELECT * FROM tablename WHERE (id BETWEEN 1 AND 2) AND (ID =3) 

This give empty result with no error.

As you can see you are fetching result between two ids and also passing AND condition with different id the result will be empty

Upvotes: 0

krishn Patel
krishn Patel

Reputation: 2599

when you use AND it will check id is must equal to 1 to 11 and 22.

Id can not have same time two value.

You should use OR. But when you use OR condition you must put it in (). so other condition will work properly.

you can add other condition after bracket.

WHERE (this.ID BETWEEN 1 AND 11 OR this.ID = 22)

Upvotes: 1

Related Questions