**In Part One**we talk about concept of sets, operations on sets, started with the first one which is intersection.- Now in This part we'll complete our journey in sets by talking about the other two operations which are difference and union, so let's start.

Whats the difference between 21 and 10? If you answered 11, youre on the right track! A difference operation (sometimes also called subtract, minus, or except) takes one set of values and removes the set of values from a second set. What remains is the set of values in the first set that are not in the second set.

Lets take a look at difference in action by examining two sets of numbers.

- The first set of numbers is as follows: 1, 5, 8, 9, 32, 55, 78
- The second set of numbers is as follows: 3, 7, 8, 22, 55, 71, 99
- The difference of the first set of numbers minus the second set of numbers is the numbers that exist in the first set but not the second: 1, 5, 9, 32, 78
- Note that you can turn the previous difference operation around. Thus, the difference of the second set minus the first set : 3, 7, 22, 71, 99

- To find the difference between two sets of complex set members, you have to find the members that match on all the attributes in the second set with members in the first set.
- Dont forget that all of the members in each set youre trying to compare must have the same number and type of attributes.
- Remove from the first set all the matching members you find in the second set, and the result is the difference.
- For example, By recalling the example I mentioned early in Intersection which is the
**"lunch recipe"** - The difference between My recipes and Mikes recipes (My minus Mikes) is all the recipes in My result set that do not appear in Mikes.

- You can also turn this problem around. Suppose you want to find the recipes in Mikes result set that are not in my. Heres the answer:

- Lets assume you have a nice database containing all your favorite recipes. You really do not like the way onions taste with beef, so youre interested in finding all recipes that contain beef but not onions.
- Figure 7-3 below shows you the set diagram that helps you visualize how to solve this problem.

- The upper full circle represents the set of recipes that contain beef.
- The lower full circle represents the set of recipes that contain onions.
- As you remember from the discussion about
**INTERSECT**, where the two circles overlap is where youll find the recipes that contain both. - The dark-shaded part of the upper circle thats not part of the overlapping area represents the set of recipes that contain beef but do not contain onions.
- Likewise, the part of the lower circle thats not part of the overlapping area represents the set of recipes that contain onions but do not contain beef.

Okay, lets go back to the bicycles and helmets problem again. Lets say youre trying to solve this seemingly simple request as follows:**Example: **

**Problem statement:**Show me the orders that contain a bike but not a helmet.**Translation:**Select the distinct order numbers from the order details table where the product number is in the list of bike product numbers and product number is not in the list of helmet product numbers.**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 11) AND ProductNumber NOT IN (10, 25, 26);`

- Unfortunately, the answer shows you orders that contain only a bike! The problem is that the first
**IN**clause finds detail rows containing a bicycle, but the second**IN**clause simply eliminates helmet rows. - If you visualize orders with bicycles and orders with helmets as two distinct sets, youll find this easier to understand.
- Figure 7-9 below shows one possible relationship between the two sets of orders.

- Seeing
**except**or**but not**in your request suggests youre probably going to have to break the solution into separate sets of data and then link the two sets in some way. (Your request also needs to be broken into two parts.)

**The Problem After breaking it into two parts:****Problem 1: **

**Problem statement:**Show me the orders that contain a bike.**Translation:**Select the distinct order numbers from the order details table where the product number is in the list of bike product numbers**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 11);`

**Problem 2: **

**Problem statement:**Show me the orders that contain a helmet.**Translation:**Select the distinct order numbers from the order details table where the product number is in the list of helmet product numbers**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (10, 25, 26);`

- Now youre ready to get the final solution by usingyou guessed ita difference of the two sets.
**SQL**uses the**EXCEPT**keyword to denote a difference operation. Figure 7-10 shows you the**SQL**syntax diagram that handles this problem.

- You can now take the two parts of your request and link them with an
**EXCEPT**operator to get the correct answer: **SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 11) EXCEPT SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (10, 25, 26);`

