MySQL ORDER BY

Last updated on

Sorting data is one of those things we do all the time but rarely stop to think about. Whether you build an e-commerce website or a basic blog, you are probably sorting stuff behind the scenes—products by price, posts by date, or users by name. That is where the PHP MySQL ORDER BY clause shines. It lets you sort database records in just the order you need.

In this article, you will learn what ORDER BY is, how to use it with PHP and MySQL, and tweak it for more advanced tasks.

What Is ORDER BY in MySQL?

The ORDER BY clause in SQL is used to sort the rows in your result set. By default, it sorts in ascending order, but you can flip that to descending if you need to. It works perfectly with both numbers and text.

Here is the basic syntax:

SELECT column1, column2 
FROM table_name
ORDER BY column1 ASC;

In this syntax:

  • column1: The column you want to sort by.
  • ASC: Sorts the data in ascending order. It is optional because ascending is the default.
  • DESC: Sorts the data in descending order.

You usually run SQL queries using a MySQL database. You can integrate ORDER BY into these queries to sort the results before displaying them on your webpage.

Let's start by creating a sample database and table to work with:  

CREATE DATABASE your_database_name;
USE your_database_name;

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO products (name, price) VALUES
('Laptop', 899.99),
('Smartphone', 599.99),
('Tablet', 299.99),
('Headphones', 49.99);

In the following section, we will fetch the data by using PHP based on the sorting task.

Fetching and Sorting Data in PHP

The below code helps you to fetch this data and sort it by price in descending order:

$db_servername = "localhost";
$db_username = "root";
$db_password = "";
$db_dbname = "your_database_name";

// Create connection
$dbconne = new mysqli($db_servername, $db_username, $db_password, $db_dbname);

// Check connection
if ($dbconne->connect_error) {
    die("Unable to Connect: " . $dbconne->connect_error);
}

// SQL query with ORDER BY
$sql = "SELECT * FROM products ORDER BY price DESC";
$dbresult = $dbconne->query($sql);

if ($dbresult->num_rows > 0) {
    while ($recrow = $dbresult->fetch_assoc()) {
        echo "Product Name: " . $recrow['name'] . " - Price: $" . $recrow['price'] . "<br>";
    }
} else {
    echo "No results found.";
}

$dbconne->close();

As you see, the query retrieves all records from the products table, sorted by the price column in descending order.  

Sorting with Multiple Columns

If you need to sort data by using more than one column. For instance, you might want to sort by price and then by name (alphabetically) for products with the same price.

Here is how you can do it:

SELECT * FROM products
ORDER BY price DESC, name ASC;

The priority is determined by the order of the columns in the ORDER BY clause. In this case, price takes precedence, and name is used as a secondary sort.

If you decide to give your users the ability to how they want to sort the data. This can be achieved by dynamically building the ORDER BY clause based on user input.

$sort_column = isset($_GET['sort']) ? $_GET['sort'] : 'name'; // Default sort by name
$order = isset($_GET['order']) && $_GET['order'] === 'desc' ? 'DESC' : 'ASC';

$sql = "SELECT * FROM products ORDER BY $sort_column $order";
$dbresult = $conn->query($sql);

if ($dbresult->num_rows > 0) {
    while ($recrow = $dbresult->fetch_assoc()) {
        echo "Name: " . $recrow['name'] . " - Price: $" . $recrow['price'] . "<br>";
    }
} else {
    echo "No results found.";
}

The query selects all data from the products table and orders it by the column specified in $sort_column (e.g., name or price) and the direction specified in $order (ascending or descending).

If you have not heard about the $_GET superglobal variable, you can read this tutorial.

Anyway, let' move on to the following section to see how to do that by dates.

Sorting Dates

Sorting by dates is common in applications like blogs or e-commerce sites. With the created_at column we added earlier, you can easily sort products by their creation date.

Here is an example of the SQL query:

SELECT * FROM products
ORDER BY created_at DESC;

And the PHP implementation:

$sql = "SELECT * FROM products ORDER BY created_at DESC";
$dbresult= $dbconne->query($sql);

if ($dbresult->num_rows > 0) {
    while ($recrow= $dbresult->fetch_assoc()) {
        echo "Name: " . $recrow['name'] . " - Created At: " . $recrow['created_at'] . "<br>";
    }
} else {
    echo "No result found.";
}

This query selects all rows from the products table and orders them by the created_at column in descending order. The newest entries (most recent created_at values) will appear first.

Let's summarize it.

Wrapping Up

The MySQL ORDER BY in PHP is an incredibly useful tool for sorting data in MySQL. By combining it with PHP, you can create dynamic and user-friendly applications that serve sorted data exactly how your users need it. From sorting prices to ordering by dates, the possibilities are endless when you understand how to use it properly.

Now it is your turn. Try out the examples above, tweak the code to fit your project, and watch your database queries. Do not forget to test with different datasets to see how sorting transforms your application's behavior.

Thank you for reading. Happy Coding!

Frequently Asked Questions (FAQs)

  • What is the purpose of the ORDER BY clause in MySQL?

    The ORDER BY clause is used to sort the rows of a query result set in either ascending or descending order based on one or more columns.
  • How can I sort data in ascending order using ORDER BY?

    By default, the ORDER BY clause sorts data in ascending order. For example:
    SELECT * FROM table_name ORDER BY column_name ASC;
    .
  • Can I sort data in descending order using ORDER BY?

    Yes, use the DESC keyword. For example:
    SELECT * FROM table_name ORDER BY column_name DESC; 
  • How do I sort data by multiple columns?

    Specify multiple columns separated by commas in the ORDER BY clause. For example:
    SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC;
  • How can I sort MySQL data dynamically based on user input in PHP?

    You can build the ORDER BY clause dynamically using PHP variables. For example:
    $sort_column = isset($_GET['sort']) ? $_GET['sort'] : 'name';
    $order = isset($_GET['order']) && $_GET['order'] === 'desc' ? 'DESC' : 'ASC';
    $sql = "SELECT * FROM table_name ORDER BY $sort_column $order";
  • Is it possible to sort data by dates?

    Yes, you can use a date column in the ORDER BY clause. For example:
    SELECT * FROM table_name ORDER BY date_column DESC; 
    .
  • What happens if two rows have the same value in the sorting column?

    You can add a secondary column to the ORDER BY clause to resolve ties. For example:
    SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC;
    .
  • How do I implement sorting in PHP and MySQL?

    Use the ORDER BY clause in your SQL query and fetch the results in PHP using database functions like mysqli_query or PDO.
  • Can ORDER BY be used with numeric and text columns?

    Yes, the ORDER BY clause works seamlessly with both numeric and text columns.
  • How do I ensure SQL injection protection when sorting data dynamically?

    Use prepared statements with placeholders for any user input, ensuring it is properly sanitized before being included in the query.
  • Can ORDER BY be combined with LIMIT?

    Yes, you can limit the number of rows returned after sorting. For example:
    SELECT * FROM table_name ORDER BY column_name DESC LIMIT 10;
    .
  • Is it possible to use ORDER BY with joins?

    Yes, you can use ORDER BY with queries involving joins. Just specify the column for sorting, potentially using table aliases.
  • What are common use cases for ORDER BY in web applications?

    Examples include sorting products by price, posts by date, or users alphabetically by name.
  • How does ORDER BY handle NULL values?

    NULL values are sorted first in ascending order and last in descending order by default.
  • Can I use ORDER BY with aggregate functions?

    Yes, you can sort results by the output of aggregate functions like COUNT, SUM, AVG, etc.
Share on: