Lesson

The minimum Python for working with SQLite

The Python that a first program needs in order to ask a SQLite database a question: values and text, tuples, connect, cursor, execute and fetch, parameters, functions that query, and max with a key.

Last updated:


What does a Python program need in order to ask a database a question?

In the SQL guide you typed queries into DB Browser. A program sends the same queries and receives the rows as Python values.
This lesson goes through the Python that such a program uses, in the order in which a program uses it:
values and text, tuples and lists, the calls that talk to the database, parameters, a function that runs a query, and a list that is built from query results.

The data is the bike-share table daily_ridership of the guide:
731 real days, one row for each day. This lesson uses six of its columns:
year, month, season, weather (one of three labels), working_day (1 for a working day, 0 otherwise) and total_rides (the rides of that day).

Where a topic has a full lesson of its own, this lesson repeats the idea in one sentence and links to it:
values and collections, loops and functions and SQL from Python.

The examples run in your browser: select Run from top to bottom, because the boxes of the page share their variables.

A notebook is a document made of text cells and code cells: each code cell runs on its own, and its output appears below it.
The file .ipynb holds such a notebook, and Google Colab opens it in the browser, with no installation.
The same questions also appear in the notebook, and you can keep following them from there or from this page.
The notebook downloads the database from this site, so no key and no account setting is involved.

If the link does not open, open colab.research.google.com, choose File, then Upload notebook, and select the downloaded file.
The first cell downloads the database from this site, so no key and no account setting is involved.

Values, variables and print

A variable is a name that refers to a value, such as the number 985 or the text 'Mist or cloudy'.
The function print shows values on the screen: it puts a space between one value and the next, so it can show text and numbers together.
A line that starts with # is a comment: Python ignores it, and it is there for the reader.

# one day of the table
rides = 985
weather = 'Mist or cloudy'
print('Weather:', weather, 'Rides:', rides)
Weather: Mist or cloudy Rides: 985

Text and quotes

Text is written between quotes, and single and double quotes are the same.
Text in triple quotes can continue over several lines. SQL is text for Python, and it contains single quotes around its own text values, so it is written either in double quotes or in triple quotes:

label = 'Light rain or snow'
one_line = "SELECT * FROM daily_ridership WHERE year = 2012"
many_lines = """
    SELECT year, month
    FROM daily_ridership
    WHERE weather = 'Mist or cloudy'
"""
print(label)
print(one_line)
Light rain or snow
SELECT * FROM daily_ridership WHERE year = 2012

Tuples, lists and indexing

A table in a database is rows under fixed columns. A query result arrives in Python as a list of tuples:
a tuple is written with round brackets and holds a fixed number of values in order, one for each column of the SELECT, and it cannot be changed by accident.
A list is written with square brackets and holds many items, here many rows.
An index is the position of an item in square brackets, and counting starts at 0, so row[0] is the first value.

row = (2011, 1, 985)
rows = [(2011, 1, 985), (2011, 1, 801), (2011, 1, 1349)]
print(row[0], row[2])
print(rows[1])
print(rows[1][2])
2011 985
(2011, 1, 801)
801

The last line takes the second row of the list and then the third value of that row.
See tuples and lists for the full lesson.

Connect, cursor, execute, fetch

Four steps take rows from a database into Python. Each step is one line.
The line import sqlite3 makes the module sqlite3, which comes with Python, available.

Connect. The function sqlite3.connect opens the database file whose name you give it and returns a connection, an object that stands for the open database.

import sqlite3

conn = sqlite3.connect('sql-practice.sqlite')

Create a cursor. The method cursor of the connection creates a cursor, an object that sends SQL and holds the answer until you take it.

c = conn.cursor()

Execute a query. The method execute of the cursor sends one query.
It returns the cursor itself, so what you see is the cursor object, and the rows of the answer wait in it.

c.execute("""
    SELECT year, month, weather, total_rides
    FROM daily_ridership
    LIMIT 2
""")

Fetch the results. The method fetchall takes all the rows of the answer, as a list of tuples.

