Reputation: 23
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
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