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.
This is a part of the course
“Introduction to Databases in Python”
Exercise instructions
- Import
desc
from thesqlalchemy
module. - Select all records of the
state
column from thecensus
table. - Append an
.order_by()
to sort the result output by thestate
column in descending order. Save the result asrev_stmt
. - Execute
rev_stmt
usingconnection.execute()
and fetch all the results with.fetchall()
. Save them asrev_results
. - Print the first 10 rows of
rev_results
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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(____)