results = c.fetchall()
print(results)
[(2011, 1, 'Mist or cloudy', 985), (2011, 1, 'Mist or cloudy', 801)]

The method fetchmany takes the next rows, as many as the number you give it.
The method fetchone takes the next row alone, as a tuple. A query can select 731 rows while fetchmany(3) takes three of them.
Because execute returns the cursor, a fetch can follow it in the same line.
The values of a row are in the order of the SELECT: the first selected column is index 0.

three = c.execute(
    "SELECT year, month, total_rides FROM daily_ridership"
).fetchmany(3)
print(three)
row = c.execute(
    "SELECT month, total_rides FROM daily_ridership LIMIT 1"
).fetchone()
print(row)
print('Month:', row[0])
print('Rides:', row[1])
[(2011, 1, 985), (2011, 1, 801), (2011, 1, 1349)]
(1, 985)
Month: 1
Rides: 985

Summary functions in a query

The summary functions of the SQL guide work the same inside a program.
SUM(total_rides) adds the rides of the chosen days, while COUNT(*) counts the days; COUNT(weather) counts the rows that have a label and COUNT(DISTINCT weather) counts the different labels.
A summary query returns one row, so fetchone() is the right fetch, and the row is a tuple even when it holds a single value.

result = c.execute("""
    SELECT SUM(total_rides), COUNT(*)
    FROM daily_ridership
    WHERE year = 2011 AND working_day = 0
""").fetchone()
print('Rides:', result[0], 'Days:', result[1])
Rides: 386839 Days: 115

The query needs SUM because each row is a day with many rides:
COUNT(*) would return the number of days, 115, and not the rides.

Task 1 (worked example): days and labels of 2012

How many days does 2012 have in the table, and how many different weather labels do they have?
Compare COUNT(weather) with COUNT(DISTINCT weather): what does each count?
Decide before you run the code.

result = c.execute("""
    SELECT COUNT(weather), COUNT(DISTINCT weather)
    FROM daily_ridership
    WHERE year = 2012
""").fetchone()
print('Days:', result[0], 'Different weather labels:', result[1])
Days: 366 Different weather labels: 3

The year 2012 has 366 days (a leap year), every day has a label, and the labels are three in all.
The row is a tuple with two values.

A query with DISTINCT returns one row for each value, and when it selects one column the rows are tuples with one value.
Python writes such a tuple with a comma, ('Mist or cloudy',).
LIKE '%cloudy%' matches a text that contains cloudy anywhere.

Task 2 (worked example): labels that contain cloudy

How many different weather labels contain the text cloudy? Then list those labels.

result = c.execute("""
    SELECT COUNT(DISTINCT weather)
    FROM daily_ridership
    WHERE weather LIKE '%cloudy%'
""").fetchone()
print('Labels that contain cloudy:', result[0])
labels = c.execute("""
    SELECT DISTINCT weather
    FROM daily_ridership
    WHERE weather LIKE '%cloudy%'
    LIMIT 10
""").fetchall()
print(labels)
Labels that contain cloudy: 2
[('Mist or cloudy',), ('Clear or partly cloudy',)]

The count is result[0], and the list holds a tuple with one value for each label.

Task 3: rides on working days

Your turn. Use the cursor c to get the total number of rides on the working days of 2012.
Print the text Total rides: and then the number, in one print.

# your answer here
Show a hint

Write the SQL as in DB Browser: one summary function, and a WHERE with two conditions joined by AND.
The result is one row, so take it with fetchone and take the number out of the tuple with an index.

Show a solution
result = c.execute("""
    SELECT SUM(total_rides)
    FROM daily_ridership
    WHERE year = 2012 AND working_day = 1
""").fetchone()
print('Total rides:', result[0])
Total rides: 1436146

The result is a tuple with one value, so the number is result[0].

Show a common mistake and why it happens

Here COUNT(*) counts the rows, so the answer is the number of working days, not the rides on them.
To add the rides, use SUM(total_rides).

