MySQL ORDER BY Query
The data can save in table in
non sequence format. If you can arrange the data in proper sequence then you
can use the ORDER BY command in SQL. You can arrange the data in Ascending or
descending order.
Syntax
Select field1, field2, field3
from table _ name ORDER BY field1 [ASC [DESC]]
- You can sort returned result on any field provided that filed is being listed out.
- You can use keyword ASC or DESC to get result in ascending or descending.
- You can use WHERE...LIKE clause in usually way to put condition.
- You can sort result on more than one field.
Suppose the table in store
the value in unordered.
Student name
|
Age
|
Id
|
Lakwinder singh
|
30
|
2
|
Pardeep singh
|
25
|
1
|
Amandeep singh
|
25
|
4
|
Deepak kumar
|
26
|
3
|
These value are unordered
means not in sequence. Now we can use the ORDER BY to arrange this table.
Select * from student ORDER BY Student_name Asc;
The output is given below
Student name
|
Age
|
Id
|
Amandeep singh
|
25
|
4
|
Deepak kumar
|
26
|
3
|
Lakwinder singh
|
30
|
2
|
Pardeep singh
|
25
|
1
|
Example
<?php
$con=mysql_connect(“localhost”, “deep “, 12345);
if (!$con)
{
die(“could not be connect the database” . mysql_error());
}
echo “ connected successfully “;
mysql_select_db ( “student”);
$sql = ”select stu_id, stu_name, stu_class from student1 ORDER
BY Student_name Asc;
$retrive =mysql_query ($sql, $con );
If (!$retrive)
{
die (“could not be connect”);
}
While ($row = mysql_fetch_array ($retrive))
{
echo “ Student id is
: {$row [‘stu_id’] } <br>”.
“ Student Name is : {$row [‘stu_name’] } <br>”.
“ Student Class is : {$row [‘stu_class’] } <br>” ;
}
mysql_close ($con);
?>