SQL AND ,OR LOGICAL OPERATORS
The AND and OR logical operators allow you to test more than one condition in a WHERE statement. Their meanings in SQL and their meanings in English are almost identical. The AND operator means that both the condition on the left-hand side of the operator and the condition on the right-hand side must be true.
SQL AND LOGICAL OPERATOR
The AND operator displays a record if both the first condition AND the second condition are true.
SQL AND OPERATOR EXAMPLE
We have the table "books" with the following information;
And we want to select the title of the books which have isbn="4444" and the author "edu". In this case it will only be one book; "sql in 15 minutes".
We can select them through the following query;
SELECT TITLE FROM eli.books WHERE isbn='4444' and AUTHOR='edu';
As you can see below, we get the result we were expecting;
When using AND, put the condition least likely to be true first. The database system evaluates
conditions from left to right, subject to operator precedence. If you have two or more AND operators
in a condition, the one to the left is evaluated first, and only if it's true is the next condition
evaluated. Finally, if that condition is true, then the third condition is evaluated. You can
save the database system work, and hence increase speed, by putting the least likely condition
first.
SQL OR LOGICAL OPERATOR
The OR operator displays a record if either the first condition OR the second condition is true.
SQL OR OPERATOR EXAMPLE
With the same table "books" we can select the titles of the books which have the "isbn=4444" or the author="eli":
SELECT TITLE FROM eli.books WHERE isbn='4444' or AUTHOR='ELI';
So far you've used only one AND or OR operator in each WHERE clause, but you can include as many,
within reason, as you like. You can also mix AND and OR operators in the same WHERE clause.
<< Previous | Next >> |