- If you want to find out the opposite case orders for helmets that do not include bikes, you can turn it around as follows:
**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (10, 25, 26) EXCEPT SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 11);`

- The sad news is that not many commercial implementations of SQL yet support the
**EXCEPT**operator. But don't worry Ill show you an alternative method (**OUTER JOIN**) in the coming article that can solve this type of problem in another way.

Show me customers whose names are not the same as any employee.

Find all the customers who ordered a bicycle but did not order a helmet.

Find the bowlers who had a raw score of 155 or better at Thunderbird Lanes but not at Bolero Lanes.

Show me the recipes that have beef but not garlic.

- Union lets you combine two sets of similar information into one set.
- The union of two sets A and B is defined as the set of all the elements which lie in set A and set B or both the elements in A and B altogether.

- Lets take a look at union in action by examining two sets of numbers.
- The first set of numbers is as follows: 1, 5, 8, 9, 32, 55, 78
- The second set of numbers is as follows: 3, 7, 8, 22, 55, 71, 99
- The union of these two sets of numbers is the numbers in both sets combined into one new set: 1, 5, 8, 9, 32, 55, 78, 3, 7, 22, 71, 99
- that the values common to both sets, 8 and 55, appear only once in the answer.
- Also, the sequence of the numbers in the result set is not necessarily in any specific order.
- When you ask a database system to perform a
**UNION**, the values returned wont necessarily be in sequence unless you explicitly include an**ORDER BY**clause. - In
**SQL**, you can also ask for a**UNION ALL**if you want to see the duplicate members.

- The members of each set dont have to be just single values.
- To find the union of two or more sets of complex members, all the members in each set youre trying to union must have the same number and type of attributes.
- Recalling the
**"lunch recipe"**example - The union of these two sets is all the rows in both sets as shown in the figure below:

- Lets assume you have a nice database containing all your favorite recipes. You really like recipes with either beef or onions, so you want a list of recipes that contain either ingredient.
- Figure 7-5 below shows you the set diagram that helps you visualize how to solve this problem.

- The upper circle represents the set of recipes that contain beef.
- The lower circle represents the set of recipes that contain onions.
- The union of the two circles gives you all the recipes that contain either ingredient, with duplicates eliminated where the two sets overlap.

- One more problem about bicycles and helmets, then i promise you Ill pedal on to the next chapter.
- Lets say youre trying to solve this request, which looks simple enough on the first look:

**Example: **

**Problem statement:**Show me the orders that contain either a bike or a helmet.**Translation:**Select the distinct order numbers from the order details table where the product number is in the list of bike and helmet product numbers.**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 10, 11, 25, 26);`

- Actually, that works just fine! So why use a
**UNION**to solve this problem? The truth is, you probably would not. However, if I make the problem more complicated, a**UNION**would be useful:List the customers who ordered a bicycle together with the vendors who provide bicycles.

- Unfortunately, answering this request involves creating a couple of queries using JOIN operations, then using UNION to get the final result.
Because I havent shown you how to do a JOIN yet, Ill save solving this problem for a coming article . Gives you something to look forward to, doesnt it?

**Solving the bike and helmet problem using UNION:****SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 11) UNION SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (10, 25, 26);`

- The good news is that nearly all commercial implementations of
**SQL**support the**UNION**operator. - As is perhaps obvious from the examples, a
**UNION**might be doing it the hard way when you want to get an either-or result from a single table. **UNION**is most useful for compiling a list from several similarly structured but different tables. Ill explore**UNION**in much more detail in a coming article.

- A union lets you mush together rows from two similar sets, with the added advantage of no duplicate rows.
Heres a sample of the problems you can solve using a union technique with data from the sample databases:

Show me all the customer and employee names and addresses.

List all the customers who ordered a bicycle combined with all the customers who ordered a helmet.

Show me the recipes that have beef together with the recipes that have garlic.

Show me the students who have an average score of 85 or better in Art together with the students who have an average score of 85 or better in Computer Science.As with other pure set operations, one of the limitations is that the values must match in all the columns in each result set.

- This works well if youre unioning two or more sets from the same tablefor example, customers who ordered bicycles and customers who ordered helmets.
- It also works well when youre performing a union on sets from tables that have like columnsfor example, customer names and addresses and employee names and addresses.

- If you remember in high school, you might have studied set theory in a mathematics course. If you were introduced to set algebra, you probably wondered why any of it would ever be useful.
- A set can be as little as the data from one column from one row in one table. Actually, you can construct a request in
**SQL**that returns no rows an empty set. - A set can also be multiple columns (including columns you create with expressions) from multiple rows fetched from multiple tables. Each row in a result set is a member of the set. The values in the columns are specific attributes of each member (data items that describe the member of the set).

The three most common set operations are as follows:

**Intersection**

You use this to find the common elements in two or more different sets:List all students and the classes for which they are currently enrolled.

Show me the recipes that contain both lamb and rice.

Show me the customers who ordered both bicycles and helmets.**Difference**

You use this to find items that are in one set but not in another:Show me the recipes that contain lamb but do not contain rice.

Show me the customers who ordered a bicycle but not a helmet.**Union**

You use this to combine two or more similar sets:Show me all the recipes that contain either lamb or rice.

Show me the customers who ordered either a bicycle or a helmet.

List the names and addresses for both staff and students.

An intersection of two sets contains the common elements of two sets. Lets first take a look at an intersection from the pure perspective of set theory and then see how you can use an intersection to solve business problems.

- An intersection is a very powerful mathematical tool often used by scientists and engineers
- you might be interested in finding common points between two sets of chemical or physical sample data.
- Lets take a look at intersection in action by examining two sets of numbers. In this example, each single number is a member of the set.
- The first set of numbers is as follows: 1, 5, 8, 9, 32, 55, 78
- The second set of numbers is as follows: 3, 7, 8, 22, 55, 71, 99
- The intersection of these two sets of numbers is the numbers common to both sets: 8, 55
- The individual entriesthe membersof each set dont have to be just single values. In fact, when solving problems with
**SQL**, youll probably deal with sets of rows.

- According to set theory, when a member of a set is something more than a single number or value, each member (or object) of the set has multiple attributes or bits of data that describe the properties of each member.
- For example, your favorite lunch recipe is a complex member of the set of all recipes that contains many different ingredients. Each ingredient is an attribute of your complex lunch member.
- To find the intersection between two sets of complex set members, you have to find the members that match on all the attributes.
- Also, all the members in each set youre trying to compare must have the same number and type of attributes.
- For example, suppose you have a complex set like the one below, in which each row represents a member of the set (a lunch recipe), and each column denotes a particular attribute (an ingredient).

My Recipes Set

My Friend's Mike Recipes Set

The intersection of these two sets is the two members whose attributes all match in both setsthat is, the two recipes that Mike and Me have in common.

- Sometimes its easier to see how intersection works using a set diagram.
- A set diagram is an elegant yet simple way to diagram sets of information and graphically represent how the sets intersect or overlap.
- You might also have heard this sort of diagram called a Euler or Venn diagram That we will use.
- Lets assume you have a nice database containing all your favorite recipes.
- So youre interested in finding all recipes that contain both beef and onions.
- Figure 7-1 below shows the set diagram that helps you visualize how to solve this problem.

- The upper circle represents the set of recipes that contain beef.
- The lower circle represents the set of recipes that contain onions.
- Where the two circles overlap is where youll find the recipes that contain both the intersection of the two sets.
- As you can imagine, you first ask
**SQL**to fetch all the recipes that have beef. - In the second query, you ask
**SQL**to fetch all the recipes that have onions. - As youll see later, you can use a special
**SQL**keyword**INTERSECT**to link the two queries to get the final answer.

**The Sales Orders Database Schema below: **

Lets say youre trying to solve the following seemingly simple problem:

** NOTE: **

- It is know in this database that bike products has one of this ids: 1, 2, 6, 11.
- It is know in this database that helmet products has one of this ids: 10, 25, 26.

**Example: **

**Problem statement:**Show me the orders that contain**both**a bike and a helmet.**Translation:**Select the distinct order numbers from the order details table where the product number is in the list of bike and helmet product numbers.**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 10, 11, 25, 26);`

- That seems to do the trick at first, but the answer includes orders that contain either a bike or a helmet.
- And you really want to find ones that contain both a bike and a helmet! If you visualize orders with bicycles and orders with helmets as two distinct sets, its easier to understand the problem.
- Figure 7-6 below shows one possible relationship between the two sets of orders using a set diagram.

- In Figure 7-6, some orders have a bicycle in the list of products ordered, but no helmet. Some have a helmet, but no bicycle.
- The overlapping area, or intersection, of the two sets is where youll find orders that have both a bicycle and a helmet.
- Seeing word
**both**in your request's problem statement suggests youre probably going to have to break the solution into separate sets of data and then link the two sets in some way. (Your request also needs to be broken into two parts.)

