Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Databases

Learning goals

Reading

Reading PDF

Database

Our app speaks to a database management system (DBMS) using SQL to store data on a database. We will use SQLite, which is one of the most popular DBMS[1].

SQLite installation

MacOS
Windows

MacOS has probably SQLite installed, however I recommend updating to the latest version:

brew install sqlite

Connection and operation

(294, 'pen')
(295, 'book')

[2] [3]

SQLite viewer

Useful for viewing database contents.[4]

codium --install-extension qwtel.sqlite-viewer
orders.db opened with the editor extension. We see the two rows we inserted.

orders.db opened with the editor extension. We see the two rows we inserted.

Working on a temporary database

con = sqlite3.connect(":memory:") 

Creates a temporary database (instead of a permanent file). Useful for exercises, and will be used for the following cells.

I am not going to use the example database from Notebook-code again and use the temporary one instead.

Creating a table

CREATE TABLE orders(id, item)

We should also declare datatypes of the columns, because:

When we provide datatypes, then SQLite tries to convert our input to the particular column’s datatype.[5]

We create the table using database schema.

Datatypes

https://docs.python.org/3/library/sqlite3.html#sqlite3-types

Python

SQLite

None

NULL

int

INTEGER

float

REAL

str

TEXT

bytes

BLOB

Creating a table with datatypes

CREATE TABLE orders(id INTEGER, item TEXT)
# After First insert
(294, 'pen')
(295, 'book')

# After second insert
(294, 'pen')
(295, 'book')
(296, 'orange')
(297, 'apple')

Even we provided a string, SQLite converted it to an integer

# After first insert
(294, 'pen')
(295, 'book')

# After second insert
(294, 'pen')
(295, 'book')
('296', 'orange')
('297', 'apple')

Without explicit datatype, string gets stored as is.

Constraint: PRIMARY KEY

We usually want to address the data with a unique identifier, like F13 on a spreadsheet. Therefore we should pick a primary key upon creating a new table. This helps us later to relate to our data from other tables.[6]

CREATE TABLE orders(id INTEGER PRIMARY KEY, item TEXT)

An integer primary key has an implicit UNIQUE constraint and NOT NULL constraint.[7]

Other constraints

Details: https://sqlite.org/lang_createtable.html

Connection for the following cells

I will use this connection for the rest of the cells:

Long SQL statements

Python’s triple-quoted strings are useful for readability:

Other table statements

CRUD operations

Getting affected row count

Insert example data:

# After insert
(296, 'orange')
(297, 'apple')

Delete and get affected row count:

1

Useful to know whether our statement changed anything.

Composite keys

Sometimes we cannot find a primary key based on a single column. Imagine you have a database of residents in a single-person apartment building:

Table 2:Table residents

building

floor

room

name

R

1

9

“Donald”

R

2

19

“Cindy”

A unique key would be the composite of all the three columns that represent a unique apartment.

CREATE TABLE residents(
  building TEXT NOT NULL,
  floor INTEGER NOT NULL,
  room INTEGER NOT NULL,
  name TEXT, -- a room can be empty
  PRIMARY KEY (building, floor, room)
)

Composite keys can lead to long SQL statements in table relations.[9] For simplicity, I will try to avoid them in next examples.

Relational data

SQLite is a relational database. It allows us to join information to other information. For example, we can define visitors in relation to residents:

```{list-table} Table employees :header-rows: 1

    • id

    • site

    • floor

    • desk

    • name

    • 1

    • HQ

    • 3

    • 12

    • Bernd Lopez

    • 2

    • Riverside

    • 1

    • 4

    • Dilek Chen

    • 3

    • HQ

    • 2

    • 7

    • Priya Patel

```{list-table} Table appointments :header-rows: 1

    • id

    • time

    • client

    • employee_id

    • 1

    • 2026-07-30 16:45:43

    • Novo

    • 1

    • 2

    • 2026-07-29 09:15:00

    • Volkswagen

    • 2

    • 3

    • 2026-07-30 11:30:00

    • Siemens

    • 3

The table schemas can be created as follows:

employee_id is a foreign key.

appointments table does not contain the names:

(1, '2026-07-30 16:45:43', 'Novo', 1)
(2, '2026-07-29 09:15:00', 'Volkswagen', 2)
(3, '2026-07-30 11:30:00', 'Siemens', 3)

If we relate to employees by joining two tables, we can append the necessary info to each row

