API sorting allows a mobile application to control the order in which records are returned by the REST API. For example, students can be sorted by name, newest records can be shown first, or products can be sorted by price.
API sorting means arranging API results according to a selected column or property.
Mobile App
↓
Sort Parameter
↓
REST API
↓
Database
↓
Sorted Records
↓
JSON Response
Suppose a student application contains 500 students. Users may want to see students alphabetically by name or newest students first.
Instead of sorting everything on the mobile device, the API can request the database to return records in the required order.
A common sorting URL is:
GET /api/students.php?sort=name
The API receives name as the requested sorting column.
Sorting normally has two directions:
| Direction | Meaning |
|---|---|
| ASC | Ascending order |
| DESC | Descending order |
?sort=name&order=asc
?sort=name&order=desc
MySQL uses ORDER BY to sort query results.
SELECT *
FROM students
ORDER BY name ASC;
This returns students in ascending alphabetical order by name.
To display larger, newer, or later values first, use
DESC.
SELECT *
FROM students
ORDER BY id DESC;
This can be useful for displaying recently inserted records first.
SELECT
id,
student_id,
name,
course
FROM students
ORDER BY name ASC;
The result is arranged alphabetically by student name.
SELECT *
FROM students
ORDER BY id DESC;
Using descending ID order commonly displays recently created records first when IDs increase as records are created.
Sorting is not limited to text fields.
SELECT *
FROM students
ORDER BY fee ASC;
This displays records from the lowest fee to the highest fee.
Date columns can also be sorted.
SELECT *
FROM students
ORDER BY admission_date DESC;
This can show recently admitted students first.
$sort = $_GET['sort'] ?? 'id';
$order = $_GET['order'] ?? 'desc';
Default values can be used when the client does not send sorting parameters.
The sort direction should be restricted to known values.
$order = strtolower(
$_GET['order'] ?? 'desc'
);
if (!in_array(
$order,
['asc', 'desc'],
true
)) {
$order = 'desc';
}
This prevents unexpected values from being used as SQL syntax.
Column names should not be accepted directly from the user. Create an allowlist of columns that the API permits.
$allowedSortColumns = [
'id' => 'id',
'name' => 'name',
'fee' => 'fee',
'admission_date' => 'admission_date'
];
$sort = $_GET['sort'] ?? 'id';
if (!isset($allowedSortColumns[$sort])) {
$sort = 'id';
}
$sortColumn =
$allowedSortColumns[$sort];
A prepared statement placeholder is designed for values. It should not be treated as a direct placeholder for a SQL column name.
Therefore, dynamic sort columns should be selected from a trusted allowlist.
$allowedSortColumns = [
'name' => 'name',
'fee' => 'fee',
'id' => 'id'
];
Only columns defined in the allowlist should be used in the
ORDER BY clause.
<?php
header(
"Content-Type: application/json"
);
require_once '../db.php';
$allowedSortColumns = [
'id' => 'id',
'name' => 'name',
'fee' => 'fee',
'admission_date' => 'admission_date'
];
$sort =
$_GET['sort'] ?? 'id';
$order = strtolower(
$_GET['order'] ?? 'desc'
);
if (!isset(
$allowedSortColumns[$sort]
)) {
$sort = 'id';
}
if (!in_array(
$order,
['asc', 'desc'],
true
)) {
$order = 'desc';
}
$sortColumn =
$allowedSortColumns[$sort];
try {
$sql = "
SELECT
id,
student_id,
name,
course,
fee,
admission_date
FROM students
ORDER BY $sortColumn $order
";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$students =
$stmt->fetchAll(
PDO::FETCH_ASSOC
);
echo json_encode([
"success" => true,
"sort" => $sort,
"order" => $order,
"data" => $students
]);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
"success" => false,
"message" =>
"Server error"
]);
}
?>
To sort students by name in ascending order:
GET /api/students.php?sort=name&order=asc
Example result:
Amit
Anil
Rahul
Ravi
Vijay
GET /api/students.php?sort=name&order=desc
The results will be returned in reverse alphabetical order.
Vijay
Ravi
Rahul
Anil
Amit
Sorting can be combined with filtering.
GET /api/students.php?status=active&sort=name&order=asc
The API first selects active students and then sorts the matching records by name.
SELECT *
FROM students
WHERE status = ?
ORDER BY name ASC;
Search and sorting can also be combined.
GET /api/students.php?search=rahul&sort=name&order=asc
The API can search for matching students and then arrange the results.
const response = await fetch(
"https://example.com/api/students.php"
+ "?sort=name"
+ "&order=asc"
);
const result =
await response.json();
setStudents(
result.data || []
);
The mobile application can request the required sorting order from the API.
import axios from "axios";
const response = await axios.get(
"https://example.com/api/students.php",
{
params: {
sort: "name",
order: "asc"
}
}
);
setStudents(
response.data.data || []
);
A mobile application can provide buttons or a dropdown for selecting the sort column.
const [sort, setSort] =
useState("name");
const [order, setOrder] =
useState("asc");
These values can be sent to the API.
<Button
title="A-Z"
onPress={() => {
setSort("name");
setOrder("asc");
}}
/>
<Button
title="Z-A"
onPress={() => {
setSort("name");
setOrder("desc");
}}
/>
This provides a simple way for users to change the result order.
After receiving sorted data from the API, the React Native application can display it directly in a FlatList.
<FlatList
data={students}
keyExtractor={(item) =>
item.id.toString()
}
renderItem={({ item }) => (
<Text>
{item.name}
</Text>
)}
/>
The order of the FlatList items follows the order returned by the API.
Many applications need the newest records first.
GET /api/students.php?sort=id&order=desc
If IDs increase as records are created, this can commonly show newer records first.
For more accurate date-based ordering, use a dedicated timestamp or date column.
Dynamic sort columns require special care because a column name is part of the SQL statement.
Unsafe:
$sort = $_GET['sort'];
$sql =
"SELECT *
FROM students
ORDER BY $sort";
Safer:
$allowedSortColumns = [
'id' => 'id',
'name' => 'name',
'fee' => 'fee'
];
$sort =
$_GET['sort'] ?? 'id';
if (!isset(
$allowedSortColumns[$sort]
)) {
$sort = 'id';
}
$sortColumn =
$allowedSortColumns[$sort];
Always use an allowlist for dynamic SQL identifiers.
Sorting becomes especially important when an API uses pagination. The
API should apply a consistent ordering before applying
LIMIT and OFFSET.
SELECT *
FROM students
ORDER BY name ASC
LIMIT 20 OFFSET 0;
This helps keep pages predictable.
Method: GET
http://localhost/api/students.php?sort=name&order=asc
Click Send and check the order of the returned records.
You can also test:
http://localhost/api/students.php?sort=id&order=desc
Compare the results to understand ascending and descending order.
React Native
↓
Select Sort Column
↓
Select ASC / DESC
↓
Query Parameters
↓
GET Request
↓
PHP REST API
↓
Validate Sort Column
↓
Validate Sort Direction
↓
ORDER BY
↓
MySQL
↓
Sorted JSON Data
↓
React Native FlatList
API sorting allows the client to control the order of records returned
by a REST API. PHP can read the requested sort field and direction,
validate them using an allowlist, and build a safe
ORDER BY clause.
GET /api/students.php?sort=name&order=asc
Sorting is especially useful when building student lists, product lists, payment reports, attendance records, and other mobile applications.
ORDER BY is used in SQL for sorting.ASC means ascending order.DESC means descending order.Question: Which SQL clause is used to sort records?