1. Learn
  2. /
  3. Courses
  4. /
  5. Introduction to Databases in Python

Exercise

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.

Instructions

100 XP
  • Import desc from the sqlalchemy module.
  • Select all records of the state column from the census table.
  • Append an .order_by() to sort the result output by the state column in descending order. Save the result as rev_stmt.
  • Execute rev_stmt using connection.execute() and fetch all the results with .fetchall(). Save them as rev_results.
  • Print the first 10 rows of rev_results.