Python Tutorial
Python MySQL - Select From
Read rows from a table and fetch results one, some, or all at a time.
Select All Rows
Run a SELECT, then fetch the results. fetchall() returns every row as a list of tuples.
import mysql.connector
conn = mysql.connector.connect(
host="localhost", user="root", password="secret", database="mydatabase")
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers")
for row in cursor.fetchall():
print(row) # ('John', 'Highway 21'), ...Avoid SELECT * in real code — list the columns you need. It is clearer, faster, and unaffected by later schema changes.
Select Specific Columns
cursor.execute("SELECT name, address FROM customers")
for name, address in cursor.fetchall():
print(name, "-", address)fetchone and fetchmany
Fetch a single row or a batch to control memory on large results.
cursor.execute("SELECT * FROM customers")
first = cursor.fetchone() # one row (or None)
print(first)
batch = cursor.fetchmany(5) # next 5 rows as a list
print(len(batch))Results as Dictionaries
A dictionary cursor returns each row keyed by column name — easier to read and less brittle than positional tuples.
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT id, name FROM customers")
for row in cursor.fetchall():
print(row["id"], row["name"]) # access by column nameIterate Without Loading Everything
For large tables, iterate the cursor directly so rows stream in instead of loading all at once.
cursor.execute("SELECT * FROM customers")
for row in cursor: # memory-friendly iteration
print(row)Best Practices
- Select only the columns you need, not
*. - Use a dictionary cursor for readable, column-name access.
- Use
fetchmanyor cursor iteration for large result sets. - Combine with WHERE, ORDER BY, and LIMIT (next lessons) to fetch exactly the rows you want.
Try It Yourself
Exercise 1: Fetch only the name column from customers and print each.
Show solution
cursor.execute("SELECT name FROM customers")
for (name,) in cursor.fetchall():
print(name)Exercise 2: Why avoid SELECT * in production code?
Show solution
It fetches unneeded columns, is slower, and breaks silently if the schema changes. List the exact columns you need.
📘 Real-World Deep Dive
Knowing <strong>MySQL Select (MySQL)</strong> well is what turns MySQL from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of MySQL Select that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import mysql.connector
conn = mysql.connector.connect(database="shop")
cur = conn.cursor(dictionary=True)
cur.execute("SELECT id, name FROM users WHERE email LIKE %s", ("%@x",))
for row in cur.fetchall():
print(row)Expected Output
(see source)Common mistakes
- Reading with the default cursor returns tuples — switch to
DictCursorfor named access. - Strings without parameter binding produce SQL-injection holes — never use f-strings in queries.
- Connecting through a long-lived daemon pool: make sure
pool_reset_connectionis on to avoid session state leakage. - Treating MySQL Select as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Use prepared statements (
cursor.executemany) for bulk inserts. - Fetch with
cursor.fetchmany(1000)in streams instead offetchall(). - Use
pymysql's server-side cursors for very large result sets. - When working with MySQL, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.