MySQL Lesson 10: Creating Views

Advertisements

Hello everybody,

This is Michael, and today’s post will be about creating views. This will be the last post in this series of MySQL lessons, but I’ll likely have more MySQL lessons and/or analyses in the future, so keep following my posts.

Anyway, views are basically virtual tables created from queries that allow you to query the data within them. Here’s an example:

26Oct capture2

Here, I am building a view from the query, which consists of the block of code between the parentheses. In the query, I selected the foreign key Album_idAlbum and the fields Ceremony and Won/Nominated from the Awards table. I narrowed down the criteria so that Album_idAlbum with keys greater than 30 and less than 58 will be displayed. In other words, I only want the query-and in turn, the view-to include awards considerations for albums released in the 2010s, hence the view’s name 2010s Album Awards.

  • The syntax for views is ALWAYS:
    • CREATE VIEW (name of view) AS (query)
  • Parentheses aren’t necessary when creating views. I just use them to improve readability of the code.

If you press the refresh button on the “Schemas” tab, the view will appear.

You can even query the data in the view. Here’s an example:

Using every field from the view, I asked the query to only display the Album_idAlbum of any album that was considered (whether they won or were just nominated) for a Teen Choice Award, which only applied to one album in this case (Usher’s 2010 album Raymond v. Raymond).

Let’s try another example. First we’ll create a view consisting of any debut albums listed on the database (WHERE Album Number = 1 refers to debut albums), along with the corresponding [Album] Release Date and Singer Name (referring to which singer/group created the album):

  • JOINs are perfectly fine to include in views-honestly anything you can include in a normal query you can include in a view.

Then we hit the refresh button on the “Schema” tab to see if the view was created (which it was).

And finally, let’s query this view:

In this query, I selected the fields [Album] Name and Singer Name from the view and asked the query to only display albums WHERE MONTH(Release Date) = 1 OR MONTH(Release Date) = 2, which refers to albums released in January or February. As you can see, two albums fit the criteria.

Thanks for reading,

Michael

 

MySQL Lesson 9: More Joins

Advertisements

Hello everybody,

My name is Michael, and today’s post will be a continuation of the previous post’s lesson on JOINs. As I mentioned in the previous post, JOINs are queries that join columns from different tables together based on a common column in each table (or in the case of SELF-JOINs, connected columns from the same table-more on that later in this post).

The first type of JOIN I will cover in this post is FULL JOIN, which returns all records from both the left-linked and right-linked tables and fills in NULL for missing matches from either table. Here’s an example:

I selected the fields Name and Release Date from the Album table and the fields Ceremony and Won/Nominated from the Awards table (which I FULL JOINed to the Album table). I then linked the two tables using the idAlbum/Album_idAlbum primary/foreign key. Had there been an album that wasn’t in consideration for an award (for instance Grace VanderWaal’s Just The Beginning), then the Ceremony and Won/Nominated fields corresponding to that album would NULL (Name and Release Dat will still be displayed).

With FULL JOINs, keep in mind that if you don’t filter out results, you could end up with a large result set (this query returned 216 rows of data). Here’s the same FULL JOIN query except with a WHERE clause to filter out results:

This query is similar to the previous one, except that it only shows the rap albums that were considered for awards (and as a result, show only 41 rows of data as opposed to the 216 rows returned from the previous query).

The next type of join I will cover is the SELF JOIN, which basically joins a table to itself. Here’s an example:

I selected the fields Singer Name, Age, and Member of from the Singer table, but there’s a catch. See, because I’m joining a table to itself, I need to give aliases to each of the instances of the table in this query. I went with S* for the Singer table before the JOIN clause and B** for the Singer table after the JOIN clause. As you can see, I had to include the aliases before each field name (S for Singer Name and Age and B for Member of). In my WHERE clause, notice how I mention Member of twice in the line WHERE B.Member of IS NOT NULL AND S.Member of IS NOT NULL. I did this so that only the members of a band are listed alongside the corresponding band/group; when I only included WHERE B.Member of IS NOT NULL, the band name would display alongside itself (e.g. Imagine Dragons was listed as a member of Imagine Dragons).

*for Singer

**for Band (or Group)

Now let’s filter the results further:

It’s the same query as above, except with the addition of the AND S.Death IS NOT NULL, which asks the query to display any deceased singers part of groups. As you can see, only 1 singer in the database meets this criteria (Linkin Park’s Chester Bennington, who died on July 20, 2017).

Let’s try a different filter to the query:

This is similar to the first SELF JOIN query I did, except the filter asks the query to only display band singers under 40 years old (hence the S.Age < 40 line), of which there are 10.

The last JOIN I will cover in this post is the UNION query, which, even though it does not have JOIN in its name, still serves a function similar to JOINs (except entire queries are being joined together, not just tables).

Here’s an example of a UNION query:

In each individual query, I selected the fields Track Name and Track Duration from the Tracks table and joined the two queries together with a UNION clause. The one difference between the two queries is their WHERE clauses; the top query retrieves the name of the longest song (Empire of the Clouds by Iron Maiden at a whopping 18 minutes and 1 second) and the bottom query retrieves the name of the shortest song (Intro by 50 Cent at a mere 6 seconds).

