⊗ppPmDBNSr 376 of 447 menu

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 $query = "SELECT * FROM users ORDER BY age"; ?>

Example

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

<?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 $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 $query = "SELECT * FROM users ORDER BY age, salary"; ?>

Practical Tasks

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

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

Retrieve all users and sort them by name.

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

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

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline