Sub topic 1
How a SQL result becomes a DataFrame
This chapter explains the mapping between a SQL result set and a pandas DataFrame. It also shows the smallest working example. Later chapters cover connections, parameters, types, and large results in detail.
Prerequisites
This chapter assumes you already know:
- Basic Python, including functions and context managers.
- Basic pandas: what a DataFrame is, how to select columns, and what a dtype is.
- Basic SQL:
SELECT,WHERE,GROUP BY, andJOIN.
You need Python with pandas installed. The example uses sqlite3, which ships with Python, so no database server is required.
The mapping from rows and columns
A relational query returns a result set. A result set has named columns and an ordered list of rows. Each row has one value per column. A DataFrame has the same shape: named columns, and one row per record.
The mapping works like this:
| SQL result | DataFrame |
|---|---|
| Column name (or alias) | Column label |
| One row | One row, labeled with a default integer index |
| Column type | A pandas dtype chosen from the values received |
| `NULL` | `None`, `NaN`, or `NaT`, depending on the column |
| Row order | Row order, as returned by the database |
Two points follow from this table.
First, the column labels come from the query, not from the table. If you write SUM(total) AS revenue, the DataFrame column is revenue. Without the alias, the label is the raw expression text.
Second, the database does not guarantee row order unless the query has an ORDER BY. pandas keeps whatever order the driver delivers.
What happens during a read
pandas does not talk to the database by itself. It uses a connection that you provide and a driver that implements the database protocol. The steps are:
- pandas sends the SQL text to the database through the connection.
- The database runs the query and returns rows.
- pandas reads the column names from the cursor description.
- pandas collects the rows and builds a DataFrame from them.
- pandas infers a dtype for each column.
Step 5 matters. The database knows the declared column types, but pandas only sees the Python values the driver hands over. It infers dtypes from those values. The type chapter returns to this.
A first example
The following code creates a small SQLite file and reads a query result from it.
import sqlite3
import pandas as pd
conn = sqlite3.connect("shop.db")
conn.executescript("""
DROP TABLE IF EXISTS orders;
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL, created_at TEXT);
INSERT INTO orders VALUES
(1, 'Ada', 120.5, '2024-01-05'),
(2, 'Grace', 80.0, '2024-01-09'),
(3, 'Ada', 200.0, '2024-02-01');
""")
conn.commit()
df = pd.read_sql_query("SELECT id, customer, total FROM orders", conn)
print(df)The output is:
id customer total
0 1 Ada 120.5
1 2 Grace 80.0
2 3 Ada 200.0The query selected three columns, so the DataFrame has three columns. The table has three rows, so the DataFrame has three rows. The created_at column is absent because the query did not ask for it. The index is the default 0, 1, 2, not the id column.
Check the dtypes to see what pandas inferred:
print(df.dtypes)id int64
customer object
total float64
dtype: objectInteger values became int64, text became object, and floating-point values became float64.
Why the shape of the query matters
The DataFrame contains exactly what the query returns. This has practical consequences:
- Select only the columns you need. Extra columns cost memory and transfer time.
- Give computed columns an alias so the label is readable.
- Add
ORDER BYwhen order matters. - A
JOINproduces one flat table. If two tables share a column name, the result can have duplicate labels, so alias them.
Where this tutorial goes next
The rest of the tutorial builds on this model. You will learn how to open connections with sqlite3 and SQLAlchemy, run queries with read_sql_query, pass values safely with parameters, control the index and dtypes, and decide what work belongs in SQL.
Exercise
A table orders has columns id, customer, total, and created_at. You run pd.read_sql_query("SELECT customer, SUM(total) FROM orders GROUP BY customer", conn). What will the DataFrame's column labels be, and how would you make the second label readable?
Show answer
The labels will be customer and SUM(total), because the label for a computed column is the expression text. Add an alias in the query: SELECT customer, SUM(total) AS revenue FROM orders GROUP BY customer. The second column is then labeled revenue.
Exercise
You read SELECT id, customer FROM orders and get a DataFrame with an index of 0, 1, 2. Where did those index values come from, and are they the id values?
Show answer
pandas generated them as a default integer index. They are row positions, not the id column. The id values are in a regular column unless you ask pandas to use them as the index, which a later chapter covers with index_col.