Friday 6 May 2016

Usage of ORDER BY for multiple columns - SQL

Sorting in an ORDER BY is done by the first column, and then by each additional column in the specified statement.
For instance, consider the following data:
Column1    Column2
=======    =======
1          Smith
2          Jones
1          Anderson
3          Andrews
The query
SELECT Column1, Column2 FROM thedata ORDER BY Column1, Column2
would first sort by all of the values in Column1
and then sort the columns by Column2 to produce this:
Column1    Column2
=======    =======
1          Anderson
1          Smith
2          Jones
3          Andrews
In other words, the data is first sorted in Column1 order, and then each subset (Column1 rows that have 1 as their value) are sorted in order of the second column.
The difference between the two statements you posted is that the rows in the first one would be sorted first by prod_price (price order, from lowest to highest), and then by order of name (meaning that if two items have the same price, the one with the lower alpha value for name would be listed first), while the second would sort in name order only (meaning that prices would appear in order based on the prod_name without regard for price).

No comments:

Post a Comment