**The Problem After breaking it into two parts:****Problem 1: **

**Problem statement:**Show me the orders that contain a bike.**Translation:**Select the distinct order numbers from the order details table where the product number is in the list of bike product numbers**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 11);`

**Problem 2: **

**Problem statement:**Show me the orders that contain a helmet.**Translation:**Select the distinct order numbers from the order details table where the product number is in the list of helmet product numbers**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (10, 25, 26);`

- Now youre ready to get the final solution by usingyou guessed itan intersection of the two sets.
- Figure 7-8 below shows the
**SQL**syntax diagram that handles this problem. (Note that you can use**INTERSECT**more than once to combine multiple**SELECT**statements.)

- You can now take the two parts of your request and link them with an INTERSECT operator to get the correct answer:
**SQL**:`SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (1, 2, 6, 11) INTERSECT SELECT DISTINCT OrderNumber FROM Order_Details WHERE ProductNumber IN (10, 25, 26);`

- The sad news is that not many commercial implementations of
**SQL**yet support the**INTERSECT**operator. But all is not lost! Ill show you an alternative method (**JOIN**) in The coming article that can solve this type of problem in another way. The good news is that virtually all commercial implementations of**SQL**do support**JOIN**.

- As you might guess, you can use an intersection to find the matches between two or more sets of information.
- Heres just a small sample of the problems you can solve using an intersection technique with data
from the sample databases:
Show me customers and employees who have the same name.

Find all the customers who ordered a bicycle and also ordered a helmet. Show me the students who have an average score of 85 or better in Art and who also have an average score of 85 or better in Computer Science.

Show me the recipes that have beef and garlic.

** NOTE: **

- One of the limitations of using a pure intersection is that the values must match in all the columns in each result set.
- This works well if youre intersecting two or more sets from the same table for example, customers who ordered bicycles and customers who ordered helmets.
- It also works well when youre intersecting sets from tables that have similar columns for example, customer names and employee names.
- In many cases, however, youll want to find solutions that require a match on only a few column values from each set.
- For this type of problem,
**SQL**provides an operation called a**JOIN**an intersection on key values. - Heres a sample of problems you can solve with a
**JOIN**:Show me customers and employees who live in the same city. (

**JOIN**on the city name.)

List customers and the entertainers they booked. (**JOIN**on the engagement number.)

Show me the students and their teachers who have the same first name. (**JOIN**on the first name.)

Find the bowlers who are on the same team. (**JOIN**on the team ID.)

- The type of
**SELECT**statement weve worked with so far retrieves all the rows from a given table and uses them in the statements result set. - This is great if you really do need to see all the information the table contains.
- But what if you want to find only the rows that apply to a specific person, a specific place, a particular numeric value, or a range of dates?
- You might, for example, have a need to ask the following types of questions:
Who are our customers in Seattle?

Show me a current list of our Bellevue employees and their phone numbers.

What kind of music classes do we currently offer?

Give me a list of classes that earn three credits.

Give me the names of our staff members who were hired on May 16, 1985.

- You use a
**WHERE**clause in a**SELECT**statement to filter the data the statement draws from a table. - The
**WHERE**clause contains a search condition that it uses as the filter. - This search condition provides the mechanism needed to select only the rows you need or exclude the ones you dont want.
- Your database system applies the search condition to each row in the logical table defined by the
**WHERE**clause. - A search condition contains one or more predicates, each of which is an expression that tests one or more value expressions and returns a true, false, or unknown answer.

Note All the Database Schemas and Tables mentioned here, I will put link to it at the end of the Article.

**First**, look for any words or phrases in the given problem statement that indicate or imply some type of restriction.

Dead giveaways are the words**where**,**who**and**for**Here are some examples of the types of phrases youre trying to identify:. . . who live in Bellevue.

. . . for everyone whose ZIP Code is 98125.

. . . who placed orders in May.

. . . for suppliers in California.

. . . who were hired on May 16, 1985.

. . . where the area code is 425.

. . . for Mike Hernandez.**Second**, When you find such a restriction, Study the phrase, and try to determine:- Which column is going to be tested.
- What value that column is going to be tested against.
- How the column is going to be tested. The answers to these questions will help you formulate the search condition for your
**WHERE**clause.

