Learner
Learner

Reputation: 23

Is there any difference between And (Condition1 or Condition2) vs And Condition1 or Condition2 in SQL

I want to know. Is there any difference between below two SQL statements.

SQL Statement 1

Select Id,Code,Name from tbl_student where IsActive=1 
       And (Name like '%'+@Searchtxt+'%' OR Code like '%'+@Searchtxt+'%')

SQL Statement 2

Select Id,Code,Name from tbl_student where IsActive=1 
       And Name like '%'+@Searchtxt+'%' OR Code like '%'+@Searchtxt+'%'

I executed both the statements and got result in same time. If there is no difference then what is the better way of writing condition?

Thank you.

Upvotes: 2

Views: 100

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271151

These two conditions are different:

where IsActive=1 And
      (Name like '%'+@Searchtxt+'%' OR Code like '%'+@Searchtxt+'%')

where IsActive=1 And Name like '%'+@Searchtxt+'%' OR
      Code like '%'+@Searchtxt+'%'

The second is equivalent to:

where (IsActive=1 And Name like '%'+@Searchtxt+'%') OR
      (Code like '%'+@Searchtxt+'%')

That is, IsActive = 1 only applies to the Name comparison not the Code.

Moral: Use parentheses for your conditions. They may not always be necessary but until you are really comfortable with boolean expressions, that is the best way to go.

Upvotes: 5

Related Questions