Learning how to use the ORDER BY clause to sort by one or more columns

Let's say you wanted to sort on more than one column. To do this, you should place the columns you want to order by in the ORDER BY clause in the order in which you want them ordered. For instance, if you wanted to order by playerid, then g_all, you can execute the following query: 

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

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

As shown in the previous screenshot, the results are now ordered by ascending playerid, then g_all

You can also change the order of either column to descending by adding DESC to one or both columns, as shown in the following query: 

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

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

As shown in the previous screenshot, the results are now ordered descending by playerid, then g_all

If you want to, you can order by all the columns in the table, but there will be a performance impact on your query. You need to be careful with choosing which and how many columns to use in your ORDER BY clause. More on this topic will be covered in the Using indexes with your queries section, later in this chapter.

Another way to use the order in an ORDER BY clause is to use the column position. In the case of the previous queries, you would use a number to denote the column instead of the column name. This number corresponds to its place in the SELECT clause. For example, in the following query, playerid is 1,  g_all is 2, g_batting is 3, and g_defense is 4, so we can order the results by their position in the SELECT clause, as shown in the following query: 

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

The previous query will give the results shown in the following screenshot, which is the same as the results we got when we used the column names instead: 

I prefer to explicitly specify column names in the ORDER BY clause to avoid confusion. If you change the order of the columns in the SELECT clause, and you've used column position numbers instead of the column names in the ORDER BY clause, you will need to change your ORDER BY clause. Also, it's more confusing to read column position numbers in the ORDER BY clause because you have to correlate them back to the SELECT clause columns. Additionally, you may mistakenly specify the wrong column using the column position number. The last drawback of using column position numbers is that you can't order by a column that isn't specified in your SELECT clause.  

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

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