**Example: **

**Problem statement:**What are the names of our customers who live in the state of Washington?**Translation:**Select first name and last name from the customers table for those customers who live in Washington State.**By applying these questions to your translation statement:**- Which column is going to be tested?
**State** - What value is it going to be tested against?
**'WA'** - How is the column going to be tested?
**Using the equal to operator**

- Which column is going to be tested?
**SQL**:`SELECT CustFirstName, CustLastName FROM Customers WHERE CustState = 'WA';`

Now that you have an idea of how to create a simple WHERE clause, lets take a closer look at the five basic types of predicates you can define.

- The most common type of condition is one that uses a comparison predicate to compare two value expressions to each other.
- As you can see in Figure 6-2 below, you can define six different types of comparisons using the following comparison predicate operators:

#### Equality and Inequality

**Example #1:****Problem statement:**Show me the first and last names of all the agents who were hired on March 14, 1977.**Translation:**Select first name and last name from the agents table for all agents hired on March 14, 1977.**SQL:**`SELECT AgtFirstName, AgtLastName FROM Agents WHERE DateHired = '1977-03-14';`

**Example #2:****Problem statement:**Give me a list of vendor names and phone numbers for all our vendors, with the exception of those here in Bellevue.**Translation:**Select vendor name and phone number from the vendors table for all vendors except those based in Bellevue.**SQL:**`SELECT VendName, VendPhone FROM Vendors WHERE VendCity <> 'Bellevue';`

Note The SQL Standard uses the <> symbol for the not equal to operator. Several RDBMS programs provide alternate notations, such as != (supported by Microsoft SQL Server and Sybase) and = ( supported by IBMs DB2). <> and != (Both supported by MySQL and PostgreSQL ), Be sure to check your database systems documentation for the appropriate notation of this operator.

#### Less Than and Greater Than

**Example #1:****Problem statement:**Are there any classes that earn more than four credits?**Translation:**Select class ID from the classes table for all classes that earn more than four credits.**SQL:**`SELECT ClassID FROM Classes WHERE Credits > 4;`

**Example #2:****Problem statement:**I need the names of everyone weve hired since January 1, 1989.**Translation:**Select first name and last name as EmployeeName from the employees table for all employees hired since January 1, 1989.**SQL:**`SELECT FirstName || ' ' || LastName AS EmployeeName FROM Employees WHERE DateHired >= '1989-01-01';`

Note The SQL Standard uses the || symbol for the String Concatenation. It is supported in Oracle and IBMs DB2, But Several RDBMS programs provide alternate notations, CONCAT(string1, string2, ...., string_n).

This equivalent to:

`SELECT CONCAT(FirstName, ' ', LastName) AS EmployeeName FROM Employees WHERE DateHired >= '1989-01-01';`

- The second type of condition is one can test a value against a specific range of value with a range condition. Figure 6-3 below shows the syntax for this condition.

**Example #1: **

**Problem statement:**Which staff members were hired in July 1986?**Translation:**Select first name and last name from the staff table where the date hired is between July 1, 1986, and July 31, 1986.**SQL:**

This equivalent to:`SELECT FirstName, LastName FROM Staff WHERE DateHired BETWEEN '1986-07-01' AND '1986-07-31';`

`SELECT FirstName, LastName FROM Staff WHERE DateHired >= '1986-07-01' AND DateHired <= '1986-07-31';`

Note That In

**BETWEEN**...**AND**, The left hand of**AND**can not be greater than the right one

**Example #2: **

**Problem statement:**Show me all engagements that are scheduled to occur on October 10, 2017.**Translation:**Select engagement number, start date, and end date from the engagements table for engagements where October 10, 2017, is between the start date and the end date.**SQL:**`SELECT EngagementNumber, StartDate, EndDate FROM Engagements WHERE '2017-10-10' BETWEEN StartDate AND EndDate;`

- The third type of condition is one can test a value against a list of explicitly defined values. Figure 6-4 below, uses
**IN**predicate to determine whether the value of the first value expression matches any value within a finite list of other values.

**Example #1: **

**Problem statement:**Which entertainers do we represent in Seattle, Redmond, and Bothell?**Translation:**Select stage name from the entertainers table for all entertainers based in Seattle, Redmond, or Bothell**SQL:**

