Sorting Records via SQL Query in PHP

Using the ORDER BY command, you can sort the result rows.

Example

Let's select all users from our users table and sort them by age from smallest to largest:

php<?php
  $query = "SELECT * FROM users ORDER BY age";
?>

Example

Let's change the sort order using the DESC command:

php<?php
  $query = "SELECT * FROM users ORDER BY age DESC";
?>

Example

Let's select all users with a salary of 500 and sort them by age from smallest to largest:

php<?php
  $query = "SELECT * FROM users WHERE salary=500 ORDER BY age";
?>

Example

You can sort not by one field, but by several. For example, let's select all users and sort them first in ascending order of age, and then sort users with the same age in ascending order of salary:

php<?php
  $query = "SELECT * FROM users ORDER BY age, salary";
?>

Practical Tasks

Задание 1

Retrieve all users and sort them by salary in ascending order.

Задание 2

Retrieve all users and sort them by salary in descending order.

Задание 3

Retrieve all users and sort them by name.

Задание 4

Retrieve users with a salary of 500 and sort them by age.

Задание 5

Retrieve all users and sort them by name and by salary.