Get Started

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”

View Course

Exercise instructions

  • 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.

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(____)
Edit and Run Code

This exercise is part of the course

Introduction to Databases in Python

IntermediateSkill Level
4.4+
14 reviews

In this course, you'll learn the basics of relational databases and how to interact with them.

In this chapter, you will build on your database knowledge by writing more nuanced queries that allow you to filter, order, and count your data—all within the Pythonic framework provided by SQLAlchemy.

Exercise 1: Filtering and targeting dataExercise 2: Connecting to a PostgreSQL databaseExercise 3: Filter data selected from a Table - SimpleExercise 4: Filter data selected from a Table - ExpressionsExercise 5: Filter data selected from a Table - AdvancedExercise 6: Ordering query resultsExercise 7: Ordering by a single columnExercise 8: Ordering in descending order by a single column
Exercise 9: Ordering by multiple columnsExercise 10: Counting, summing, and grouping dataExercise 11: Counting distinct dataExercise 12: Count of records by stateExercise 13: Determining the population sum by stateExercise 14: SQLAlchemy and pandas for visualizationExercise 15: ResultsSets and pandas DataFramesExercise 16: From SQLAlchemy results to a plot

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free