Sequelize Query Ordering Practice

Understanding the Problem

We need to implement three Express routes that retrieve and order data from a database using Sequelize:

  1. Get all bands ordered by creation date (newest first)
  2. Get all musicians ordered alphabetically by last name then first name
  3. Get all bands with their musicians, ordered by band name and then musician names

Devising a Plan

  1. For /bands/latest:
  2. For /musicians/alphabetic:
  3. For /bands/alphabetic-musicians:

Implementing the Solution

Basic Solution


// STEP 1: Order by one attribute
app.get('/bands/latest', async (req, res, next) => {
    const bands = await Band.findAll({ 
        order: [['createdAt', 'DESC']] // Orders by creation date, newest first
    });
    res.json(bands);
});

// STEP 2: Order by multiple attributes
app.get('/musicians/alphabetic', async (req, res, next) => {
    const musicians = await Musician.findAll({ 
        order: [
            ['lastName', 'ASC'],  // Primary sort by last name
            ['firstName', 'ASC']  // Secondary sort by first name
        ]
    });
    res.json(musicians);
});

// STEP 3: Order by nested attributes
app.get('/bands/alphabetic-musicians', async (req, res, next) => {
    const bands = await Band.findAll({ 
        include: { model: Musician },
        order: [
            ['name', 'ASC'],              // Order bands by name
            [Musician, 'lastName', 'ASC'], // Order musicians by last name
            [Musician, 'firstName', 'ASC'] // Then by first name
        ]
    });
    res.json(bands);
});
    

Understanding the Code

The order Option

In Sequelize, the order option accepts an array of arrays. Each inner array specifies:

Real World Example

Think of this like sorting a library:

Further Examples

Alternative ways to write the ordering:


// Using literal SQL
order: [[sequelize.literal('createdAt DESC')]]

// Using an object notation
order: [
    {
        column: 'lastName',
        order: 'ASC'
    }
]

// Multiple nested associations
order: [
    ['name', 'ASC'],
    [{ model: Musician }, { model: Instrument }, 'type', 'ASC']
]
    

Related Concepts

Common Pitfalls