Home >>MySQL Tutorial >MySQL Order By
The ORDER BY is a keyword which is used to sort the results based on one or more columns. by default it sorts the result set in ascending order . if we want to sort the results in descending order we use DESC keyword. for ascending order we use ASC keyword.
Syntax
SELECT * FROM table_name ORDER BY column_name ASC|DESC
<?php //connect database $con=mysqli_connect("localhost","root","","Employee") or die(mysqli_error()); //select all values from empInfo table $data="SELECT * FROM empInfo ORDER BY emp_id ASC"; $val=mysqli_query($con,$data); while($r=mysqli_fetch_array($val)) { echo $r['emp_id']." ".$r['name']." ".$r['email']." ".$r['mobile']."<br/>"; } ?>
Output :
Emp_id | Name | Mobile | |
---|---|---|---|
1 | devesh | devesh@gmail.com | 9910099100 |
2 | deepak | deepak@gmail.com | 9210053520 |
3 | ravi | ravi@gmail.com | 9810098100 |
In the above example there is a empInfo table the data is retrived in ascending order based on emp_id the fetched data is stored in the val variable and results are displayed in tabular form.
<?php $con=mysqli_connect("localhost","root","","Employee") or die(mysqli_error()); //select all values from empInfo table $data="SELECT * FROM empInfo ORDER BY emp_id desc"; $val=mysqli_query($con,$data); while($r=mysqli_fetch_array($val)) { echo $r['emp_id']." ".$r['name']." ".$r['email']." ".$r['mobile']."<br/>"; } ?>
Output :
Emp_id | Name | Mobile | |
---|---|---|---|
3 | ravi | ravi@gmail.com | 9810098100 |
2 | deepak | deepak@gmail.com | 9210053520 |
1 | devesh | devesh@gmail.com | 9910099100 |
In the above example first we create connection with the database and data is retrived in descending order by using DESC keyword the fetched data is stored in the val variable and results are displayed in tabular form.