SQL ORDER BY keyword

0
26

sqltuts

ORDER BY used to define how the records are to be sorted. By default, it is to order in ascending order(ASC).

If we want to sort in descending order, we can use DESC after the column name.

 

Syntax:

  1. SELECT column_name, column_name
  2. FROM table_name
  3. ORDER BY column_name ASC/DESC, column_name ASC/DESC;

 

For example, consider the following table Employee:

 

Employee_id First_name Last_name sex
123 Mack Johnson male
124 Jack Obama male
125 King Khan male

 

  1. SELECT * FROM Employee
  2.   ORDER BY Employee_id DESC;

This would give the following output:

 

Employee_id First_name Last_name sex
125 King Khan male
124 Jack Obama male
123 Mack Johnson male

 

Example:

Sorting in descending order by using “ORDER BY clause”

  1. <?php
  2. $dbhost = 'localhost';
  3. $dbusername = 'root';
  4. $dbpassword = 'rootpassword';
  5. $conn = mysql_connect($dbhost, $dbusername, $dbpassword);
  6. if(! $con )
  7. {
  8.   die('Could not connect: ' . mysql_error());
  9. }
  10. $sql = 'SELECT tutorial_id, tutorial_Fname,
  11.               tutorial_Lname, submission_FEE
  12.        FROM tutorials_Person
  13.        ORDER BY  tutorial_id DESC';
  14.  
  15. mysql_select_db(' Database,TUTORIALS');
  16. $result = mysql_query( $sql, $con );
  17. if(! $result )
  18. {
  19.   die('Could not get data: ' . mysql_error());
  20. }
  21. while($row = mysql_fetch_array($result, MYSQL_ASSOC))
  22. {
  23.     echo "Tutorial ID :{$row['tutorial_id']}  <br> ".
  24.          "Fname: {$row['tutorial_Fname']} <br> ".
  25.          "Lname: {$row['tutorial_Lname']} <br> ".
  26.          "Submission FEE : {$row['submission_FEE']} <br> ".
  27.          "--------------------------------<br>";
  28. }
  29. echo "Fetched data successfully\n";
  30. ?>
Facebook Comments
(Visited 26 times, 1 visits today)
SHARE
Previous articleSQL LIKE Clause
Next articleSQL ALTER Table Statement
Hello Itsourcecoders, welcome to itsourcecode.com. I'm Joken Villanueva, MIT a passionate Blogger, Programmer and a Hobbyist. I started Itsourcecode because I wanted to give back and Share all the learnings and knowledge I've learned in my career and I believe through this website I would be able to help and assist those newbie programmers in enhancing their skills from different programming languages. So let us all help each other by sharing our ideas!

LEAVE A REPLY

Please enter your comment!
Please enter your name here