Ordering in descending order by a single column
You can also use .order_by() to sort from highest to lowest by wrapping a column
in the desc() function. Although you haven't seen this function in action, it generalizes what you have already learned.
Pass desc() (for "descending") inside an .order_by() with the name of the column you want to sort by. For instance,
stmt.order_by(desc(table.columns.column_name)) sorts column_name in descending order.
Cet exercice fait partie du cours
Introduction to Databases in Python
Instructions
- Import
descfrom thesqlalchemymodule. - Select all records of the
statecolumn from thecensustable. - Append an
.order_by()to sort the result output by thestatecolumn in descending order. Save the result asrev_stmt. - Execute
rev_stmtusingconnection.execute()and fetch all the results with.fetchall(). Save them asrev_results. - Print the first 10 rows of
rev_results.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Import desc
from ____ import ____
# Build a query to select the state column: stmt
stmt = ____
# Order stmt by state in descending order: rev_stmt
rev_stmt = stmt.order_by(____)
# Execute the query and store the results: rev_results
rev_results = ____
# Print the first 10 rev_results
print(____)