SQLite Aggregate Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

SQLite Aggregate Functions

in this tutorial, you will learn about the SQLite aggregate functions to find the maximum,
minimum, average, sum, and count of a set of values.
Aggregate functions operate on a set of rows and return a single result.
SQLite provides the following aggregate functions:

• AVG() – returns the average value of a group.


• COUNT() – returns the number of rows that match a specified condition
• MAX() – returns the maximum value in a group.
• MIN() – returns the minimum value in a group
• SUM() – returns the sum of values

We will use the tracks table from the sample database for the demonstration:

SQLite AVG() function example


SELECT
AlbumId,
ROUND(AVG(Milliseconds) / 60000 ,0) "Average In Minutes"
FROM
Tracks
GROUP BY
AlbumId;

In this example:

• First, the GROUP BY clause divides the tracks by album id into groups.
• Then, the AVG() function applies to each group that has the same album id to calculate
the average length of tracks.

SQLite COUNT() function example


The following statement returns the number of rows from the tracks table:

SELECT
COUNT(*)
FROM
tracks;
To find the albums and their corresponding track count, you use the following statement:

SELECT
AlbumId,
COUNT(TrackId) track_count
FROM
tracks
GROUP BY
AlbumId
ORDER BY
track_count DESC;

SQLite SUM() function example


The following example uses the SUM() function to calculate the length of each album in
minutes:

SELECT
AlbumId,
SUM(Milliseconds) / 60000 Minutes
FROM
tracks
GROUP BY
AlbumId;

SQLite MAX() function example


To find the longest time of all tracks, you use the MAX() function as follows:
SELECT
MAX(Milliseconds) / 60000 Minutes
FROM
tracks;

In order to find the tracks whose length are the longest.:

Select trackid,
name,max(milliseconds)
from tracks;

SQLite MIN() function example

Similarly, the following statement finds the track whose length is shortest by using
the MIN() function:

SELECT
TrackId,
Name,
MIN(Milliseconds)
FROM
tracks

Tasks:
Find the total unit price of all the tracks.
Find the number of tracks in each media type.
Find the number of tracks in each genre.
Find the total numbers of distinct countries from customers table.
Find the average time of each album in seconds.
Find the youngest employee in the company.
Find the total quantity of invoice items.
Find the track with maximum bytes.

You might also like