The daily bars of KO fit in a DataFrame of 6,699 rows. To ask "what was the busiest day?" you could sort it with pandas, or you could ask in SQL, right there, without starting a database server or loading anything. That is DuckDB: a database that lives inside your Python process.
The idea in plain words
Where we are. This is the first topic of the DuckDB skill. It assumes the basics from the SQL skill (select, filter, group) and uses them from Python. The next topic points DuckDB at files instead of DataFrames.
A database engine that runs as a library inside your own program rather than as a separate server. There is nothing to install, start or connect to over a network, and it can read the program's own memory.
Query a DataFrame by its name
When a SQL statement names a table that does not exist, DuckDB looks for a Python variable of that name, and if it holds a DataFrame (or an Arrow table, or a Polars frame), it reads it directly. This is called a replacement scan. Nothing is copied into the database first.
# DuckDB finds the variable called frame and queries it where it sitsframe = load_frame("KO")print(duckdb.sql("SELECT count(*) AS days, min(date) AS first_day, max(date) AS last_day FROM frame"))1
┌───────┬────────────┬────────────┐ │ days │ first_day │ last_day │ │ int64 │ date │ date │ ├───────┼────────────┼────────────┤ │ 6699 │ 2000-01-03 │ 2026-08-21 │ └───────┴────────────┴────────────┘
- 1
frameis a Python variable, not a table anyone created.
A connection, tables, and two ways to run
duckdb.connect() opens a database of its own, in memory unless you give it a file name. A table made there belongs to that connection. Two calls run SQL. con.sql(query) returns a lazy relation that you can inspect (.columns) and finish with .fetchall(), .df() or .to_arrow_table(). con.execute(query) runs at once and leaves a cursor on the connection, which you must read to the end with fetchall() before you do anything else on that connection.
# Copy the DataFrame into a table of this connection, then ask for a lazy relationprint(frame_to_table(con, "ko", frame))rel = con.sql("SELECT date, close FROM ko ORDER BY date DESC LIMIT 3")print(rel.columns)print(rel.fetchall())
6699 ['date', 'close'] [(datetime.date(2026, 8, 21), 91.1), (datetime.date(2026, 8, 20), 90.5), (datetime.date(2026, 8, 19), 90.35)]
# The same result in four shapesfor how in ("tuples", "dicts", "frame", "arrow"): result = rows_as(con, "SELECT date, close FROM ko ORDER BY date DESC LIMIT 2", how) print(how, "->", type(result).__name__)print(describe_table(con, "ko"))
tuples -> list
dicts -> list
frame -> DataFrame
arrow -> Table
[('date', 'DATE'), ('open', 'DOUBLE'), ('high', 'DOUBLE'), ('low', 'DOUBLE'), ('close', 'DOUBLE'), ('volume', 'BIGINT')]# An execute() cursor left unread blocks the next call on the same connectioncursor = con.execute("SELECT date FROM ko")cursor.fetchone()try: con.register("x", frame)except Exception as error: print(type(error).__name__)cursor.fetchall()con.register("x", frame)print("registered after reading the cursor to the end")
ResourceInUseException registered after reading the cursor to the end
fetchone() reads one row and leaves the cursor open, so the next call on that connection raises an error that mentions an unfinished result. Use fetchall(), or use con.sql(...), which does not hold the connection. Reading one value with fetchall()[0][0] is the safe habit.
What the tasks ask
- 1`frame_top_volume`A SQL query on the variable
frame, with no pandas sorting. - 2`frame_to_table` and `describe_table`Register the DataFrame and create a table from it, then read the table's columns back with
DESCRIBE. Table names go throughident(). - 3`rows_as`One query, four return shapes, and a clear error for anything else.
con.execute(sql).fetchone() and then con.register("x", frame) on the same connection, and the second call raises an error about an unfinished result. What fixes it?Lab · what's graded
4 tasks · 100 pts- Query a DataFrame in place:
frame_top_volume25 pts - A DataFrame becomes a table:
frame_to_table25 pts - One result, four shapes:
rows_as25 pts - Ask the database about itself:
describe_table25 pts