How to analyze data with SQL: ORDER BY


SELECT 
       * 
  FROM 
       My_Table
 ORDER BY 
       Column_1;

In the previous post, we looked at four basic SQL statement clauses SELECT, FROM, WHERE, and LIMIT with some simple examples. We saw how SELECT can be used alone to perform math calculations and to select the columns we want to be returned in our query results. Then, we added FROM to tell SQL which table to use for our query, and we used WHERE to filter on the rows we want to look at and LIMIT to limit our results to a specified number so we can save on our computing power when we are just exploring our data.

In this post, we’re going to expand on these basic SQL statements by introducing some new clauses and functionalities.

ORDER BY – ORDER BY is another basic SQL clause where you can specify which column or columns to use to sort your results. When you add this clause, you can also choose to have your results in ascending or descending order.

ORDER BY column_name;

You can order your results by a specific column in ascending order by just specifying the column. By default, ORDER BY will order your results in ascending order if you do not specify. Otherwise, you can specify by writing the keyword ASC for ascending and DESC for descending.

ORDER BY column_name ASC;
ORDER BY column_name DESC;

Additionally, you can sort by multiple columns by separating them with a comma. ORDER BY will order your results in the order that you place the columns.

ORDER BY column_name1, column_name2 DESC;

In this example, ORDER BY will first order your results by the first column in ascending order, and then by the second column in descending order.

EXAMPLE

SELECT * 
  FROM inventory
 ORDER BY quantity DESC;
Here we ordered by quantity descending and we can see that we have more of product3, then 4 and so on.

CONCLUSION

Use ORDER BY to arrange your results in a way that will reveal patterns more easily and make more sense for your analysis by making use of ascending and descending.