SQL tutorial •

AND / OR: Filtering your data with several conditions

For slightly more advanced analysis, filtering based on one condition is often not enough. You can combine several conditions in your <span class="code">WHERE</span> statement by using the statements <span class="code">AND</span> and <span class="code">OR</span>. For example, you might want to only see fulfilled orders and only to a shipping address in certain countries — let’s say Sweden, Norway, and Australia. This information is located in the <span class="code">Order</span> table, so you’ll need to go back to it. These conditions could be defined in a query like this:

While SQL code, in general, is not case sensitive, the values you use as conditions encapsulated by single quotation marks are sensitive to upper and lower letters. Make sure you write the conditions exactly as written in the query above. If you run this query on your own, the result should look like this:

The <span class="code">AND</span> statement only returns values if both conditions are satisfied, while the <span class="code">OR</span> statement returns values if just one of the conditions is satisfied. As you see in the query above, you can combine these statements as you please, and in that way create your own advanced filter.

Exercise 3: Find all items where the price is between 50 and 55

Continue with the <span class="code">webshop_order_line</span> table from the exercise before. This time you want to find the items where the price is between 50 and 55. See if you can write a query to get to this result. If you run your query, it should give a result like this: 

In SQL there are often many means to an end, so you’ll usually be able to get the required result by writing different variations of the same query. A simple way to solve the exercise above would be to write a query like this:

Next up
Filtering on non-exact values with LIKE