(1, '2026-07-30 16:45:43', 'Novo', 1, 1, 'HQ', 3, 12, 'Bernd Lopez')
(2, '2026-07-29 09:15:00', 'Volkswagen', 2, 2, 'Riverside', 1, 4, 'Dilek Chen')
(3, '2026-07-30 11:30:00', 'Siemens', 3, 3, 'HQ', 2, 7, 'Priya Patel')

Foreign key integrity enforcement

If we add a row with a foreign key that does not exist, then SQLite does not warn us[10]:

In the following cell employee id 99 does not exist:

Activating the following option is recommended:

So that SQLite warns us:

---------------------------------------------------------------------------
IntegrityError                            Traceback (most recent call last)
Cell In[14], line 1
----> 1 con.execute(
      2     """
      3 INSERT INTO appointments
      4 VALUES (?, ?, ?, ?)

IntegrityError: FOREIGN KEY constraint failed

Entity relationship diagram

This entity relationship diagram uses Crow’s foot notation:

  • dash and dash on employee’s side means minimum one, maximum one.

  • Ring and crow’s foot means minimum zero, maximum many.

=> An employee can have 0 or many appointments. An appointment is related to only one employee.

Python in Excel

Data in some companies are kept on spreadsheets and so they become like databases. Excel supports running Python code in Excel.

Requirements

Python in Excel requires internet access and Excel license. As a student you have a license through our university.

You have to use https://excel.cloud.microsoft, because Python in Excel does not seem to be active on the desktop version in our university.

Internet access is required, because Excel runs in the cloud.

Tutorial

https://support.microsoft.com/en-us/excel/python/introduction-to-python-in-excel

Get started

Enter into a cell:

=py(

It will be converted to a Python cell. Then you can write your code, e.g.,

x = xl("B1")
y = xl("C1")
x + y

Then press CtrlEnter.

Two ways of using the cell

Two types of return values

  1. Python object => for continuing working with Python

  2. Excel value => for continuing working with native Excel features

Two types of output of a Python cell.

Figure 4:Two types of output of a Python cell.

Card icon

Provides information about data.

Calculation order

Python cells can be everywhere in the worksheet. The Python cells in first rows are processed first and inside a row, first columns are processed first[11].

Recalculation

Errors

DataFrame

a fundamental datatype for two-dimensional data

  • part of pandas library

  • similar to an Excel table

Can be converted to Excel values using output type.

Import data

Two sources

  1. Internal: Worksheet

  2. External: Power Query

External data

Using Data->Get Data->OData then the following example dataset

https://services.odata.org/northwind/northwind.svc/

Working with data

df = xl("Alphabetical_list_of_products[#All]", headers=True)
df

[12]

Row with the lowest units in stock:

df.loc[df["UnitsInStock"].idxmin()]

Plotting:

plt.scatter(df["ProductID"], df["UnitsInStock"])

My experience with Python in Excel

In conclusion, I did not like that there is no possibility to run Python cells locally. I had many synchronization issues with the cloud. For example

I would probably rather work on an editor first and then try to integrate my analysis into the Excel sheet if required. Therefore it is still important to know that Python is available in Excel.

Footnotes
  1. According to Stackoverflow technology data 2026 https://survey.stackoverflow.co/2026/technology/data/databases

  2. For simplicity, I used autocommit, which executes the SQL prompt and saves the changes immediately on the database. In more complex projects, many SQL prompts are collected in a transaction and the changes are saved on the file in a batch. This is called commit. This can be achieved with:

    con.commit()

    Or with a context manager:

    with con:
      con.executemany("INSERT INTO orders VALUES(?, ?)", data)
    # The context manager commits changes at the end of the context. (same as `con.commit()`)
    # If we don't commit, then the changes will not be stored in the database and therefore will
    # not be visible for other clients.
  3. Many tutorials use a cursor made from the connection object: cur = con.cursor(), which I did not use explicitly for the first example. An implicit cursor is used in con.execute in the for loop, for example.

  4. There is also a web version of the extension: https://beta.sqliteviewer.app/. SQLite has also a native browser called sqlitebrowser, which is typically included in the installation package.

  5. SQLite uses flexible typing. So a TEXT can still end up in an INTEGER column after an INSERT.

  6. Actually SQLite creates a hidden column called RowID, but we should not use it. Excerpt from https://sqlite.org/rowidtable.html:

    If the rowid is not aliased by INTEGER PRIMARY KEY then it is not persistent and might change ...

  7. According to PRIMARY KEY docs, due to a bug, a primary key is not always unique even expected by the SQL standard.

  8. ... when crafting SQL statements through an another source, e.g., Python.

  9. Called row-major order. See row- and column-major order

  10. If used like this:

    df = xl("Alphabetical_list_of_products")

    Then the headers are not available.