This equivalent to:`SELECT EntStageName FROM Entertainers WHERE EntCity IN ('Seattle', 'Redmond', 'Bothell');`

`SELECT EntStageName FROM Entertainers WHERE EntCity = 'Seattle' OR EntCity = 'Redmond' OR EntCity = 'Bothell';`

- The fourth type of condition is The pattern match condition, useful when you need to find values that are similar to a given pattern string or when you have only a partial piece of information to use as a search criterion. Figure 6-5 below shows the syntax for this type of condition.
- A pattern string can consist of any logical combination of regular string characters and two special wildcard characters: the percent sign
**(%)**and the underscore**(_)**.**(%)**represents zero or more arbitrary regular characters, and**(_)**represents a single arbitrary regular character.

Here are a few examples of the types of phrases youre likely to encounter:

. . . begin with Her.

. . . start with Ba.

. . . include the word Park.

. . . contain the letters han.

. . . have ave in the middle of it.

. . . with son at the end.

. . . ending in ez.

**Example #1: **

**Problem statement:**Give me a list of customers whose last names begin with Mar.**Translation:**Select last name and first name from the customers table where the last name begins with Mar**SQL:**`SELECT CustLastName, CustFirstName FROM Customers WHERE CustLastName LIKE 'Mar%';`

**Example #2: **

**Problem statement:**Show me a list of vendor names where the word Forest appears in the street address.**Translation:**Select vendor name from the vendors table where the street address contains the word Forest**SQL:**`SELECT VendName FROM Vendors WHERE VendStreetAddress LIKE '%Forest%';`

- You may encounter a search pattern request where the wildcards % and _ is a part of the pattern string.
Introducing
**ESCAPE**option:**Example #3:****Problem statement:**Show me a list of products that have product codes beginning with G_00 and ending in a single number or letter.**Translation:**Select product name and product code from the products table where the product code begins with G_00 and ends in a single number or letter**SQL:**`SELECT ProductName, ProductCode FROM Products WHERE ProductCode LIKE 'G\_00_' ESCAPE '\';`

**Explaination:**

Its clear that you need to use theoption to answer this requestotherwise, the DBMS interprets the underscore character in the pattern string as a wildcard character.*ESCAPE*

If I ask for LIKE 'G*00*', the database system will return rows where the product code has a G for the first letter, any character in the second position, zeros in the third and fourth positions, and any character in the fifth position.

When I define \ as the escape character, the database system ignores the escape character but interprets the first underscore character literally, not as a wildcard.

Because I did not use the escape character just before the second underscore, the database system interprets the second underscore as a true wildcard character.

- The fifth type of condition is checking for null condition, you know that a
**NULL**represents a missing or unknown value. This condition takes the value of the value expression and determines whether it is Null using the**IS NULL**predicate. Figure 6-6 below shows the syntax for this type of condition.

**Example #1: **

**Problem statement:**Give me a list of customers who didnt specify what county they live in.**Translation:**Select first name and last name as Customer from the customers table where the county name is unspecified**SQL:**`SELECT CustFirstName || ' ' || CustLastName AS Customer FROM Customers WHERE CustCounty IS NULL;`

- Up to this point, Weve shown how to include specific rows in a result set. Lets now take a look at how you exclude rows from a result set by using the
**NOT**operator. - As you can see in Figure 6-7 below, this operator is an optional component of the
**BETWEEN**,**IN**,**LIKE**, and**IS NULL**predicates. - A
**SELECT**statement will ignore any rows that meet the condition expressed by any of these predicates when you include the**NOT**operator. The rows that will be in the result set instead are those that did not meet the condition.

**Example #1: **

**Problem statement:**Show me a list of all the orders weve taken, except for those posted in July.**Translation:**Select order ID and order date from the orders table where the order date does not fall between October 1, 2017, and October 31, 2017**SQL:**`SELECT OrderID, OrderDate FROM Orders WHERE OrderDate NOT BETWEEN '2017-10-01' AND '2017-10-31';`

**Example #2: **

**Problem statement:**I need the identification numbers of all faculty members who are not professors or associate professors.**Translation:**Select staff ID and title from the faculty table where the title is not professor or associate professor**SQL:**`SELECT StaffID, Title FROM Faculty WHERE Title NOT IN ('Professor', 'Associate Professor');`

