

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 8
click for more info
Not enough gems
Cost: 6 gems
1: What Are Aggregations?
incomplete
2: SUM
incomplete
3: MAX
incomplete
4: MIN
incomplete
5: GROUP BY
incomplete
6: Average
incomplete
7: HAVING
incomplete
8: HAVING vs. WHERE in SQL
incomplete
9: ROUND
incomplete
10: Query Practice – Average Ages
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
There are times when we need to group data based on specific values.
SQL offers the GROUP BY clause, which can group rows that have similar values into "summary" rows. It returns one row for each group. The interesting part is that each group can have an aggregation function applied to it that operates only on the grouped data.
Imagine that we have a database with songs and albums:
| song_id | title | album_id |
|---|---|---|
| 1 | Crawl | 10 |
| 2 | Oakland | 10 |
| 3 | Bonfire | 11 |
| 4 | Fire Fly | 11 |
| 5 | Heartbeat | 11 |
| 6 | Sober | 12 |
If we want to see how many songs are on each album, we can use a query like this:
SELECT album_id, COUNT(song_id) AS song_count
FROM songs
GROUP BY album_id;
This query retrieves a count of all the songs on each album. One record is returned per album, and they each have their own count:
| album_id | song_count |
|---|---|
| 10 | 2 |
| 11 | 3 |
| 12 | 1 |
Let's get the balance of each user with successful transactions, all in a single query!
| id | user_id | recipient_id | sender_id | note | amount | was_successful |