From the course: SQL Essential Training
Grouping with the WHERE and HAVING clause - SQL Tutorial
From the course: SQL Essential Training
Grouping with the WHERE and HAVING clause
- Now a simple way of explaining the difference between the WHERE versus the HAVING clause is the WHERE clause is for filtering non aggregate data and the HAVING is for filtering results that contain aggregates. Now, a more detailed way to describe this difference is that two types of filtering occur when both a WHERE and a HAVING clause are included in the same query. The WHERE clause tells the query what information to include from the table. Then once the information is filtered and aggregate functions are applied to the fields the HAVING clause acts as a further filter for the aggregated data. Now, let's take a look at this and add a little twist to our current request from WSDA Music management. They would now want the exact result that we have here but only for the cities that start with B. So let's alter our question here. What are the average invoice totals greater than $5 for cities starting with B? Now we already have our query filtering for the average totals that are greater than five. Now we need to include the filter for only cities that start with B. So first let's go ahead and include the WHERE clause which always comes after the FROM and before the GROUP BY. So I'm going to say WHERE and now I want where the billing cities that start with B. So I'm going to say billing city and I want to include my LIKE it's a text field. I'm including my single quotes and I want the ones that start with B. I include my wild card because I don't care what comes after B. I do care that it starts with a B. Now, let's now run our query. We now have updated results eight rows and as we can see all our billing cities start with B and all of our average invoice amounts are greater than five. Now, in this query we just performed we have done the same task as we did before but this time we added the WHERE clause to filter results to only the cities that start with B. This filtering step is performed before the HAVING and ORDER BY clauses are processed. Since we must filter before we can group the order of these filtering clauses is important and the WHERE is most always coming before the HAVING.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.