Code

Ask for the Right Rows

SELECT * gives you everything. Usually you want a precise answer: some columns, from some rows, in a useful order.

rows = conn.execute(
    "SELECT name, coins FROM members "
    "WHERE coins > 10 "
    "ORDER BY coins DESC, name"
).fetchall()
  • SELECT name, coins picks the columns, in that order.
  • WHERE keeps only rows where the condition is true. Use =, <> (not equal), <, >, <=, >=, and combine with AND and OR. Text values go in single quotes: WHERE island = 'Fog Reach'.
  • ORDER BY coins DESC sorts biggest first (ASC, the default, is smallest first). , name breaks ties A to Z.
  • LIMIT 3 would keep only the first 3 rows.

Let the database do the filtering and sorting. It's fast, and the rule lives right next to the question.

Pip tip: Python glues neighbouring strings together, so end each piece with a space. "FROM members" "WHERE" becomes FROM membersWHERE, and SQL gets confused!

Assignment

  1. rich_members(conn) returns a list of (name, coins) tuples for members with at least 50 coins. Most coins first; ties in name order (A to Z).
  2. fog_roll(conn) returns a list of just the names (strings) of members on 'Fog Reach', A to Z. Loop over the rows and append each row[0].
  3. Sort with ORDER BY in SQL, not with Python's sorted().

The program should print:

[('Bram', 120), ('Ada', 75), ('Wren', 75)]
['Ada', 'Moss', 'Wren']