Get Started

Ordering by multiple columns

We can pass multiple arguments to the .order_by() method to order by multiple columns. In fact, we can also sort in ascending or descending order for each individual column. Each column in the .order_by() method is fully sorted from left to right. This means that the first column is completely sorted, and then within each matching group of values in the first column, it's sorted by the next column in the .order_by() method. This process is repeated until all the columns in the .order_by() are sorted.

This is a part of the course

“Introduction to Databases in Python”

View Course

Exercise instructions

  • Select all records of the state and age columns from the census table.
  • Use .order_by() to sort the output of the state column in ascending order and age in descending order. (NOTE: desc is already imported).
  • Execute stmt using the .execute() method on connection and retrieve all the results using .fetchall().
  • Print the first 20 results.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Build a query to select state and age: stmt
stmt = select([____, ____])

# Append order by to ascend by state and descend by age
stmt = stmt.order_by(____, ____)

# Execute the statement and store all the records: results
results = ____

# Print the first 20 results
print(____)

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 columnExercise 9: Ordering by multiple columns
Exercise 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