Ordering by a single column
To sort the result output by a field, we use the .order_by() method. By default, the .order_by() method sorts from lowest to highest on the supplied column. You just have to pass in the name of the column you want sorted to .order_by().
In the video, for example, Jason used stmt.order_by(census.columns.state) to sort the result output by the state column.
Cet exercice fait partie du cours
Introduction to Databases in Python
Instructions
- Select all records of the
statecolumn from thecensustable. To do this, passcensus.columns.stateas a list toselect(). - Append an
.order_by()to sort the result output by thestatecolumn. - Execute
stmtusing the.execute()method onconnectionand retrieve all the results using.fetchall(). - Print the first 10 rows of
results.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Build a query to select the state column: stmt
stmt = ____
# Order stmt by the state column
stmt = ____
# Execute the query and store the results: results
results = ____
# Print the first 10 results
print(____[:10])