In this post, we aim to learn how to sort data using ORDER BY since data returned using filters is presented randomly.
Learning Objectives:
- Discuss the importance of sorting data for analysis.
- Explain rules related to using ORDER BY.
- Use ORDER BY to sort data in ascending or descending order.
Why Sort Data?
- Data displayed appears in the order of underlying tables.
- Updated and deleted data can change this order.
- The sequence of reviewed data cannot be assumed if the order was not specified.
- Sorting data helps keep the order logical.
- ORDER BY can allow users to sort data by a particular column
Rules for ORDER BY.
- Takes the name of one or more columns.
- Add a comma after each additional column name.
- Can sort by a column not retrieved.
- Must always be the last clause in a SELECT statement.
Here is an example below:
SELECT product_name
FROM products
ORDER BY product_price
Sorting by Column Position.
You can sort by the name of the column or the position like below:
ORDER BY 2, 3
2 means 2nd column.
3 means 3rd column etc.
Sort Direction.
We can sort the direction of the data by using DESC or ASC. These stand for descending and ascending.
Here is an example:
SELECT *
FROM customers
ORDER BY country DESC;