---[REF]---"style":"heading"---[REF]---
---[SIDEBAR]---
"type":"objectives",
"title":"Learning Objectives",
"text":"After completing this lesson, the successful student will be able to:
- Use the ORDER BY clause of a SELECT statement to sort the rows in a query result.
- Sort the rows of a query result in both ascending and descending order.
- Sort the rows of a query result by more than one column in the data.
- Use the keyword LIMIT to show a specified number of rows in a query result.
As you saw in the last lesson, the SQL statement below will display the names of the museums from the museum table.
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas|visible
owner:atlas-query
result:museum-name
---[SQL]---
SELECT name
FROM museum;
---[SQL]---
Notice that the museum names will be displayed in what appears to be a random order. Generally, the data is displayed in the order that it is stored in the database table. This is often the order that the data was added to the table. However, when data is updated in or deleted from the table, the DBMS may store the data in a different order. The only way you can predict the order that rows will be retrieved is to intentionally define how you want the data sorted as part of the SQL statement. This is done using the ORDER BY clause of the SELECT statement.
---[SIDEBAR]---
"type":"term",
"title":"CLAUSE",
"text":"As clause of a SQL statement is an element of the statement that defines a specific aspect of the statement. The SELECT statement has six clauses: SELECT, FROM, WHERE, GROUP BY, HAVING, and ORDER BY. Of these, only SELECT and FROM are required in all SELECT statements."
---[SIDEBAR]---
To define the sorting order of the rows that are retrieved using a SELECT statement, you use the ORDER BY clause. The ORDER BY clause is used to define one or more columns on which the data returned by the query will be sorted.
---[SIDEBAR]---
"type":"term",
"title":"ORDER BY",
"text":"The ORDER BY clause is used to define one or more columns on which the data returned by a SELECT statement will be sorted."
---[SIDEBAR]---
You may want to list the museum names in the last query and arrange them in alphabetical order.
---[EVALUATE]---
"type":"plan",
"task":"Display the names of the museums in alphabetical order.",
"columns":"name",
"tables":"museum",
"order":"Alphabetically by museum name."
---[EVALUATE]---
You may want to arrange and display the museum names in the last query in alphabetical order. To do so, adjust the SELECT statement to:
SELECT name
FROM museum
ORDER BY name ASC;
---[EVALUATE]---
"type":"evaluate",
"query":"SELECT name FROM museum ORDER BY name ASC;"
---[EVALUATE]---
This query will produce the correct results. It will display the name column from the museum table. The ORDER BY clause is used to sort the rows in the query results. The keyword ASC will sort the rows in ascending order. Since the name column contains text, sorting my name in ascending order will return an alphabetized list.
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:museum-name-sorted-asc
---[SQL]---
SELECT name
FROM museum
ORDER BY name ASC;
---[SQL]---
---[SIDEBAR]---
"type":"caution",
"title":"Where to place the ORDER BY Clause",
"text":"When you use an ORDER BY clause in a SELECT statement, it must always be last. Placing ORDER BY before any of the other clauses (SELECT, FROM, WHERE, GROUP BY, or HAVING) will result in an error."
---[SIDEBAR]---
The default option for sorting data in a column is to do so in ascending order. Because of this, it is actually not necessary to include the keyword ASC in the statement. In fact the keyword ASC is omitted in most cases. It is just as correct, and more common, to use this syntax:
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:museum-name-sorted-asc
---[SQL]---
SELECT name
FROM museum
ORDER BY name;
---[SQL]---
## Setting the Sort Direction
When you sort columns that contain text, ascending order means that the data in the column will be sorted in alphabetical (A-Z) order. You can also sort columns that contain other types of data. When a column that contains numbers is sorted in ascending order, the values are arranged smallest to largest. A column that contains dates that is sorted in ascending order will be arranged from the oldest to the newest.
---[SIDEBAR]---
"type":"term",
"title":"Ascending (ASC)",
"text":"When data is sorted in ascending order (ASC) it is arranged alphabetically for text, smallest to largest for numbers, and from the least to the most current for dates."
---[SIDEBAR]---
You can also choose to reverse the sorting order of a column or sort the data in a column in descending order. To sort data in descending order, you use the keyword DESC. Since this is not the default way to sort, you must include the keyword DESC in the ORDER BY clause if you wish to reverse the sorting of the data.
When you sort text in descending order, the data will be arranged in reverse alphabetical order (Z-A). Sorting numbers in descending order will arrange them from largest to smallest. Finally, sorting dates in descending order will put the most current date first and the least current date last.
---[SIDEBAR]---
"type":"term",
"title":"Descending (DESC)",
"text":"When data is sorted in descending order (DESC) it is arranged reverse alphabetically for text, largest to smallest for numbers, and from the most to the least current for dates."
---[SIDEBAR]---
Assume you want to arrange and display the museum names in the last query in reverse alphabetical order.
---[EVALUATE]---
"type":"plan",
"task":"List the names of the museums in reverse alphabetical order.",
"columns":"name",
"tables":"museum",
"order":"Descending order (reverse alphabetically) by museum name."
---[EVALUATE]---
Assume you want to arrange and display the museum names in the last query in reverse alphabetical order. This would require an adjustment the SELECT statement to:
SELECT name
FROM museum
ORDER BY name DESC;
---[EVALUATE]---
"type":"evaluate",
"query":"SELECT name FROM museum ORDER BY name DESC;"
---[EVALUATE]---
This query will produce the correct result. It will display the museum names from the museum table. The keyword DESC will ensure that the results are sorted in reverse alphabetical order.
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:museum-name-sorted-desc
---[SQL]---
SELECT name
FROM museum
ORDER BY name DESC;
---[SQL]---
---[SIDEBAR]---
"type":"caution",
"title":"Sorting Text and Case Sensitivity",
"text":"When sorting text, capitalization can be problematic. For example, it is possible that an upper-case A will not be treated the same as a lower-case a. When this happens, would the letter 'a' be sorted before or after the letter 'Z'? In most cases the DBMS will treat upper and lower case letters the same (A will be treated the same as a). However, there may be situations where this is not desirable and the database administrator configures the DBMS to behave differently. When this is the case, you may find that sorting text gives you some unexpected results and you may not be able to achieve the result you are looking for with a simple ORDER BY clause."
---[SIDEBAR]---
## Sorting by Multiple Columns
Generally, a query will include more than one column. When a query contains more than one column, you can still arrange sort the query results. For example, you may wish to see the city and country for each museum in the alphabetized list of museum names.
---[EVALUATE]---
"type":"plan",
"task":"List the name, city, and country for each museum. Arrange the rows alphabetically by museum name.",
"columns":"name, city, country",
"tables":"museum",
"order":"Alphabetically by museum name."
---[EVALUATE]---
The SELECT statement for this query would be:
SELECT name, city, country
FROM museum
ORDER BY name;
---[EVALUATE]---
"type":"evaluate",
"query":"SELECT name, city, country FROM museum ORDER BY name;"
---[EVALUATE]---
This query will produce the correct results. It will list the name, city, and country columns from the museum table. The rows will be sorted in ascending order by museum name.
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:museum-name-city-country-sorted-by-name
---[SQL]---
SELECT name, city, country
FROM museum
ORDER BY name;
---[SQL]---
Recall that each row of the a database table contains all of the information stored about an individual instance of that table. For example, the first row of the last example query contains information about the Army Museum which is in Paris, France. If the data were to be sorted in reverse alphetical order by name not only would the Army Museum be displayed as the last row of the query result, but the Paris and France would also move with it. In other words, data on the same row will be rearranged together even if the query is only sorted on one column.
Additionally, it is possible to sort data by more than one column. For example, you may wish to to see the list of museums arranged by country and then by city within each country. This would provide a geographical arrangement of the museum data.
---[EVALUATE]---
"type":"plan",
"task":"Display a list of names, cities, and countries of museums. Sort the results first by country and then by city.",
"columns":"name, city, country",
"tables":"museum",
"order":"By country in ascending order then city in ascending order."
---[EVALUATE]---
This would provide a geographical arrangement of the museum data. The SELECT statement for this query would be:
SELECT name, city, country
FROM museum
ORDER BY country, city;
---[EVALUATE]---
"type":"evaluate",
"query":"SELECT name, city, country FROM museum ORDER BY country, city;"
---[EVALUATE]---
This query will product the correct result. It will list the name, city, and country from the museum table. The results will first be sorted by country, then by city. Both country and city will be sorted in alphabetical (ascending) order.
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:museum-name-city-country-sorted
---[SQL]---
SELECT name, city, country
FROM museum
ORDER BY country, city;
---[SQL]---
The order of the columns listed in the ORDER BY clause matters. The data will first be sorted by the first column in the list and by each successive column. Sorting by country first and then city would create a very different arrangement than sorting by city first and then country. Notice how sorting first by country and then by city alphabetically arranges the museums by country. When there is more than one museum in a country, the museums are then arranged within that country group alphabetically by city.
If you want to sort by more than column in descending order, each of the columns must use the DESC keyword. Note that the DESC keyword only affects the column right before it in the ORDER BY clause. Suppose you want to list the name, city, and country from the museum table. Order the rows in reverse alphabetical order by country then alphabetically by city.
---[EVALUATE]---
"type":"plan",
"task":"Display a list of names, cities, and countries of museums. Sort the results first by country in reverse alphabetical order and then by city in alphabetical order.",
"columns":"name, city, country",
"tables":"museum",
"order":"By country in descending order then city in ascending order."
---[EVALUATE]---
The SELECT statement for this query would be:
SELECT name, city, country
FROM museum
ORDER BY country DESC, city;
---[EVALUATE]---
"type":"evaluate",
"query":"SELECT name, city, country FROM museum ORDER BY country DESC, city;"
---[EVALUATE]---
The query syntax is correct. The query will list the name, citym and country columns from the museum table. The ORDER BY clause correctly specifies that the rows will first be sorted by country in reverse alphabetical order and then by city in alphabetical order.
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:museum-name-country-desc-country-sorted
---[SQL]---
SELECT name, city, country
FROM museum
ORDER BY country DESC, city;
---[SQL]---
Notice that the museums in the USA are arranged at the top of the query result, because USA is the last country alphabetically on the Museum table. Also notice that the cities within the USA are arranged alphabetically. This happens because the keyword DESC only applies to the column directly before it in the ORDER BY clause - in this example Country. City is not affected by the DESC keyword, so the query result is sorted by city in ascending or alphabetical order.
---[SIDEBAR]---
"type":"caution",
"title":"Sorting Multiple Columns in Descending Order",
"text":"Make sure you include the keyword DESC after each column you wish to be sorted in descending order. Otherwise, the columns without the keyword DESC will be sorted in ascending order."
---[SIDEBAR]---
---[SIDEBAR]---
"type":"note",
"title":"Sorting by Columns Not in the SELECT Clause.",
"text":"Generally, the columns you use in the ORDER BY clause will also be listed in the SELECT clause to be shown in the query result. This is not required, however. You can sort by any column on the table, regardless of whether the columns is displayed in the query result and therefore listed in the SELECT clause."
---[SIDEBAR]---
## Sorting by Column Position
All of the examples of the ORDER BY clause have used column names for sorting. ORDER BY will also accept the position number of the columns in the SELECT clause in place of column names for sorting. In a previous example you selected the name, city, and country of the museums on the museum table in the database. These names were then arranged by country and then city, both in ascending (or alphabetical) order. The SELECT statement for this query is:
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:museum-name-city-country-sorted
---[SQL]---
SELECT name
,city
,country
FROM museum
ORDER BY country, city
---[SQL]---
This syntax can be modified to refer to column numbers in the ORDER BY clause rather than column names. The SELECT statement would be:
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:museum-name-city-country-sorted-3-2
---[SQL]---
SELECT name
,city
,country
FROM museum
ORDER BY 3, 2
---[SQL]---
Notice that the query results in the data being sorted first by country and then by city. Also, note the positioning of the columns in the SELECT clause. Name is listed first, city second, and country third. In the updated syntax, the ORDER BY clause is set to sort by column 3 (country) and then column 2 (city). This means that both queries will display the data identically.
Using column position rather than column names in the ORDER BY clause has one main advantage and some disadvantages. The main advantage is that you don't need to retype the column names in the ORDER BY clause after already typing them in the SELECT clause. Unfortunately, this approach increases the likelihood of choosing the wrong column for sorting. Also, if you change the order of the columns in the SELECT clause, you might forget to update the column numbers in the ORDER BY clause. Moreover, this approach makes the SQL statement a little harder to read. Finally, you cannot use the column position to sort data on a column that is not listed in the SELECT clause.
---[SIDEBAR]---
"type":"tip",
"title":"Sorting by Column Names and Column Numbers.",
"text":"You can use a combination of column names and column numbers in the same ORDER BY clause."
---[SIDEBAR]---
## Limiting Results
There are times that you want to retrieve only the first row or set of rows from a table. Unfortunately, the different database management systems have implemented this in different ways. A common way to retrieve only a few rows involves using the keyword LIMIT.
---[SIDEBAR]---
"type":"note",
"title":"LIMIT",
"text":"The keyword LIMIT will always appear as the last clause of a SELECT statement."
---[SIDEBAR]---
Suppose you want to retrieve the first five rows of the museum table.
---[EVALUATE]---
"type":"plan",
"task":"List the first five rows of the museum table.",
"columns":"All (*)",
"tables":"museum",
"rows":"The first five rows",
"order":"Not specified"
---[EVALUATE]---
The SQL statement used to retrieve the first five rows of the museum table is:
SELECT *
FROM museum
LIMIT 5;
---[EVALUATE]---
"type":"evaluate",
"task":"List the first five rows of the museum table.",
"query":"SELECT * FROM museum LIMIT 5;"
---[EVALUATE]---
All columns will be retrieved from the museum table. The syntax "LIMIT 5" ensures that the first five rows of the result will be displayed.
**Try the SQL Statement**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:limit
---[SQL]---
SELECT *
FROM museum
LIMIT 5;
---[SQL]---
Since no sorting order is specified for the query results, it is impossible to know which rows will be returned. For this reason, LIMIT is almost always applied to a query that is sorted. When LIMIT and ORDER BY are used together, the query will display rows that contain either the top (largest) or bottom (smallest) values for a column. For example, suppose you want to retrieve all information for the five artists who were born most recently.
---[EVALUATE]---
"type":"plan",
"task":"List all information for the ten artists who were born most recently.",
"columns":"All (*)",
"tables":"artist",
"rows":"The first five rows",
"order":"Descending by birth"
---[EVALUATE]---
The SELECT statement for this query is:
SELECT *
FROM artist
ORDER BY birth DESC
LIMIT 5;
---[EVALUATE]---
"type":"evaluate",
"query":"SELECT * FROM artist ORDER BY birth DESC LIMIT 5;"
---[EVALUATE]---
This query will produce the correct results. All columns will be retrieved from the artist table. The results are sorted by birth in descending order. This ensure that the artists born most recently will be the first rows displayed. The syntax LIMIT 5 will ensure that only the first five rows will be displayed. Since the results are ordered by birth in descending order, this will list the five artists who were born most recently.
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:5-most-recent-artists-born
---[SQL]---
SELECT *
FROM artist
ORDER BY birth DESC
LIMIT 5;
---[SQL]---
There are times that you want to retrieve only the first row or set of rows from a table. Unfortunately, the different database management systems have implemented this in different ways. A common way to retrieve only a few rows involves using the keywords FETCH FIRST *n* ROWS ONLY where 'n' is the number of rows to display.
---[SIDEBAR]---
"type":"note",
"title":"FETCH FIRST 'n' ROWS ONLY",
"text":"The keywords FETCH FIRST 'n' ROWS ONLY will always appear as the last clause of a SELECT statement."
---[SIDEBAR]---
Suppose you want to retrieve the first five rows of the museum table.
---[EVALUATE]---
"type":"plan",
"task":"List the first five rows of the museum table.",
"columns":"All (*)",
"tables":"museum",
"rows":"The first five rows",
"order":"Not specified"
---[EVALUATE]---
The SQL statement used to retrieve the first five rows of the museum table is:
SELECT *
FROM museum
FETCH FIRST 5 ROWS ONLY;
---[EVALUATE]---
"type":"evaluate",
"task":"List the first five rows of the museum table.",
"query":"SELECT * FROM museum FETCH FIRST 5 ROWS ONLY;"
---[EVALUATE]---
All columns will be retrieved from the museum table. The syntax "FETCH FIRST 5 ROWS ONLY" ensures that the first five rows of the result will be displayed.
**Try the SQL Statement**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:fetch
---[SQL]---
SELECT *
FROM museum
FETCH FIRST 5 ROWS ONLY;
---[SQL]---
Since no sorting order is specified for the query results, it is impossible to know which rows will be returned. For this reason, any limits to the number of rows retrieved will almost always applied to a query that is sorted. When the FETCH FIRST and ORDER BY keywords are used together, the query will display rows that contain either the top (largest) or bottom (smallest) values for a column. For example, suppose you want to retrieve all information for the five artists who were born most recently.
---[EVALUATE]---
"type":"plan",
"task":"List all information for the ten artists who were born most recently.",
"columns":"All (*)",
"tables":"artist",
"rows":"The first five rows",
"order":"Descending by birth"
---[EVALUATE]---
The SELECT statement for this query is:
SELECT *
FROM artist
ORDER BY birth DESC
FETCH FIRST 5 ROWS ONLY;
---[EVALUATE]---
"type":"evaluate",
"query":"SELECT * FROM artist ORDER BY birth DESC FETCH FIRST 5 ROWS ONLY;"
---[EVALUATE]---
This query will produce the correct results. All columns will be retrieved from the artist table. The results are sorted by birth in descending order. This ensure that the artists born most recently will be the first rows displayed. The syntax FETCH FIRST 5 ROWS ONLY will ensure that only the first five rows will be displayed. Since the results are ordered by birth in descending order, this will list the five artists who were born most recently.
**Try the SQL statement.**
---[SQL]---
connection:sql_book_connection
schema:canvas
diagram:canvas
owner:atlas-query
result:5-most-recent-artists-born-fetch
---[SQL]---
SELECT *
FROM artist
ORDER BY birth DESC
FETCH FIRST 5 ROWS ONLY;
---[SQL]---
## Summary
In this lesson, you learned how to use the ORDER BY clause in the SELECT statement to arrange the rows in a query result. Data can be sorted in ascending or descending order. It can also be sorted on multiple columns. Finally, you learned how to use the keyword LIMIT to display the first rows in a query result.