The ORDER BY keyword is used to sort the data in the recordset

Source: Internet
Author: User
Keywords Network programming Mysql tutorial
Tags data echo example mysql mysql tutorial network network programming note
ORDER BY keyword

The ORDER BY keyword is used to sort the data in the recordset.

Syntax SELECT column_name (s) FROM table_name ORDER BY column_name

Note: SQL is not case sensitive. ORDER BY and order by equivalent.

example

The following example picks all the data stored in the "Person" table and sorts the results according to the "Age" column:

<? php $ con = mysql_connect ("localhost", "peter", "abc123"); if ($ con) {die ('Could not connect:'. mysql_error ());} mysql_select_db ("my_db", $ ($ result = con); $ result = mysql_query ("SELECT * FROM person ORDER BY age"); while ($ row = mysql_fetch_array ($ result)) {echo $ row ['FirstName']; echo "". $ row ['LastName' echo "". $ row ['Age']; echo "<br />";} mysql_close ($ con);?>

Output of the above code:

Glenn Quagmire 33 Peter Griffin 35 Sort Ascending Or Descending

If you use the ORDER BY keyword, the recordset's sort order is by default ascending (1 before 9 and "a" before "p").

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

SELECT column_name (s) FROM table_name ORDER BY column_name DESC Sort according to two columns

You can sort according to multiple columns. When sorting by multiple columns, the second column is used only if the first column is the same:

SELECT column_name (s) FROM table_name ORDER BY column_name1, column_name2

Related Article

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.