- The requests Weve worked with up to this point have been simple and have required only a single condition to answer. Now Well look at how you can answer complex requests using multiple conditions.
- You can combine two or more conditions by using the AND and OR operators, and the complete set of conditions youve combined to answer a given request constitutes a single search condition. As Figure 6-8 below shows.
- You can also combine a complete search condition with other conditions by enclosing the search condition in parentheses.

- The first way you can combine two or more conditions is by using the AND operator. You use this operator when all the conditions you combine must be met in order for a row to be included in a result set.

**Example #1: **

**Problem statement:**Give me the first and last names of customers who live in Seattle and whose last names start with the letter H.**Translation:**Select first name and last name from the customers table where the city is Seattle and the last name begins with H**SQL:**`SELECT CustFirstName, CustLastName FROM Customers WHERE CustCity = 'Seattle' AND CustLastName LIKE 'H%';`

- The second way to combine two or more conditions is by using the OR operator. You use this operator when either of the conditions you combine can be met for a row to be included in a result set.

**Example #1: **

**Problem statement:**I need the name, city, and state of every staff member who lives in Seattle or is from the state of Oregon.**Translation:**Select first name, last name, city, and state from the staff table where the city is Seattle or the state is OR**SQL:**`SELECT StfFirstName, StfLastName, StfCity, StfState FROM Staff WHERE StfCity = 'Seattle' OR StfState = 'OR';`

- You can use both AND and OR to answer particularly tricky requests that has multiple conditions.

**Example #1: **

**Problem statement:**I need to see the names of staff members who have a 425 area code and a phone number that begins with 555, along with anyone who was hired between October 1 and December 31 of 2007.**Translation:**Select first name, last name, area code, phone number, and date hired from the staff table where the area code is 425 and the phone number begins with 555 or the date hired falls between October 1, 2017, and December 31, 2017**SQL:**`SELECT StfFirstName, StfLastName, StfAreaCode, StfPhoneNumber, DateHired FROM Staff WHERE (StfAreaCode = '425' AND StfPhoneNumber LIKE '555%') OR DateHired BETWEEN '2017-10-01' AND '2017-12-31';`

Note, As you see comparison and pattern match conditions with an AND are dependent on each other and then treat them as a single unit, When you treat a combined set of conditions as a single unit you should enclose it in parentheses, so I probably could have gotten away with not placing parentheses around the two comparisons linked with AND. Always use parentheses to make it crystal clear

**Example #2: **

**Problem statement:**I need the name and title of every professor or associate professor who was hired on May 16, 1989.**Translation:**Select first name, last name, title, and date hired from the staff table where the title is professor or associate professor and the date hired is May 16, 1989**SQL:**`SELECT StfFirstName, StfLastName, Title, DateHired FROM Staff WHERE (Title = 'Professor' OR Title = 'Associate Professor') AND DateHired = '1989-05-16';`

- The SQL Standard specifies how a database system should evaluate single conditions within a search condition and the order in which those evaluations take place.
- By default, the database evaluates conditions from left to right. This is particularly true in the case of simple conditions.
- When a search condition contains various types of single conditions, the database evaluates them in a specific order based on the operator used in each condition. The SQL Standard defines the following order of precedence for operator evaluation.

Evaluation Order | Type of Operator |

1 | Positive sign (+), negative sign () |

2 | Multiplication (*), division (/) |

3 | Addition (+), subtraction () |

4 | =, <>, <, >, <=, >=, BETWEEN, IN, LIKE, IS NULL |

5 | NOT |

6 | AND |

7 | OR |

- You can greatly increase the accuracy of your search conditions by understanding the order of precedence. This knowledge will help you formulate exactly the right condition for the request at hand. But you must be careful to avoid defining ambiguous conditions because they can produce unexpected results.
- Lets use the following example to take a look at this potential problem:
`SELECT CustFirstName, CustLastName, CustState, CustZipCode FROM Orders WHERE CustLastName = 'Patterson' AND CustState = 'CA' OR CustZipCode LIKE '%9';`

In this instance, its difficult to determine the true intent of the search condition because there are two ways you can interpret it.

