Order Query Results

When you learned SQL, you learned how to use the ORDER BY keyword to order your results in a specific way. Similarly, Sequelize allows you to specify how you want to order the results of your query.

By the end of this reading, you will be able to:

Why Order Query Results?

Imagine you are working on a large ed-tech application used by a high school. These applications generally include a variety of user roles, such as teachers, students, and parents. They also include a variety of models and complex associations, including:

When working with such a large application with many associations among models, you need to carefully structure your database queries to make your application efficient and user-friendly. Different users require different views of the data, and sorting results effectively helps improve the user experience.

Using Sequelize to Order Query Results

Sequelize provides multiple ways to order query results efficiently.

Using the order Key

You can use the order key in the options object to specify sorting conditions.

For example, to get all of a student's submissions ordered from most recent to oldest, you can use:


const student = await Student.findByPk(5);
const submissions = await student.getSubmissions({
    order: [['createdAt', 'DESC']]
});
    

This translates to the SQL query:


SELECT 'Submissions'.* FROM 'Submissions' WHERE 'studentId' = ? ORDER BY 'createdAt' DESC;
    

Ordering by Multiple Properties

You can order results by multiple attributes by adding additional nested arrays:


const teacher = await Teacher.findByPk(2);
const assignments = await teacher.getAssignments({
    order: [ ['name', 'ASC'], ['createdAt', 'DESC'] ]
});
    

This results in:


SELECT 'Assignments'.* FROM 'Assignments' WHERE 'teacherId' = ? ORDER BY 'name' ASC, 'createdAt' DESC;
    

Ordering by Association

Sometimes, you may need to order results based on associated models. For instance, you can order a teacher's assignments by course title first, then by assignment name:


const teacher = await Teacher.findByPk(2);
const assignments = await teacher.getAssignments({
    include: { model: Course },
    order: [ [Course, 'title'], ['name', 'ASC'] ]
});
    

What You Learned

Sequelize provides several ways to order query results efficiently. Properly ordering results is critical in large applications, as it enhances user experience and reduces unnecessary computations on the frontend.

For more information, check out the Sequelize documentation on ordering and the order key in the findAll method.