PHPMySQLOrderBy keyword usage

Source: Internet
Author: User
PHPMySQLOrderBy keyword usage

  1. SELECT column_name (s)
  2. FROM table_name
  3. Order by column_name

Note: SQL is case insensitive. Order by is equivalent to order.

For example, select all the data stored in the "Persons" table and sort the results according to the "Age" column:

  1. $ Con = mysql_connect ("localhost", "peter", "abc123 ");

  2. If (! $ Con)
  3. {
  4. Die ('could not connect: '. mysql_error ());
  5. }

  6. Mysql_select_db ("my_db", $ con );

  7. $ Result = mysql_query ("SELECT * FROM Persons order by age ");

  8. While ($ row = mysql_fetch_array ($ result ))

  9. {
  10. Echo $ row ['firstname'];
  11. Echo "". $ row ['lastname'];
  12. Echo "". $ row ['age'];
  13. Echo"
    ";
  14. }

  15. Mysql_close ($ con );

  16. ?>

Output: Glenn Quagmire 33 Peter Griffin 35

1. sort in ascending or descending ORDER if you use the order by keyword, the sorting ORDER of the record set is ascending BY default (1 before 9, "a" before "p ).

Use the DESC keyword to set the descending order (9 before 1, "p" before "):

  1. SELECT column_name (s)
  2. FROM table_name
  3. Order by column_name DESC

2. Sort by two columns by multiple columns. When sorting by multiple columns, the second column is used only when the first column is the same:

  1. SELECT column_name (s)
  2. FROM table_name
  3. Order by column_name1, column_name2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.