Ordering criteria
Learn how to order results
This version of the library is no longer maintained. Please consider upgrading to the latest release
Adding an ordering criterion is done by using the orderBy
method.
$result = $db->from('users')
->orderBy('name')
->select()
->all();
SELECT * FROM `users` ORDER BY `name` ASC
Changing an ordering criterion is done by passing desc
as the second argument to the orderBy
method.
$result = $db->from('users')
->orderBy('name', 'desc')
->select()
->all();
SELECT * FROM `users` ORDER BY `name` DESC
You can provide multiple columns as an ordering criterion, by passing to the orderBy
method
an array containing all column names.
$result = $db->from('users')
->orderBy(['name', 'age'])
->select()
->all();
SELECT * FROM `users` ORDER BY `name`, `age` ASC
Adding multiple ordering criteria to the same query is done by calling the orderBy
method as many times as you need.
$result = $db->from('users')
->orderBy('name')
->orderBy('age', 'desc')
->select()
->all();
SELECT * FROM `users` ORDER BY `name` ASC, `age` DESC
Ordering NULL values
You can specify how NULL
values should be ordered by passing nulls first
or
nulls last
as the third argument to the orderBy
method.
$result = $db->from('users')
->orderBy('name')
->orderBy('age', 'desc', 'nulls first')
->select()
->all();
SELECT * FROM `users` ORDER BY `name` ASC, `age` DESC NULLS FIRST