- Youre looking for everyone named Patterson in the state of California or anyone with a ZIP Code that ends with a 9.
- Youre specifically looking for everyone named Patterson and anyone who lives in California or has a ZIP Code that ends with a 9.

If you have memorized the evaluation order table, you know that the first way is correct because your system should evaluate AND before OR. But are you always going to remember the evaluation sequence?

You can avoid this ambiguity and make the search condition clearer by using parentheses to combine and prioritize certain conditions.

- To follow the first interpretation of the search condition, you define the WHERE clause in this manner:
`WHERE (CustLastName = 'Patterson' AND CustState = 'CA') OR CustZipCode LIKE '%9'`

- The second interpretation:
`WHERE CustLastName = 'Patterson' AND (CustState = 'CA' OR CustZipCode LIKE '%9')`

- To follow the first interpretation of the search condition, you define the WHERE clause in this manner:

- Sample Databases Used in This Book Implemented in various DBMS like MySQL, PostgreSQL, MS SQL, MS Access with the sample data and schema diagrams. Download It

- Search for nouns in the problem statement as it may be a table name or a column name.
- Map the extracted nouns with the suitable table and column names.
- Try to translate the statement to an abstract query
Finally, Write The SQL Version of it.

**Example**:**Problem statement**: "I need the names and addresses of all our employees."**Translation**: Select first name, last name, street address, city, state and ZIP Code from the employees table**SQL**:`SELECT FirstName, LastName,StreetAddress, City, State, ZipCode FROM Employees;`

**Example 2**:**Problem statement**: "Show me a list of vendor names in ZIP Code order in descending order:"**Translation**: Select vendor name and ZIP Code from the vendors table and order by ZIP Code DESC.**SQL**:`SELECT VendName, VendZipCode FROM Vendors ORDER BY VendZipCode DESC;`

**Simple Select Statment With Order by:**

In "Example 2" , if there is more than one vendor has the same ZIP Code, your DBMS determines the sort order by ordering vendor names Ascendingly.

By default DBMS sorts columns in ascending order even if you don't explicitly write ASC

The sequence of the columns in the ORDER BY clause is important, because DBMS will evaluate the columns in the ORDER BY clause from left to right.

- You can explicitly define how you want to order every column in the query, so if there is a tie in first one, the second will fire.
**Example**:**Problem statement**: Give me a list of all tournament dates and locations. I need the dates in descending order and the locations in alphabetical order.**Translation**: SELECT tournament date , tournament location from the tournaments table sort date descending and location alphabetically.**SQL**:`SELECT TourneyDate, TourneyLocation FROM tournaments ORDER BY TourneyDate DESC , TourneyLocation ASC;`

**Explanation**: The DBMS will sort first every row by "TourneyDate" descendingly, when there is a tie i.e. two rows have the same value for "TourneyDate" the DBMS will use the second column "TourneyLocation" defined in the ORDER BY Clause to sort and so on...

- DISTINCT is an optional keyword that precedes the list of columns specified in the SELECT clause.
- The DISTINCT keyword asks your DBMS to evaluate the values of all the columns as a single unit on a row-by-row basis and eliminate any redundant rows it finds.
- The remaining unique rows are then returned to the result set.
**Example**:**Problem statement**: Which cities are represented by our bowling league membership?**Translation**: Select Unique city name from the bowlers table**SQL**:`sql SELECT DISTINCT City FROM Bowlers;`

sql

- You can use the DISTINCT keyword on multiple columns as well.
**Example 2**:**SQL**:`sql SELECT DISTINCT City, State FROM Bowlers`

sql**Explanation**: This Query will guarantee that for every combination of city and state will be only one raw in the result set.

- The DBMS products from Microsoft like Microsoft Office Access and Microsoft SQL Server include an interesting extension
that allows you to request a subset of rows based on your ORDER BY
clause by using the TOP keyword in the SELECT clause.
**Example**:**Problem statement**: List the five most expensive products**SQL**:`SELECT TOP 5 ProductName, RetailPrice FROM Products ORDER BY RetailPrice DESC;`

- Both database systems also allow you to specify the number of rows returned as a percentage of all the rows.
**Example 2**:**Problem statement**: List the top 10 percent of products by price**SQL**:`SELECT TOP 10 PERCENT ProductName, RetailPrice FROM Products ORDER BY RetailPrice DESC;`