Some things to keep in mind with UNION queries include:

  • UNIONs only work with the same number of columns in both queries (I selected two columns in both the top and bottom queries)
  • They work best when the columns selected in each query-along with any aliases- and the order in which the columns/aliases are listed are identical. Though there should be at least one difference between the two queries, as I have in my query (the WHERE clause has MAX for the top query and MIN for the bottom one).

Here’s another slightly more complex UNION query

In each query, I selected the foreign key Album_idAlbum and the aggregate function COUNT(Album_idAlbum)-using the alias Awards Considerations-from the Awards table. I also remember to GROUP BY the same thing in each table (the Album_idAlbum foreign key). The one difference between each query is the WHERE clause, as I selected Album_idAlbum 34 for the top query and Album_idAlbum 48 for the bottom one (both are rock albums, with 34 being Mylo Xyloto by Coldplay and 48 being Smoke+Mirrors by Imagine Dragons). As you can see, Mylo Xyloto was considered for 8 awards while Smoke+Mirrors was only considered for 1 award.

Before I go, here’s a spreadsheet with the modified Singer table (couldn’t save SQL files on WordPress)-Singer table modified.

Thanks for reading,

Michael

MySQL Lesson 8: Joins

Advertisements

Hello everybody,

It’s Michael, and this post (and the next) will be covering joins in MySQL. Joins are essentially queries that are meant to retrieve data from several tables rather than just a single table. I’ll take two posts to cover joins because there are several different types of joins.

But first, here’s a slight modification to the database, which I felt would be appropriate when learning about joins:

The two new fields included are:

  • Singer_idSinger-Ok, this is more of a foreign key, but it indicates the band/group the singer belongs to (e.g. Dan Reynolds is a part of the band Imagine Dragons). For individual singers, the value in this field will be the same as the value in the idSinger primary key.
  • Member of-What band (if any) a singer is part of. If the singer isn’t part of a band, then this field will be NULL.

The arrow on top of the singer table indicates a unary one-to-many relationship. Unary basically means the table relates to itself (which is perfectly fine by MySQL standards); the one-to-many in this case means that a band must have MANY (at least 2) singers while each singer must belong to only ONE band.

This type of relationship works best for SELF JOIN queries, which are queries that join a table to itself. I’ll cover them more in the next post.

The first type of join I will focus on is an INNER JOIN. Here’s a query using INNER JOIN:

INNER JOIN queries basically join columns from different tables using values common to both tables (which are usually foreign/primary keys); results are returned only if a row in both tables matches the JOIN condition. In this case; the common column is Singer_idSinger-the Singer and Album tables both have this column.

  • You don’t have to display the common column in the query results; just remember to include it in the ON clause. This goes for all JOIN queries.

I first selected the field Singer Name from the Singer table and the fields Name and Release Date from the Album table (which is INNER JOINed to the Singer table). I then linked both tables through the Singer_idSinger primary/foreign key (which is the common column among both tables). I finally narrowed down the criteria to only include albums WHERE Release Date > Death so that only posthumous albums (along with corresponding singer name and release dates) are displayed.

  • INNER JOIN queries will work the same without the word INNER, as seen below:

The next type of JOIN I will cover is a LEFT JOIN, which basically goes:

  • SELECT (columns) FROM (table A) LEFT JOIN (table B) ON (table A.column) = (table B.column)

Like INNER JOIN queries, LEFT JOIN queries link tables based on common columns. The difference between these two types of queries are that INNER JOIN queries retrieve results that have matching values in both tables, while LEFT JOIN queries retrieve all results from the left-linked table (table A) and any matching results from the right-linked table (table B).  If there are no matching results from the right-linked table, NULL will be displayed on any rows connected to the right-linked table (this is not the case with INNER JOINS).

Here’s an example of a LEFT JOIN query:

In this query, I am selecting the fields Track Name from the Tracks table and Featured Artist Name from the Featured Artist table (which is LEFT JOINed to the Tracks table). I filtered out the results so that only tracks WHERE Album_idAlbum = 44  (44 is the primary key for Linkin Park’s The Hunting Party if you were wondering) are displayed. The query will display all the records from the left-linked table (in other words, every track from The Hunting Party) along with matching records from the right-linked table (meaning if there are any guest artists on a track). For tracks without guest artists, NULL is displayed on the right side rows.

The last of the joins I will cover is the RIGHT JOIN, which is basically the opposite of LEFT JOIN because the query retrieves all results from the right-linked table (table B) and any matching results from the left-linked table (table A). Should there be no matching results in the left-linked table, NULL will be displayed on any rows connected to the left-linked table (so basically the opposite of what happens in a LEFT JOIN query).

Here’s an example of a RIGHT JOIN query:

In this query, I selected the field Name from the Album table and the field Won/Nominated from the Awards table (which is RIGHT JOINed to the Album table). I then used the idAlbum/Album_idAlbum (they’re the same thing) primary/foreign keys to link the two tables. I also narrowed down the criteria so as to only display albums WHERE Won/Nominated = "Won" AND Ceremony = "Grammys" (referring to album that won Grammys). The query will display all results from the right-linked table (any Grammy wins) and any matching records from the left-linked table (the names of albums that won Grammys).

  • For every result from the right-linked table (Awards), there are matching results from the left-linked table (Album). Had this not been the case, you would be seeing NULL in rows linked to the Name column.

Thanks for reading, and be sure to check out the next post with more JOINs.

Michael