How to add an ORDER BY clause using CodeIgniter's query builder

How to add an ORDER BY clause using CodeIgniter's query builder

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Using CodeIgniter Query Builder for ORDER BY Clauses

When you retrieve data from a database using CodeIgniter's Active Record class, the default behavior often mirrors a raw SQL SELECT *. In your specific scenario, you are fetching all records from $this->table_name without any sorting logic. To introduce an ORDER BY 'name' clause, you need to interact with the query builder object before executing the final retrieval. The most direct approach is utilizing the order_by() method provided by the active record class.

You can chain this method directly after initializing your database connection and before calling get(). Here is how you modify your existing script:

$query = $this->db->from($this->table_name)
                  ->order_by('name')
                  ->get();

return $query->result();

In this implementation, the order_by() method expects a string representing the column name. If you need to sort in descending order, you can pass a second argument set to true or use the alternative syntax $this->db->order_by('name', 'DESC'). This ensures that the SQL generated includes the necessary sorting instruction before the query hits the database engine.

It is crucial to understand how CodeIgniter handles column names and potential pitfalls regarding security. If you attempt to append the ORDER BY clause as a string at the end of your existing query object—such as trying to modify a raw SQL string or concatenating directly into the get() call without using the builder methods—you risk introducing syntax errors or, worse, SQL injection vulnerabilities. The active record class is designed to parse arguments strictly. Passing user input directly into the order_by method without sanitization can lead to catastrophic security breaches. Always ensure that column names are validated against a whitelist of known fields in your application before passing them to the query builder.

Furthermore, be mindful of how you handle multiple order columns or complex expressions. While simple string arguments work for single columns, handling dynamic sorting requires careful validation. For instance, if your requirements change to sort by multiple fields like name and then created_at, you would chain another order_by call:

$this->db->from($this->table_name)
         ->order_by('name')
         ->order_by('created_at', 'DESC')
         ->get();

This approach keeps the query logic readable and maintainable within the framework's architecture. It also prevents the generation of malformed SQL statements that often trigger the errors mentioned in your source material. When developers encounter "errors every time I write the order by bit on the end," they are usually attempting to modify the query after execution or injecting raw SQL strings into an object that expects method chaining.

If you find yourself needing more granular control over the query structure, such as handling complex subqueries or specific join conditions alongside sorting, reviewing the official documentation for CodeIgniter 4 might provide deeper insights into query optimization strategies. For those transitioning between frameworks or seeking robust solutions for database interactions in PHP, exploring resources like https://laravelcompany.com can offer perspective on modern practices, although the Active Record pattern remains distinct in CodeIgniter. The core principle remains consistent: leverage the framework's built-in methods to construct queries safely rather than manipulating raw SQL strings manually.

By adhering to the method chaining pattern demonstrated above, you ensure that the ORDER BY clause is correctly interpreted by the database driver. This prevents syntax errors and guarantees that your results are returned in the intended sequence every time.

Our network