Advanced Features

The SQL we have seen so far is powerful enough for many everyday tasks, but other questions require more powerful tools. This section introduces a handful and shows when and how they are useful.

Aggregation

Our next task is to calculate the total projected world population for the year 2300. We will do this by adding up the values in PopByRegion’s Population column using the SQL aggregate function SUM:

 >>>​​ ​​cur.execute(​​'SELECT SUM (Population) FROM PopByRegion'​​)
 <sqlite3.Cursor object at 0x102e3e490>
 >>>​​ ​​cur.fetchone()
 (8965762,)

SQL provides several other aggregate functions. All of these are associative; that is, the result doesn’t depend on the order of operations. This ensures that the result doesn’t ...

Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.