|
Custom Search
| |
|
Sorting Data It's often easier to examine the result rows from a query when the rows are sorted in some meaningful way. To sort a query output from a particular SELECT statement, use ORDER BY clause. Read Prerequisites for this tutorial and practices if you haven't done so. Consider the following facts when using ORDER BY clause in a SELECT statement:
Most of the queries in the tutorials need Northwind MySQL database, you can download the database script on this page. Practice #1: Sort column in descending order. -- In this query, the result is sorted in descending order.
Query result set - 77 rows returned: Practice #2: Sort column in ascending order by default. /*
Query result set - 77 rows returned: Practice #3: Case-sensitive descending sort Note that, before executing this query, in products table, you need to change the first letter to lower-case in two product names:
Aniseed Syrup ==> aniseed Syrup (ProductID 3) /* Normally sorting on a character type column is conducted in a case-insensitive fashion. You can force a case-sensitive sort by using the keyword BINARY after ORDER BY clause. Because lower-case letters are considered to have lower priority than upper-case letters, the result from this query displays the lower-case product names first in descending order.
Query result set - 77 rows returned: Practice #4: Case-sensitive ascending sort /* Because lower-case letters are considered to have lower priority than upper-case letters, the result from this query displays the upper-case product names first in ascending order.
Query result set - 77 rows returned: Practice #5: Sorting on two columns /*
Query result set - 77 rows returned: Practice #6: Sorting by column alias /*
Query result set - 77 rows returned: Practice #7: Sorting by a column of arithmetic operation /*
Query 1 result - 77 rows returned (Column alias is not used):
Query 2 result- 77 rows returned (Use column alias): Practice #8: Sort by a column which is not included in the result set /* The column(s) used in ORDER BY clause does not have to be included in the result set.
Query result set - 77 rows returned: Practice #9: Use column position number for sorting /*
Query result set - 77 rows returned: Practice #10: Randomly sort a query result /*
Query result set - 9 rows returned (yours can be different as it's random sort): To see how the random function works, execute the following query multiple times to see how the result changes: -- Generate random numbers Other tutorials in this category 1. The Basic SELECT Statement |
Copyright © 2024 GeeksEngine.com. All Rights Reserved. This website is hosted by HostGator. No portion may be reproduced without my written permission. Software and hardware names mentioned on this site are registered trademarks of their respective companies. Should any right be infringed, it is totally unintentional. Drop me an email and I will promptly and gladly rectify it. |
Home | Feedback | Terms of Use | Privacy Policy |