Summing Up Musical Durations with SQL's SUM Function

Introduction and Context

Howdy Swiftie, welcome back to our exciting SQL journey using Taylor Swift's music data! To quickly recap what we've covered so far: first, we delved into the COUNT function to quantify aspects of Taylor's discography. Then, we explored the DISTINCT keyword to handle uniqueness within our data. Now, it's time to advance to the next level!

This unit shines a spotlight on the SUM function in SQL. It's an incredibly useful tool for aggregating data or calculating the sum of numerical fields. Are you curious about the total duration of each of Taylor's albums? That's exactly what we're going to find out using the SUM function!

Understanding SUM

The SUM function is an aggregate operation in SQL, used to calculate the total sum of a numerical column in a database. Think of it as a mathematical operation that adds up all the numbers in a set—simple, yet profound!

The syntax is as follows: SUM(column) where column is the name of the column for which you want to calculate the sum.

You might be wondering, "When would I need to use SUM?" Consider a situation where you have a music database like ours and want to determine the total duration of each album. That's a perfect opportunity to deploy the SUM function. Let's see how it works!

Applying SUM in a Query

Let's take a look at a query that does the above and then break it down:

SELECT Albums.AlbumName, SUM(Songs.DurationMS) AS TotalDuration
FROM Albums
JOIN Songs ON Albums.AlbumID = Songs.AlbumID
GROUP BY Albums.AlbumName;

It might seem complex, but don't worry! We're here to dissect it line by line.

  1. SELECT Albums.AlbumName, SUM(Songs.DurationMS) AS TotalDuration: This line tells SQL to extract two things—the AlbumName from the Albums table and the sum of the durations of the songs from the Songs table—which is renamed as TotalDuration using AS.
  2. FROM Albums: This line informs SQL that our main table in this operation is Albums.
  3. JOIN Songs ON Albums.AlbumID = Songs.AlbumID: Here, we express our intention to join the Albums table with the Songs table on the common field AlbumID, essentially linking albums and their respective songs.
  4. GROUP BY Albums.AlbumName: Finally, we use the GROUP BY clause to group the total durations by album name. You will learn more about GROUP BY in the next unit!
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal