order_by() Query in Codeigniter

The order_by() method is used to sort the result-set in ascending or descending order. The first parameter contains the name of the column you would like to order by. The second parameter lets you set the direction of the result. Options are ASC, DESC AND RANDOM.

$this->db->order_by('id', 'DESC');
// Produces: ORDER BY `id` DESC

You can also pass your own string in the first parameter

$this->db->order_by('id DESC, name ASC');
// Produces: ORDER BY `id` DESC, `name` ASC

Or multiple function calls can be made if you need multiple fields.

$this->db->order_by('id', 'DESC');
$this->db->order_by('name', 'ASC');
// Produces: ORDER BY `id` DESC, `name` ASC

If you choose the RANDOM direction option.

$this->db->order_by('id', 'RANDOM');
// Produces: ORDER BY RAND()

$this->db->order_by(42, 'RANDOM');
// Produces: ORDER BY RAND(42)

Leave a Reply

Your email address will not be published. Required fields are marked *