result = c.execute("""
    SELECT COUNT(*)
    FROM daily_ridership
    WHERE year = 2012 AND working_day = 1
""").fetchone()
print('Total rides:', result[0])
Show a common mistake and why it happens

The row is a tuple, even with one value, so printing it shows the brackets and the comma.
Take the value with result[0].

result = c.execute("""
    SELECT SUM(total_rides)
    FROM daily_ridership
    WHERE year = 2012 AND working_day = 1
""").fetchone()
print('Total rides:', result)

Groups and the largest total

GROUP BY puts the rows with the same value together and SUM adds each group.
ORDER BY ... DESC sorts the groups from the largest, and LIMIT 1 keeps the first.
Here they find the season with the most rides in 2011:

best = c.execute("""
    SELECT season, SUM(total_rides)
    FROM daily_ridership
    WHERE year = 2011
    GROUP BY season
    ORDER BY SUM(total_rides) DESC
    LIMIT 1
""").fetchone()
print('Season:', best[0], 'Rides:', best[1])
Season: Summer Rides: 419650

Task 4: the busiest month

Your turn. Which month of the year had the most rides in the whole table?
The rides of the same month in 2011 and in 2012 are added together.
Print the text Busiest month: and then the tuple of the month number and its total rides, in one print.

# your answer here
Show a hint

Group the rows by month, so that the same month of the two years is one group.
Sort the groups by the sum in descending order and keep one.
The row is a tuple of the month and the sum, and it is what the print shows.

Show a solution
result = c.execute("""
    SELECT month, SUM(total_rides) AS total
    FROM daily_ridership
    GROUP BY month
    ORDER BY total DESC
    LIMIT 1
""").fetchone()
print('Busiest month:', result)
Busiest month: (8, 351194)

Month 8, August, has the most rides when the two years are added together.

Show a common mistake and why it happens

The groups are sorted by the month number and not by the total, so the query returns the last month of the year, December, whatever its rides.
Sort by the sum.

result = c.execute("""
    SELECT month, SUM(total_rides) AS total
    FROM daily_ridership
    GROUP BY month
    ORDER BY month DESC
    LIMIT 1
""").fetchone()
print('Busiest month:', result)
Show a common mistake and why it happens

Without GROUP BY the sum covers the whole table, so the result is one total of all 731 days next to the month of an arbitrary row.
GROUP BY month gives one total for each month.

result = c.execute("""
    SELECT month, SUM(total_rides) AS total
    FROM daily_ridership
    ORDER BY total DESC
    LIMIT 1
""").fetchone()
print('Busiest month:', result)

Values from Python variables: parameters

A program usually asks about values that it holds in variables.
The values are passed as parameters: write a question mark ? in the SQL where a value belongs, and give the values separately, in a tuple, as the second argument of execute.
The question marks are filled in order. Python can create several variables in one line, as in the first line of the box below:
the names on the left receive the values on the right, in order (this is unpacking).

weather, year, working_day = 'Mist or cloudy', 2011, 0
query = """
    SELECT SUM(total_rides)
    FROM daily_ridership
    WHERE weather = ? AND year = ? AND working_day = ?
"""
values = (weather, year, working_day)
result = c.execute(query, values).fetchone()
print('Rides:', result[0])
Rides: 102244
Why not put the values into the text with an f-string?

An f-string pastes a value into the SQL text, and a value that contains SQL changes the query.
A season that arrives as Summer' OR '1'='1 closes the quote and adds a condition that is always true, so the query below counts all 731 days.
This is SQL injection. With ? the value is only data, and the same text matches no season:

season = "Summer' OR '1'='1"
pasted = f"""
    SELECT COUNT(*) FROM daily_ridership
    WHERE season = '{season}'
"""
print(c.execute(pasted).fetchone())
safe = """
    SELECT COUNT(*) FROM daily_ridership
    WHERE season = ?
"""
print(c.execute(safe, (season,)).fetchone())
(731,)
(0,)

SQL from Python shows this in full.

Task 5: values from variables

