PHP MySQL Use ORDER BY

PHP MySQL Use ORDER BY – Complete Tutorial

Sorting database records is a very common requirement in dynamic websites. Whether you want to display users alphabetically, latest posts first, or highest prices on top, the MySQL ORDER BY clause makes it possible.

This tutorial explains how to use ORDER BY in PHP MySQL with clear examples and outputs.


What Is ORDER BY in PHP MySQL?

The ORDER BY clause is used in SQL to sort the result set returned by a SELECT query.

It can sort data:

  • In ascending order (ASC)
  • In descending order (DESC)

Basic syntax:

SELECT column_name FROM table_name ORDER BY column_name;

Prerequisites for Using ORDER BY in PHP

Before using ORDER BY, you should have:

  • A working PHP MySQL connection
  • A table with data
  • Basic understanding of SELECT queries

Sample MySQL Table Used in This Tutorial

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    age INT
);

PHP MySQL Database Connection Code

<?php
$conn = mysqli_connect("localhost", "root", "", "testdb");

if (!$conn) {
    die("Database connection failed");
}
?>

Select Data Using ORDER BY in PHP MySQL

<?php
$query = "SELECT * FROM users ORDER BY name";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . "<br>";
}
?>

Output:

Amit
Neha
Rahul

By default, ORDER BY sorts data in ascending order.


Using ORDER BY ASC in PHP MySQL

<?php
$query = "SELECT * FROM users ORDER BY age ASC";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . " - " . $row['age'] . "<br>";
}
?>

Output:

Neha - 22
Rahul - 25
Amit - 30

Using ORDER BY DESC in PHP MySQL

<?php
$query = "SELECT * FROM users ORDER BY age DESC";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . " - " . $row['age'] . "<br>";
}
?>

Output:

Amit - 30
Rahul - 25
Neha - 22

ORDER BY with Multiple Columns in PHP MySQL

<?php
$query = "SELECT * FROM users ORDER BY age ASC, name ASC";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . " - " . $row['age'] . "<br>";
}
?>

Output:

Neha - 22
Rahul - 25
Amit - 30

ORDER BY with LIMIT in PHP MySQL

<?php
$query = "SELECT * FROM users ORDER BY id DESC LIMIT 2";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . "<br>";
}
?>

Output:

Neha
Amit

ORDER BY with WHERE Clause in PHP MySQL

<?php
$query = "SELECT * FROM users WHERE age > 20 ORDER BY name";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    echo $row['name'] . "<br>";
}
?>

Output:

Amit
Neha
Rahul

Secure ORDER BY Queries in PHP MySQL

When column names come from user input, always validate them manually because prepared statements cannot bind column names.

<?php
$allowed_columns = ['name', 'age'];
$order = in_array($_GET['order'], $allowed_columns) ? $_GET['order'] : 'name';

$query = "SELECT * FROM users ORDER BY $order";
$result = mysqli_query($conn, $query);
?>

Common Mistakes When Using ORDER BY

  • Forgetting ASC or DESC meaning
  • Using ORDER BY without SELECT
  • Sorting by non-indexed columns in large tables
  • Allowing user input without validation

PHP MySQL ORDER BY, PHP MySQL sort data, PHP ORDER BY ASC DESC, PHP MySQL ORDER BY example, PHP MySQLi ORDER BY tutorial, PHP database sorting, PHP SELECT ORDER BY


Best Practices for ORDER BY in PHP MySQL

  • Use indexes on frequently sorted columns
  • Combine ORDER BY with LIMIT for performance
  • Validate column names if dynamic
  • Avoid sorting large datasets unnecessarily

Link this tutorial with related topics:


Frequently Asked Questions (FAQ)

1. What is ORDER BY used for?

It sorts query results in ascending or descending order.

2. What is default order of ORDER BY?

Ascending order (ASC).

3. Can ORDER BY sort text values?

Yes, alphabetically.

4. Can I use ORDER BY with LIMIT?

Yes, it is very common.

5. Is ORDER BY case-sensitive?

It depends on database collation.

Related Article
50+ PHP Interview Questions and Answers 2023

1. Differentiate between static and dynamic websites. Static Website The content cannot be modified after the script is executed The Read more

All We Need to Know About PHP Ecommerce Development

  Many e-commerce sites let you search for products, show them off, and sell them online. The flood of money Read more

PHP Custom Web Development: How It Can Be Used, What Its Pros and Cons Are,

PHP is a scripting language that runs on the server. It uses server resources to process outputs. It is a Read more

PHP Tutorial

PHP Tutorial – Complete Guide for Beginners to Advanced Welcome to the most comprehensive PHP tutorial available online at PHPOnline.in Read more

Introduction of PHP

Introduction to PHP – Learn PHP from Scratch with Practical Examples Welcome to your complete beginner's guide to PHP. Whether Read more

Syntax Overview of PHP

Syntax Overview of PHP (2025 Edition) Welcome to phponline.in, your one-stop platform for mastering PHP. This comprehensive, SEO-rich tutorial on Read more

Environment Setup in PHP

Setting Up PHP Environment (Beginner’s Guide) If you’re planning to learn PHP or start developing websites using PHP, the first Read more

Variable Types in PHP

PHP Variable Types: Complete Beginner's Guide to PHP Data Types Welcome to phponline.in, your trusted source for beginner-to-advanced level PHP Read more