Ask a precise question.
Filter, order, and limit rows with a predictable query contract.
01 The idea
A SELECT query should describe which columns you need and which records qualify. WHERE filters rows; ORDER BY chooses their sequence; LIMIT caps the result. Without ORDER BY, row order is not a reliable contract. Include a unique tie-breaker when reproducibility matters, especially for pagination or reporting.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
from lab_support import mysql_lab
with mysql_lab() as (connection, cursor):
cursor.execute("SELECT id, name, minutes FROM lab_tasks WHERE done = %s AND minutes >= %s ORDER BY minutes DESC, id ASC LIMIT %s", (False, 20, 2))
for row in cursor.fetchall():
print(row["name"], row["minutes"])Build 40 Review 30
03 Under the hood
- 1
The query returns only three named columns, rather than SELECT * coupling the caller to every current column.
- 2
Both filter values and the limit are bound. The fixed ORDER BY uses id as a tie-breaker after duration.
- 3
For large results, choose a streaming/unbuffered cursor strategy and consume results before the next query. OFFSET pagination can become costly and unstable under concurrent changes; keyset pagination is often a better fit.
04 Your turn, builder
Find the two shortest unfinished tasks, with id as a tie-breaker.
Reveal one possible solution +
from lab_support import mysql_lab
with mysql_lab() as (connection, cursor):
cursor.execute("SELECT name, minutes FROM lab_tasks WHERE done = %s ORDER BY minutes ASC, id ASC LIMIT %s", (False, 2))
for row in cursor.fetchall():
print(row["name"], row["minutes"])05 Check your signal
What guarantees a defined result order?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.