Learning how to use the ORDER BY clause to order query results

The ORDER BY clause is placed after FROM, as well as after WHERE, if you have a WHERE clause. You can order columns by ascending or descending order. Ascending is the default sort order, so you don't need to specify ascending explicitly.   

Do not depend on the order of the rows in a result set, unless you have specified an ORDER BY clause. The order in which rows are returned may or may not be the same without an ORDER BY explicitly defined in your query. 

To sort the columns in ascending order, use the ASC keyword, and to order them in descending order, use the DESC keyword. To sort a table by g_all in the appearances table, you can execute the following query: 

USE lahmansbaseballdb;
SELECT playerid, g_all, g_batting, g_defense
FROM appearances
ORDER BY g_all;

The previous query will give you the results shown in the following screenshot: 

The previous query doesn't have a WHERE clause, but if it required one, then you should place it between the FROM and ORDER BY clauses, as shown in the following query: 

USE lahmansbaseballdb;
SELECT playerid, g_all, g_batting, g_defense
FROM appearances
WHERE playerid LIKE 'a%'
ORDER BY g_all;

To sort in descending order instead, you can add the DESC keyword to your ORDER BY clause, as shown in the following query: 

USE lahmansbaseballdb;
SELECT playerid, g_all, g_batting, g_defense
FROM appearances
ORDER BY g_all DESC;

The previous query will give you the results shown in the following screenshot. You can see that g_all has the highest game total at the top of the results now:

You can also ORDER BY columns that aren't specified in your SELECT clause. You need to specify them in the ORDER BY clause by the exact column name in the table. 

Next, we will learn how to sort by one or more columns. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.253.62