PHP MySQL Order By
In this page:
SELECT * FROM table_name ORDER BY column; -- ascending
SELECT * FROM table_name ORDER BY column DESC; -- descending
SELECT * FROM table_name ORDER BY column1, column2;
Sorting Results Ascending
ORDER BY column sorts a query's results by that column in ascending order by default -- smallest numbers first, earliest dates first, or alphabetical order for text -- exactly as you would expect a plain, unqualified sort to behave.
Example: Sorting Results Ascending
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT)");
$db->exec("INSERT INTO users VALUES ('Carol'), ('Alice'), ('Bob')");
// Declare `$result`, set to `$db->query("SELECT * FROM users ORDER BY name")`
$result = $db->query("SELECT * FROM users ORDER BY name");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Print `$row['name'] . "\n"` to the output
echo $row['name'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Sorting Results Descending
ORDER BY column DESC reverses the sort direction -- largest values, latest dates, or reverse-alphabetical text first -- commonly used for showing the newest content first, like a blog's most recent posts or an activity feed's latest events.
Example: Sorting Results Descending
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE posts (title TEXT, created TEXT)");
$db->exec("INSERT INTO posts VALUES ('Old', '2023-01-01'), ('New', '2024-01-01')");
// Declare `$result`, set to `$db->query("SELECT * FROM posts ORDER BY created DESC")`
$result = $db->query("SELECT * FROM posts ORDER BY created DESC");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Print `$row['title'] . "\n"` to the output
echo $row['title'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Sorting by Multiple Columns
ORDER BY col1, col2 sorts primarily by col1, and only uses col2 to decide the order among rows that have the exact same col1 value -- like sorting a class roster by last name, then by first name to break ties between students sharing the same last name.
Example: Sorting by Multiple Columns
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE students (last_name TEXT, first_name TEXT)");
$db->exec("INSERT INTO students VALUES ('Smith','Bob'), ('Smith','Alice')");
// Declare `$result`, set to `$db->query("SELECT * FROM students ORDER BY last_name, first_name")`
$result = $db->query("SELECT * FROM students ORDER BY last_name, first_name");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Print `$row['first_name'] . " " . $row['last_name'] . "\n"` to the output
echo $row['first_name'] . " " . $row['last_name'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Combining ORDER BY with WHERE
ORDER BY works together with a WHERE clause, filtering the rows first and then sorting whatever remains -- WHERE always comes before ORDER BY in the SQL statement, and the sort only applies to the rows that already passed the filter.
Example: Combining ORDER BY with WHERE
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE users (name TEXT, status TEXT)");
$db->exec("INSERT INTO users VALUES ('Bob','active'), ('Alice','active'), ('Carol','inactive')");
// Declare `$result`, set to `$db->query("SELECT * FROM users WHERE status = 'active' ORDER BY name")`
$result = $db->query("SELECT * FROM users WHERE status = 'active' ORDER BY name");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Print `$row['name'] . "\n"` to the output
echo $row['name'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Sorting by an Expression or Alias
ORDER BY can sort by more than just a plain column name -- it also accepts a computed expression (like a calculated total) or the alias given to a column in the SELECT clause, letting you sort by values that do not exist as their own stored column.
Example: Sorting by an Expression or Alias
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE items (name TEXT, price INTEGER, qty INTEGER)");
$db->exec("INSERT INTO items VALUES ('A', 10, 2), ('B', 5, 10)");
// Declare `$result`, set to `$db->query("SELECT name, (price * qty) as total FROM items ORDER BY total DESC")`
$result = $db->query("SELECT name, (price * qty) as total FROM items ORDER BY total DESC");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Print `$row['name'] . ": " . $row['total'] . "\n"` to the output
echo $row['name'] . ": " . $row['total'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
- Assuming a table's natural row order (like insertion order) is reliable without an explicit ORDER BY -- MySQL does not guarantee any particular order without one.
- Sorting a large result set purely with PHP's sort functions after fetching it, when ORDER BY in the SQL query itself is far more efficient and can use table indexes.
- Forgetting ASC/DESC direction and getting the opposite sort order than intended -- ASC (ascending, the default) sorts smallest/earliest first, DESC sorts largest/latest first.
- ORDER BY column sorts query results by that column, ascending by default.
- ORDER BY column DESC sorts in descending order instead, largest or most recent values first.
- ORDER BY col1, col2 sorts by col1 first, using col2 only to break ties where col1 values are equal.
ORDER BY is standard SQL and works identically across all MySQL and MariaDB versions PHP supports.
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- PHP MySQL Introduction
- PHP MySQLi Connection
- PHP PDO Introduction
- PHP CRUD Operations
- PHP Prepared Statements
- PHP Stored Procedures
- PHP Transactions
- PHP Error Handling in DB
- PHP MySQL Connect
- PHP MySQL Create DB
- PHP MySQL Create Table
- PHP MySQL Insert Data
- PHP MySQL Get Last ID
- PHP MySQL Insert Multiple
- PHP MySQL Prepared Statements
- PHP MySQL Select Data
- PHP MySQL Where
- PHP MySQL Order By
- PHP MySQL Delete Data
- PHP MySQL Update Data
- PHP MySQL Limit Data