Your turn. Store the weather 'Clear or partly cloudy', the year 2012 and the working-day value 1 in three variables.
Use them as three ? parameters to get the total rides of those days, and print the text Total rides: and the number.

# your answer here
Show a hint

The SQL has the three conditions weather = ?, year = ? and working_day = ?, joined by AND.
The tuple of values has the variables in the same order as the question marks.

Show a solution
weather, year, working_day = 'Clear or partly cloudy', 2012, 1
query = """
    SELECT SUM(total_rides)
    FROM daily_ridership
    WHERE weather = ? AND year = ? AND working_day = ?
"""
values = (weather, year, working_day)
result = c.execute(query, values).fetchone()
print('Total rides:', result[0])
Total rides: 990444

The tuple (weather, year, working_day) follows the order of the question marks.

Show a common mistake and why it happens

The values are in a different order from the question marks, so the year is compared with the weather text and the weather with the number of the year:
no row matches and the sum is None. The tuple must follow the order of the ?.

weather, year, working_day = 'Clear or partly cloudy', 2012, 1
query = """
    SELECT SUM(total_rides)
    FROM daily_ridership
    WHERE weather = ? AND year = ? AND working_day = ?
"""
result = c.execute(query, (year, weather, working_day)).fetchone()
print('Total rides:', result[0])

Functions that query

A function gives a name to a piece of work. The line def get_name(parameter): defines it, the indented lines below are its body, and return sends a value back to the caller.
A query function takes the values it needs as parameters and passes them on as the ? values.
See loops and functions for the full lesson.

A summary query over no rows returns a missing value: SUM of nothing is NULL, and Python shows NULL as None, the value that means no value.
A function that returns a number should return 0 in that case.
A conditional expression, a if condition else b, is a when the condition is true and b otherwise, and is not None is true when a value exists:

print(
    c.execute("""
        SELECT SUM(total_rides)
        FROM daily_ridership
        WHERE season = 'Summer' AND year = 2013
    """).fetchone()
)

def get_season_rides(season, year):
    query = """
        SELECT SUM(total_rides)
        FROM daily_ridership
        WHERE season = ? AND year = ?
    """
    row = c.execute(query, (season, year)).fetchone()
    return row[0] if row[0] is not None else 0

print('Summer 2011:', get_season_rides('Summer', 2011))
print('Summer 2013:', get_season_rides('Summer', 2013))
(None,)
Summer 2011: 419650
Summer 2013: 0

The function uses the cursor c that was created above. The data covers the years 2011 and 2012, so the year 2013 has no rows.

Task 6: a function that queries

Your turn. Write a function get_total_rides(year, month) that returns the total rides of the given year and month (a whole number from 1 to 12), and 0 when no row matches.
Print the text July 2012: and the result for July 2012, then the text January 2013: and the result for January 2013, each on its own line.

# your answer here
Show a hint

Inside the function: a query with two ? parameters, fetchone, and a conditional expression that returns 0 when the first value of the row is None.

Show a solution
def get_total_rides(year, month):
    query = """
        SELECT SUM(total_rides)
        FROM daily_ridership
        WHERE year = ? AND month = ?
    """
    row = c.execute(query, (year, month)).fetchone()
    return row[0] if row[0] is not None else 0

print('July 2012:', get_total_rides(2012, 7))
print('January 2013:', get_total_rides(2013, 1))
July 2012: 203607
January 2013: 0

The year 2013 has no rows, so SUM returns None and the function returns 0.

Show a common mistake and why it happens

Without the check, the function returns row[0] as it is, so for a month with no rows the caller receives None and not a number.

def get_total_rides(year, month):
    query = """
        SELECT SUM(total_rides)
        FROM daily_ridership
        WHERE year = ? AND month = ?
    """
    row = c.execute(query, (year, month)).fetchone()
    return row[0]

print('July 2012:', get_total_rides(2012, 7))
print('January 2013:', get_total_rides(2013, 1))

A list from query results, and max with a key

