Skip to content

Ordering criteria

The order_by() method is used to specify the order of the results returned by a query. It allows you to sort the records based on one or more columns in ascending or descending order.

TIP

The order_by() method is part of the Select class.

Syntax

You can call order_by() with two parameters:

  • The first parameter is the column name you want to sort by.
  • The second parameter (optional) is the sort direction, either asc for ascending or desc for descending. If omitted, it defaults to asc.

You can chain multiple order_by() calls to sort by multiple columns.

Example usage

php
$query = new QueryBuilder();

$query->select()
      ->from('users')
      ->order_by('last_name');

Specifying the sort direction

php
$query = new QueryBuilder();

$query->select()
      ->from('users')
      ->order_by('last_name', 'desc');

Sorting by multiple columns

php
$query = new QueryBuilder();

$query->select()
      ->from('users')
      ->order_by('last_name', 'asc')
      ->order_by('first_name', 'desc');

Released under the MIT License.