Thursday, April 26, 2012

SQL AND and OR


Hello everyone in this post, I will discussing the SQL AND and OR Operator that are used in conjunction with WHERE clause, to display a result set according to the condition.

Before I start let me explain the AND Operator, the AND Operator makes a value True, when both the inputs are True.

Example: 1 AND 1 = True,

And for the OR, if either of the input value is True, the result set will be True.

Example: 1 OR 0 = True, 1 OR 1 = True, 0 OR 1 = True, 0 OR 0 = False

Now that was just a basic Digital Circuit explanation of AND and OR Operator, its pretty much same in SQL.

Lets say we have a Table named Employee, and we have 3 columns for the table, first column named as FirstName, second column named as LastName, and the Third Column named as Designation.

and assume we have 4 records,

FirstName    LastName    Designation
 Daniel             Golmes       Associate
 Whiskey         Lullaby        Admin
 Beer               Lullaby        Admin
 Onty               Golmes       Admin


So lets assume we have these 4 records, for our table in respective columns.

Now for our SQL Query:

SELECT * FROM Employee
WHERE FirstName = "Whiskey" AND LastName = "Lullaby"


With this query, one record would be dumped, ie:

FirstName LastName Designation
 Whiskey       Lullaby     Admin

Why so? Its very easy to understand, because in the whole table, it found only one record, that satisfied our query.

Next lets see the use of OR Operator:

SELECT * FROM Employee
WHERE FirstName = "Whiskey" OR LastName = "Golmes"


With This Our Result set would be:

FirstName   LastName  Designation
 Whiskey          Lullaby      Admin
 Daniel             Golmes      Associate
 Onty               Golmes      Admin

And I wont explain this, I leave that to you to find it.

And We can even combine both AND and OR Operator:

SELECT * FROM Employee
WHERE LastName="Lullaby" AND FirstName=("Whiskey" OR "Beer")


Result-set:

FirstName    LastName    Designation
 Whiskey         Lullaby        Admin
 Beer               Lullaby        Admin

Thats all friends for this post, hope you enjoyed it, and Don't Forget to check my next Post.

Thank You!

0 comments:

Post a Comment