Starting here? This lesson is part of a full-length tutorial in using SQL for Data Analysis. Check out the beginning.
SQL Logical operators
In the previous lesson, you played with some comparison operators to filter data. You’ll likely also want to filter data using several conditions—possibly more often than you’ll want to filter by only one condition. Logical operators allow you to use multiple comparison operators in one query.
Each logical operator is a special snowflake, so we’ll go through them individually in the following lessons. Here’s a quick preview:
LIKE allows you to match similar values, instead of exact values.
IN allows you to specify a list of values you’d like to include.
BETWEEN allows you to select only rows within a certain range.
IS NULL allows you to select rows that contain no data in a given column.
AND allows you to select only rows that satisfy two conditions.
OR allows you to select rows that satisfy either of two conditions.
NOT allows you to select rows that do not match a certain condition.
About this dataset
To practice logical operators in SQL, you’ll be using data from Billboard Music Charts. It was collected in January 2014 and contains data from 1956 through 2013. The results in this table are the year-end results—the top 100 songs at the end of each year.
To access the dataset, use the following query:
SELECT * FROM tutorial.billboard_top_100_year_end
year_rank is the rank of that song at the end of the listed year.
group is the name of the entire group that won (this could be multiple artists if there was a collaboration).
artist is an individual artist. This is a little complicated, as an artist can be an individual or group.
You can get a better sense of some of the nuances of this dataset by running the query below. It uses the
ORDER BY clause, which you’ll learn about in a later lesson. Don’t worry about it for now:
ORDER BY year DESC, year_rank
You’ll notice that Macklemore does a lot of collaborations. Since his songs are listed as featuring other artists like Ryan Lewis, there are multiple lines in the dataset for Ryan Lewis. Daft Punk and Pharrell Williams are also listed as two artists. Daft Punk is actually a duo, but since the album lists them together under the name Daft Punk, that’s how Billboard treats them.
Now onto learning about each logical operator!