Ordering

order takes an array of items to order the query by or a sequelize method. Generally you will want to use a tuple/array of either attribute, direction or just direction to ensure proper escaping.

  1. Subtask.findAll({
  2. order: [
  3. // Will escape title and validate DESC against a list of valid direction parameters
  4. ['title', 'DESC'],
  5. // Will order by max(age)
  6. sequelize.fn('max', sequelize.col('age')),
  7. // Will order by max(age) DESC
  8. [sequelize.fn('max', sequelize.col('age')), 'DESC'],
  9. // Will order by otherfunction(`col1`, 12, 'lalala') DESC
  10. [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
  11. // Will order an associated model's created_at using the model name as the association's name.
  12. [Task, 'createdAt', 'DESC'],
  13. // Will order through an associated model's created_at using the model names as the associations' names.
  14. [Task, Project, 'createdAt', 'DESC'],
  15. // Will order by an associated model's created_at using the name of the association.
  16. ['Task', 'createdAt', 'DESC'],
  17. // Will order by a nested associated model's created_at using the names of the associations.
  18. ['Task', 'Project', 'createdAt', 'DESC'],
  19. // Will order by an associated model's created_at using an association object. (preferred method)
  20. [Subtask.associations.Task, 'createdAt', 'DESC'],
  21. // Will order by a nested associated model's created_at using association objects. (preferred method)
  22. [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],
  23. // Will order by an associated model's created_at using a simple association object.
  24. [{model: Task, as: 'Task'}, 'createdAt', 'DESC'],
  25. // Will order by a nested associated model's created_at simple association objects.
  26. [{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC']
  27. ]
  28. // Will order by max age descending
  29. order: sequelize.literal('max(age) DESC')
  30. // Will order by max age ascending assuming ascending is the default order when direction is omitted
  31. order: sequelize.fn('max', sequelize.col('age'))
  32. // Will order by age ascending assuming ascending is the default order when direction is omitted
  33. order: sequelize.col('age')
  34. // Will order randomly based on the dialect (instead of fn('RAND') or fn('RANDOM'))
  35. order: sequelize.random()
  36. })