chapter five

5 Filtering on specific values

 

So far, we’ve mostly been writing queries that return an entire set of data, but as you write more purposeful SQL using larger sets of data, you will find you need only a subset of the data instead of all the rows. We did work a bit in the last chapter to reduce the number of rows returned using LIMIT and OFFSET, but those commands aren’t very helpful for finding specific rows.

For instance, you may only want a report of sales for the last month, or a list of orders with pending status, or a list of customers in New Hampshire. All these scenarios have conditions for specific data being returned, and we apply those conditions using filtering. Filtering simply means taking the broader results of your data set and applying one or more conditions to restrict the data being returned, and this is primarily done using a different clause – the WHERE clause.

It’s highly likely most of the SQL you write in your career will include a WHERE clause, as there are nearly an infinite number of ways you may need to find data that meets specific criteria. The WHERE clause is incredibly powerful, with so many ways to filter data that it will take us a few chapters just to review the myriad of ways it can be applied.

Let’s get started!

5.1 Filtering on a single condition

5.1.1 Filtering on numeric values

5.1.2 Filtering on string values

5.1.3 Filtering on date values

5.2 Filtering on multiple conditions

5.2.1 Filtering that requires all conditions

5.2.2 Filtering that requires any one of many conditions

5.2.3 Controlling the order of multiple filters

5.2.4 Filtering and using ORDER BY

5.3 Lab

5.4 Lab answers