{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c001",
   "metadata": {},
   "source": [
    "# The minimum Python for working with SQLite"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c002",
   "metadata": {},
   "source": [
    "## What does a Python program need in order to ask a database a question?\n",
    "\n",
    "In the [SQL guide](https://dvirross.com/courses/intro-data-science/sql-in-db-browser) 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.\n",
    "\n",
    "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).\n",
    "\n",
    "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](https://dvirross.com/courses/intro-data-science/python-values-and-collections), [loops and functions](https://dvirross.com/courses/intro-data-science/python-loops-and-functions) and [SQL from Python](https://dvirross.com/courses/intro-data-science/sql-from-python)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c003",
   "metadata": {},
   "source": [
    "**How to work:** run the cells from top to bottom, because the cells share their variables. A cell that says `# Your turn` is empty: write your code there, run it, and run the cell under it, which checks your answer without showing the solution. The notebook with solutions has the solution, the common mistakes and the expected output under every task."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c004",
   "metadata": {},
   "source": [
    "## Setup: get the database file\n",
    "\n",
    "No account and no key are needed. The next cell downloads the course database from the public site and saves it next to the notebook (in Colab it appears in the **Files** panel). If the download fails, open the address below in a browser, download the file, and upload it to the **Files** panel of Colab.\n",
    "\n",
    "`https://dvirross.com/materials/courses/intro-data-science/sql-practice.sqlite`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c005",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:45.943308Z",
     "iopub.status.busy": "2026-11-01T21:23:45.942999Z",
     "iopub.status.idle": "2026-11-01T21:23:45.965907Z",
     "shell.execute_reply": "2026-11-01T21:23:45.964454Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Database file ready: sql-practice.sqlite\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import urllib.request\n",
    "\n",
    "DB_URL = 'https://dvirross.com/materials/courses/intro-data-science/sql-practice.sqlite'\n",
    "DB_PATH = 'sql-practice.sqlite'\n",
    "\n",
    "if not os.path.exists(DB_PATH):\n",
    "    # the site refuses the default user agent of Python, so the request names one\n",
    "    request = urllib.request.Request(DB_URL, headers={'User-Agent': 'Mozilla/5.0'})\n",
    "    with urllib.request.urlopen(request) as response, open(DB_PATH, 'wb') as file:\n",
    "        file.write(response.read())\n",
    "print('Database file ready:', DB_PATH)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c006",
   "metadata": {},
   "source": [
    "The next cell defines the function `check(task_number)`. After you run the cell of a task, run the cell under it: `check` runs your cell again, collects what it prints, and compares it with the expected output. It tells you whether the output is right, and where it differs if not; it never shows the solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c007",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:45.968217Z",
     "iopub.status.busy": "2026-11-01T21:23:45.967968Z",
     "iopub.status.idle": "2026-11-01T21:23:45.976479Z",
     "shell.execute_reply": "2026-11-01T21:23:45.974333Z"
    }
   },
   "outputs": [],
   "source": [
    "import ast, contextlib, hashlib, io\n",
    "\n",
    "# The expected output of each task, as hashes of its lines (the solutions are not stored here).\n",
    "EXPECTED = {int(k): v for k, v in {\n",
    "    '3': [\n",
    "        '4963af400ece'\n",
    "    ],\n",
    "    '4': [\n",
    "        '7d827bbe5897'\n",
    "    ],\n",
    "    '5': [\n",
    "        '14e4e0edb1cb'\n",
    "    ],\n",
    "    '6': [\n",
    "        '2b855e705c53',\n",
    "        'fa4ea1bc266c'\n",
    "    ],\n",
    "    '7': [\n",
    "        '28af1299a0b7'\n",
    "    ]\n",
    "}.items()}\n",
    "\n",
    "\n",
    "def check(task):\n",
    "    \"\"\"Run the last cell that ran (not a check) again and compare what it prints with the expected output of the task.\"\"\"\n",
    "    if task not in EXPECTED:\n",
    "        print('There is no such task: ', task)\n",
    "        return\n",
    "    cells = [s for s in In[:-1] if s.strip() and not s.lstrip().startswith('check(')]   # In: the cells that ran, kept by IPython\n",
    "    tree = ast.parse(cells[-1] if cells else '')\n",
    "    last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None   # a bare last expression counts as printed\n",
    "    out = io.StringIO()\n",
    "    try:\n",
    "        with contextlib.redirect_stdout(out):\n",
    "            exec(compile(tree, '<task>', 'exec'), globals())\n",
    "            if last is not None:\n",
    "                value = eval(compile(ast.Expression(last.value), '<task>', 'eval'), globals())\n",
    "                if value is not None:\n",
    "                    print(repr(value))\n",
    "    except Exception as error:\n",
    "        print('The cell raised an error:', type(error).__name__ + ':', error)\n",
    "        return\n",
    "    got = [hashlib.sha256(line.rstrip().encode()).hexdigest()[:12] for line in out.getvalue().rstrip().splitlines()]\n",
    "    want = EXPECTED[task]\n",
    "    if not got:\n",
    "        print('Nothing was printed. Print the answer in the task cell, run it, and run `check` straight after it.')\n",
    "    elif len(got) != len(want):\n",
    "        print('The cell printed {got} line(s) and the task expects {want}. Re-read the task and the hint.'.format(got=len(got), want=len(want)))\n",
    "    elif got != want:\n",
    "        print('Line {k} is different from the expected output. Re-read the task and the hint.'.format(k=next(i for i in range(len(want)) if got[i] != want[i]) + 1))\n",
    "    else:\n",
    "        print('OK: the output is as expected.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c008",
   "metadata": {},
   "source": [
    "## Values, variables and `print`\n",
    "\n",
    "A **[variable](https://dvirross.com/courses/intro-data-science/glossary#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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c009",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:45.979232Z",
     "iopub.status.busy": "2026-11-01T21:23:45.978981Z",
     "iopub.status.idle": "2026-11-01T21:23:45.986582Z",
     "shell.execute_reply": "2026-11-01T21:23:45.985395Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Weather: Mist or cloudy Rides: 985\n"
     ]
    }
   ],
   "source": [
    "# one day of the table\n",
    "rides = 985\n",
    "weather = 'Mist or cloudy'\n",
    "print('Weather:', weather, 'Rides:', rides)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c010",
   "metadata": {},
   "source": [
    "## Text and quotes\n",
    "\n",
    "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c011",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:45.988926Z",
     "iopub.status.busy": "2026-11-01T21:23:45.988704Z",
     "iopub.status.idle": "2026-11-01T21:23:45.994092Z",
     "shell.execute_reply": "2026-11-01T21:23:45.992080Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Light rain or snow\n",
      "SELECT * FROM daily_ridership WHERE year = 2012\n"
     ]
    }
   ],
   "source": [
    "label = 'Light rain or snow'\n",
    "one_line = \"SELECT * FROM daily_ridership WHERE year = 2012\"\n",
    "many_lines = \"\"\"\n",
    "    SELECT year, month\n",
    "    FROM daily_ridership\n",
    "    WHERE weather = 'Mist or cloudy'\n",
    "\"\"\"\n",
    "print(label)\n",
    "print(one_line)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c012",
   "metadata": {},
   "source": [
    "## Tuples, lists and indexing\n",
    "\n",
    "A table in a database is rows under fixed columns. A query result arrives in Python as a list of **[tuples](https://dvirross.com/courses/intro-data-science/glossary#tuple)**: 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](https://dvirross.com/courses/intro-data-science/glossary#list)** is written with square brackets and holds many items, here many rows. An **[index](https://dvirross.com/courses/intro-data-science/glossary#index)** is the position of an item in square brackets, and counting starts at 0, so `row[0]` is the first value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c013",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.000842Z",
     "iopub.status.busy": "2026-11-01T21:23:46.000547Z",
     "iopub.status.idle": "2026-11-01T21:23:46.011287Z",
     "shell.execute_reply": "2026-11-01T21:23:46.006363Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2011 985\n",
      "(2011, 1, 801)\n",
      "801\n"
     ]
    }
   ],
   "source": [
    "row = (2011, 1, 985)\n",
    "rows = [(2011, 1, 985), (2011, 1, 801), (2011, 1, 1349)]\n",
    "print(row[0], row[2])\n",
    "print(rows[1])\n",
    "print(rows[1][2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c014",
   "metadata": {},
   "source": [
    "The last line takes the second row of the list and then the third value of that row. See [tuples and lists](https://dvirross.com/courses/intro-data-science/python-values-and-collections#tuples-and-lists-several-values-in-order) for the full lesson.\n",
    "\n",
    "## Connect, cursor, execute, fetch\n",
    "\n",
    "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.\n",
    "\n",
    "**Connect.** The function `sqlite3.connect` opens the database file whose name you give it and returns a **[connection](https://dvirross.com/courses/intro-data-science/glossary#connection)**, an object that stands for the open database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c015",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.013642Z",
     "iopub.status.busy": "2026-11-01T21:23:46.013418Z",
     "iopub.status.idle": "2026-11-01T21:23:46.022466Z",
     "shell.execute_reply": "2026-11-01T21:23:46.016311Z"
    }
   },
   "outputs": [],
   "source": [
    "import sqlite3\n",
    "\n",
    "conn = sqlite3.connect('sql-practice.sqlite')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c016",
   "metadata": {},
   "source": [
    "**Create a cursor.** The method `cursor` of the connection creates a **[cursor](https://dvirross.com/courses/intro-data-science/glossary#cursor)**, an object that sends SQL and holds the answer until you take it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c017",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.024916Z",
     "iopub.status.busy": "2026-11-01T21:23:46.024693Z",
     "iopub.status.idle": "2026-11-01T21:23:46.028996Z",
     "shell.execute_reply": "2026-11-01T21:23:46.027250Z"
    }
   },
   "outputs": [],
   "source": [
    "c = conn.cursor()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c018",
   "metadata": {},
   "source": [
    "**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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c019",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.033524Z",
     "iopub.status.busy": "2026-11-01T21:23:46.033294Z",
     "iopub.status.idle": "2026-11-01T21:23:46.049571Z",
     "shell.execute_reply": "2026-11-01T21:23:46.046983Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<sqlite3.Cursor object at 0x7f0000000000>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c.execute(\"\"\"\n",
    "    SELECT year, month, weather, total_rides\n",
    "    FROM daily_ridership\n",
    "    LIMIT 2\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c020",
   "metadata": {},
   "source": [
    "**Fetch the results.** The method `fetchall` takes all the rows of the answer, as a list of tuples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c021",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.053081Z",
     "iopub.status.busy": "2026-11-01T21:23:46.052553Z",
     "iopub.status.idle": "2026-11-01T21:23:46.057499Z",
     "shell.execute_reply": "2026-11-01T21:23:46.056249Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(2011, 1, 'Mist or cloudy', 985), (2011, 1, 'Mist or cloudy', 801)]\n"
     ]
    }
   ],
   "source": [
    "results = c.fetchall()\n",
    "print(results)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c022",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c023",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.060000Z",
     "iopub.status.busy": "2026-11-01T21:23:46.059764Z",
     "iopub.status.idle": "2026-11-01T21:23:46.067966Z",
     "shell.execute_reply": "2026-11-01T21:23:46.064437Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(2011, 1, 985), (2011, 1, 801), (2011, 1, 1349)]\n",
      "(1, 985)\n",
      "Month: 1\n",
      "Rides: 985\n"
     ]
    }
   ],
   "source": [
    "three = c.execute(\n",
    "    \"SELECT year, month, total_rides FROM daily_ridership\"\n",
    ").fetchmany(3)\n",
    "print(three)\n",
    "row = c.execute(\n",
    "    \"SELECT month, total_rides FROM daily_ridership LIMIT 1\"\n",
    ").fetchone()\n",
    "print(row)\n",
    "print('Month:', row[0])\n",
    "print('Rides:', row[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c024",
   "metadata": {},
   "source": [
    "## Summary functions in a query\n",
    "\n",
    "The summary functions of the [SQL guide](https://dvirross.com/courses/intro-data-science/sql-in-db-browser#summarize-values) 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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c025",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.070499Z",
     "iopub.status.busy": "2026-11-01T21:23:46.070283Z",
     "iopub.status.idle": "2026-11-01T21:23:46.075018Z",
     "shell.execute_reply": "2026-11-01T21:23:46.073656Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rides: 386839 Days: 115\n"
     ]
    }
   ],
   "source": [
    "result = c.execute(\"\"\"\n",
    "    SELECT SUM(total_rides), COUNT(*)\n",
    "    FROM daily_ridership\n",
    "    WHERE year = 2011 AND working_day = 0\n",
    "\"\"\").fetchone()\n",
    "print('Rides:', result[0], 'Days:', result[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c026",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### Task 1 (worked example): days and labels of 2012\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c027",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.078325Z",
     "iopub.status.busy": "2026-11-01T21:23:46.077888Z",
     "iopub.status.idle": "2026-11-01T21:23:46.084589Z",
     "shell.execute_reply": "2026-11-01T21:23:46.082707Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Days: 366 Different weather labels: 3\n"
     ]
    }
   ],
   "source": [
    "result = c.execute(\"\"\"\n",
    "    SELECT COUNT(weather), COUNT(DISTINCT weather)\n",
    "    FROM daily_ridership\n",
    "    WHERE year = 2012\n",
    "\"\"\").fetchone()\n",
    "print('Days:', result[0], 'Different weather labels:', result[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c028",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "### Task 2 (worked example): labels that contain cloudy\n",
    "\n",
    "How many different weather labels contain the text `cloudy`? Then list those labels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c029",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.087464Z",
     "iopub.status.busy": "2026-11-01T21:23:46.087145Z",
     "iopub.status.idle": "2026-11-01T21:23:46.097034Z",
     "shell.execute_reply": "2026-11-01T21:23:46.091933Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Labels that contain cloudy: 2\n",
      "[('Mist or cloudy',), ('Clear or partly cloudy',)]\n"
     ]
    }
   ],
   "source": [
    "result = c.execute(\"\"\"\n",
    "    SELECT COUNT(DISTINCT weather)\n",
    "    FROM daily_ridership\n",
    "    WHERE weather LIKE '%cloudy%'\n",
    "\"\"\").fetchone()\n",
    "print('Labels that contain cloudy:', result[0])\n",
    "labels = c.execute(\"\"\"\n",
    "    SELECT DISTINCT weather\n",
    "    FROM daily_ridership\n",
    "    WHERE weather LIKE '%cloudy%'\n",
    "    LIMIT 10\n",
    "\"\"\").fetchall()\n",
    "print(labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c030",
   "metadata": {},
   "source": [
    "The count is `result[0]`, and the list holds a tuple with one value for each label.\n",
    "\n",
    "### Task 3: rides on working days\n",
    "\n",
    "**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`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c031",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.099753Z",
     "iopub.status.busy": "2026-11-01T21:23:46.099511Z",
     "iopub.status.idle": "2026-11-01T21:23:46.104159Z",
     "shell.execute_reply": "2026-11-01T21:23:46.102224Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c032",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "Total rides: <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c033",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.106427Z",
     "iopub.status.busy": "2026-11-01T21:23:46.106154Z",
     "iopub.status.idle": "2026-11-01T21:23:46.110697Z",
     "shell.execute_reply": "2026-11-01T21:23:46.109856Z"
    }
   },
   "outputs": [],
   "source": [
    "check(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c034",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> 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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c035",
   "metadata": {},
   "source": [
    "### Groups and the largest total\n",
    "\n",
    "`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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c036",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.113377Z",
     "iopub.status.busy": "2026-11-01T21:23:46.113110Z",
     "iopub.status.idle": "2026-11-01T21:23:46.118404Z",
     "shell.execute_reply": "2026-11-01T21:23:46.116938Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Season: Summer Rides: 419650\n"
     ]
    }
   ],
   "source": [
    "best = c.execute(\"\"\"\n",
    "    SELECT season, SUM(total_rides)\n",
    "    FROM daily_ridership\n",
    "    WHERE year = 2011\n",
    "    GROUP BY season\n",
    "    ORDER BY SUM(total_rides) DESC\n",
    "    LIMIT 1\n",
    "\"\"\").fetchone()\n",
    "print('Season:', best[0], 'Rides:', best[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c037",
   "metadata": {},
   "source": [
    "### Task 4: the busiest month\n",
    "\n",
    "**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`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c038",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.120601Z",
     "iopub.status.busy": "2026-11-01T21:23:46.120348Z",
     "iopub.status.idle": "2026-11-01T21:23:46.124661Z",
     "shell.execute_reply": "2026-11-01T21:23:46.122961Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "Busiest month: (<number>, <number>)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c040",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.126823Z",
     "iopub.status.busy": "2026-11-01T21:23:46.126589Z",
     "iopub.status.idle": "2026-11-01T21:23:46.131617Z",
     "shell.execute_reply": "2026-11-01T21:23:46.130325Z"
    }
   },
   "outputs": [],
   "source": [
    "check(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c041",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> 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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c042",
   "metadata": {},
   "source": [
    "## Values from Python variables: parameters\n",
    "\n",
    "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](https://dvirross.com/courses/intro-data-science/glossary#unpacking))."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c043",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.134171Z",
     "iopub.status.busy": "2026-11-01T21:23:46.133946Z",
     "iopub.status.idle": "2026-11-01T21:23:46.140755Z",
     "shell.execute_reply": "2026-11-01T21:23:46.139077Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rides: 102244\n"
     ]
    }
   ],
   "source": [
    "weather, year, working_day = 'Mist or cloudy', 2011, 0\n",
    "query = \"\"\"\n",
    "    SELECT SUM(total_rides)\n",
    "    FROM daily_ridership\n",
    "    WHERE weather = ? AND year = ? AND working_day = ?\n",
    "\"\"\"\n",
    "values = (weather, year, working_day)\n",
    "result = c.execute(query, values).fetchone()\n",
    "print('Rides:', result[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c044",
   "metadata": {},
   "source": [
    "**Why not put the values into the text with an f-string?**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c045",
   "metadata": {},
   "source": [
    "An [f-string](https://dvirross.com/courses/intro-data-science/glossary#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](https://dvirross.com/courses/intro-data-science/glossary#sql-injection). With `?` the value is only data, and the same text matches no season:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c046",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.143259Z",
     "iopub.status.busy": "2026-11-01T21:23:46.143001Z",
     "iopub.status.idle": "2026-11-01T21:23:46.148633Z",
     "shell.execute_reply": "2026-11-01T21:23:46.147404Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(731,)\n",
      "(0,)\n"
     ]
    }
   ],
   "source": [
    "season = \"Summer' OR '1'='1\"\n",
    "pasted = f\"\"\"\n",
    "    SELECT COUNT(*) FROM daily_ridership\n",
    "    WHERE season = '{season}'\n",
    "\"\"\"\n",
    "print(c.execute(pasted).fetchone())\n",
    "safe = \"\"\"\n",
    "    SELECT COUNT(*) FROM daily_ridership\n",
    "    WHERE season = ?\n",
    "\"\"\"\n",
    "print(c.execute(safe, (season,)).fetchone())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c047",
   "metadata": {},
   "source": [
    "[SQL from Python](https://dvirross.com/courses/intro-data-science/sql-from-python#passing-values-parameters) shows this in full."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c048",
   "metadata": {},
   "source": [
    "### Task 5: values from variables\n",
    "\n",
    "**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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c049",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.151251Z",
     "iopub.status.busy": "2026-11-01T21:23:46.150993Z",
     "iopub.status.idle": "2026-11-01T21:23:46.154818Z",
     "shell.execute_reply": "2026-11-01T21:23:46.153418Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c050",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "Total rides: <number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c051",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.156892Z",
     "iopub.status.busy": "2026-11-01T21:23:46.156682Z",
     "iopub.status.idle": "2026-11-01T21:23:46.161011Z",
     "shell.execute_reply": "2026-11-01T21:23:46.159670Z"
    }
   },
   "outputs": [],
   "source": [
    "check(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c052",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> 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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c053",
   "metadata": {},
   "source": [
    "## Functions that query\n",
    "\n",
    "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](https://dvirross.com/courses/intro-data-science/python-loops-and-functions#functions-a-name-for-a-piece-of-work) for the full lesson.\n",
    "\n",
    "A summary query over no rows returns a missing value: `SUM` of nothing is `NULL`, and Python shows `NULL` as **[`None`](https://dvirross.com/courses/intro-data-science/glossary#none)**, the value that means no value. A function that returns a number should return 0 in that case. A **[conditional expression](https://dvirross.com/courses/intro-data-science/glossary#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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c054",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.163044Z",
     "iopub.status.busy": "2026-11-01T21:23:46.162831Z",
     "iopub.status.idle": "2026-11-01T21:23:46.169953Z",
     "shell.execute_reply": "2026-11-01T21:23:46.168487Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(None,)\n",
      "Summer 2011: 419650\n",
      "Summer 2013: 0\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    c.execute(\"\"\"\n",
    "        SELECT SUM(total_rides)\n",
    "        FROM daily_ridership\n",
    "        WHERE season = 'Summer' AND year = 2013\n",
    "    \"\"\").fetchone()\n",
    ")\n",
    "\n",
    "def get_season_rides(season, year):\n",
    "    query = \"\"\"\n",
    "        SELECT SUM(total_rides)\n",
    "        FROM daily_ridership\n",
    "        WHERE season = ? AND year = ?\n",
    "    \"\"\"\n",
    "    row = c.execute(query, (season, year)).fetchone()\n",
    "    return row[0] if row[0] is not None else 0\n",
    "\n",
    "print('Summer 2011:', get_season_rides('Summer', 2011))\n",
    "print('Summer 2013:', get_season_rides('Summer', 2013))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c055",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### Task 6: a function that queries\n",
    "\n",
    "**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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "c056",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.172122Z",
     "iopub.status.busy": "2026-11-01T21:23:46.171903Z",
     "iopub.status.idle": "2026-11-01T21:23:46.175793Z",
     "shell.execute_reply": "2026-11-01T21:23:46.174441Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c057",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "July 2012: <number>\n",
    "January 2013: 0\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "c058",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.177863Z",
     "iopub.status.busy": "2026-11-01T21:23:46.177650Z",
     "iopub.status.idle": "2026-11-01T21:23:46.182487Z",
     "shell.execute_reply": "2026-11-01T21:23:46.181008Z"
    }
   },
   "outputs": [],
   "source": [
    "check(6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> 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`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c060",
   "metadata": {},
   "source": [
    "## A list from query results, and `max` with a key\n",
    "\n",
    "A **[list comprehension](https://dvirross.com/courses/intro-data-science/glossary#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](https://dvirross.com/courses/intro-data-science/glossary#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.\n",
    "\n",
    "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "c061",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.184950Z",
     "iopub.status.busy": "2026-11-01T21:23:46.184724Z",
     "iopub.status.idle": "2026-11-01T21:23:46.190613Z",
     "shell.execute_reply": "2026-11-01T21:23:46.189154Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('Winter', 150000), ('Spring', 347316), ('Summer', 419650), ('Fall', 326137)]\n",
      "('Summer', 419650)\n"
     ]
    }
   ],
   "source": [
    "season_totals = [\n",
    "    (season[0], get_season_rides(season[0], 2011))\n",
    "    for season in c.execute(\n",
    "        \"SELECT DISTINCT season FROM daily_ridership\"\n",
    "    ).fetchall()\n",
    "]\n",
    "print(season_totals)\n",
    "print(max(season_totals, key=lambda pair: pair[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c062",
   "metadata": {},
   "source": [
    "### Task 7: a list and `max`\n",
    "\n",
    "**Your turn.** Write a function with this name and these parameters:\n",
    "\n",
    "```text\n",
    "get_rides_by_weather_year_month(weather, year, month)\n",
    "```\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "c063",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.218720Z",
     "iopub.status.busy": "2026-11-01T21:23:46.218436Z",
     "iopub.status.idle": "2026-11-01T21:23:46.222934Z",
     "shell.execute_reply": "2026-11-01T21:23:46.221407Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c064",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "(<number>, <number>)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "c065",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.225599Z",
     "iopub.status.busy": "2026-11-01T21:23:46.225351Z",
     "iopub.status.idle": "2026-11-01T21:23:46.230674Z",
     "shell.execute_reply": "2026-11-01T21:23:46.229359Z"
    }
   },
   "outputs": [],
   "source": [
    "check(7)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c066",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> 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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c067",
   "metadata": {},
   "source": [
    "## Questions to talk about\n",
    "\n",
    "- Which part of the code changes when the weather, the year or the month come from variables?\n",
    "- What could go wrong if a value were pasted into the SQL text with an f-string?\n",
    "- Where did a query result become an ordinary Python value in your code?\n",
    "\n",
    "## Closing the connection\n",
    "\n",
    "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](https://dvirross.com/courses/intro-data-science/sql-from-python#changing-data-and-saving-it)); our queries only read."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c068",
   "metadata": {},
   "source": [
    "Run the cell below as the last step: it releases the database file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "c069",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T21:23:46.233170Z",
     "iopub.status.busy": "2026-11-01T21:23:46.232945Z",
     "iopub.status.idle": "2026-11-01T21:23:46.238126Z",
     "shell.execute_reply": "2026-11-01T21:23:46.235724Z"
    }
   },
   "outputs": [],
   "source": [
    "conn.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c070",
   "metadata": {},
   "source": [
    "## Keep in mind\n",
    "\n",
    "- 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.\n",
    "- The values of a row are in the order of the `SELECT`, and an index takes one of them: `row[0]`.\n",
    "- Pass values with `?` and a tuple of values, never by pasting text into the SQL.\n",
    "- A summary query over no rows gives `None`; a conditional expression, as in `get_total_rides`, turns it into 0.\n",
    "- `max` with `key=lambda pair: pair[1]` returns the tuple with the largest second value."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