A list comprehension builds a list in one line: [expression for item in rows] gives the expression for every item.
The function max returns the largest item of a list. When the items are tuples, key= says what to compare:
it receives a function, and lambda pair: pair[1] is a lambda, a one-line function without a name that returns the second value of a tuple.
Then max returns the whole tuple whose second value is the largest.

The example below collects (season, rides) tuples for 2011, with the function from the previous section.
The call fetchall completes before the loop starts, so the same cursor can run the queries inside it.
Each row of the seasons is a tuple with one value, so season[0] is the text:

season_totals = [
    (season[0], get_season_rides(season[0], 2011))
    for season in c.execute(
        "SELECT DISTINCT season FROM daily_ridership"
    ).fetchall()
]
print(season_totals)
print(max(season_totals, key=lambda pair: pair[1]))
[('Winter', 150000), ('Spring', 347316), ('Summer', 419650), ('Fall', 326137)]
('Summer', 419650)

Task 7: a list and max

Your turn. Write a function with this name and these parameters:

get_rides_by_weather_year_month(weather, year, month)

It returns the total rides on the days of that weather in that year and month, and 0 when no row matches.
Use it to build a list of (month, rides) tuples for the weather 'Clear or partly cloudy' in 2012, with one tuple for every different month in the table (the table also has the months of 2011, so select the months of 2012).
Find the tuple with the most rides with max and print it.

# your answer here
Show a hint

The function is like get_total_rides with one more condition, weather = ?.
The list comprehension runs over a query that selects the different months of 2012, and month[0] is the number of the month.

Show a solution
def get_rides_by_weather_year_month(weather, year, month):
    query = """
        SELECT SUM(total_rides)
        FROM daily_ridership
        WHERE weather = ? AND year = ? AND month = ?
    """
    row = c.execute(query, (weather, year, month)).fetchone()
    return row[0] if row[0] is not None else 0

clear = [
    (month[0], get_rides_by_weather_year_month(
        'Clear or partly cloudy', 2012, month[0]))
    for month in c.execute("""
        SELECT DISTINCT month FROM daily_ridership
        WHERE year = 2012
    """).fetchall()
]
print(max(clear, key=lambda pair: pair[1]))
(6, 174967)

Among the clear days of 2012, June has the most rides. The busiest month of 2012 as a whole is September, because the days of other weather are counted there too.

Show a common mistake and why it happens

Without key, max compares the tuples from their first value, so it returns the month with the largest number, December, and not the month with the most rides.

def get_rides_by_weather_year_month(weather, year, month):
    query = """
        SELECT SUM(total_rides)
        FROM daily_ridership
        WHERE weather = ? AND year = ? AND month = ?
    """
    row = c.execute(query, (weather, year, month)).fetchone()
    return row[0] if row[0] is not None else 0

clear = [
    (month[0], get_rides_by_weather_year_month(
        'Clear or partly cloudy', 2012, month[0]))
    for month in c.execute("""
        SELECT DISTINCT month FROM daily_ridership
        WHERE year = 2012
    """).fetchall()
]
print(max(clear))

Questions to talk about

  • Which part of the code changes when the weather, the year or the month come from variables?
  • What could go wrong if a value were pasted into the SQL text with an f-string?
  • Where did a query result become an ordinary Python value in your code?

Closing the connection

The method close of the connection closes the database when the work is done.
Closing a connection does not save changes (a program that changes data calls commit first, see SQL from Python); our queries only read.

The line below is shown and not run, because the boxes of this page share one open connection and the tasks above use it.

conn.close()

Keep in mind

  • A program asks a database in four steps: connect, cursor, execute, fetch. fetchall returns a list of tuples, fetchone one tuple, and fetchmany(n) the next n tuples.
  • The values of a row are in the order of the SELECT, and an index takes one of them: row[0].
  • Pass values with ? and a tuple of values, never by pasting text into the SQL.
  • A summary query over no rows gives None; a conditional expression, as in get_total_rides, turns it into 0.
  • max with key=lambda pair: pair[1] returns the tuple with the largest second value.