Beginners Guide to SQL – SQL ORDER BY Clause

(SQL Tutorials for Citizen Data Scientist)

SQL ORDER BY Clause

In this tutorial you will learn how to sort data returned by a SELECT query in SQL.

Ordering the Result Set

Generally when you use the SELECT statement to fetch data from a table, the rows in result set are not in any particular order. If you want your result set in a particular order, you can specify the ORDER BY clause at the end of the statement which tells the server how to sort the data returned by the query. The default sorting order is ascending.

Syntax

The ORDER BY clause is used to sort the data returned by a query in ascending or descending order. The basic syntax of this clause can be given with:

SELECT column_list FROM table_name ORDER BY column_name ASC|DESC;

Here, column_list are the names of columns/fields like nameagecountry etc. of a database table whose values you want to fetch, whereas the column_name is name of the column you want to sort. Let’s check out some examples that demonstrate how it actually works.

Consider we’ve an employees table in our database that has following records:

+--------+--------------+------------+--------+---------+
| emp_id | emp_name     | hire_date  | salary | dept_id |
+--------+--------------+------------+--------+---------+
|      1 | Ethan Hunt   | 2001-05-01 |   5000 |       4 |
|      2 | Tony Montana | 2002-07-15 |   6500 |       1 |
|      3 | Sarah Connor | 2005-10-18 |   8000 |       5 |
|      4 | Rick Deckard | 2007-01-03 |   7200 |       3 |
|      5 | Martin Blank | 2008-06-24 |   5600 |    NULL |
+--------+--------------+------------+--------+---------+

Sorting Single Column

The following SQL statement will return all the employees from the employees table and orders the result set by the emp_name column in ascending order.

Example

SELECT * FROM employees 
ORDER BY emp_name ASC;

You can skip the ASC option and simply use the following syntax. It returns the same result set as previous statement, because the default sorting order is ascending:

Example

SELECT * FROM employees 
ORDER BY emp_name;

After executing the above command, you’ll get the output something like this:

+--------+--------------+------------+--------+---------+
| emp_id | emp_name     | hire_date  | salary | dept_id |
+--------+--------------+------------+--------+---------+
|      1 | Ethan Hunt   | 2001-05-01 |   5000 |       4 |
|      5 | Martin Blank | 2008-06-24 |   5600 |    NULL |
|      4 | Rick Deckard | 2007-01-03 |   7200 |       3 |
|      3 | Sarah Connor | 2005-10-18 |   8000 |       5 |
|      2 | Tony Montana | 2002-07-15 |   6500 |       1 |
+--------+--------------+------------+--------+---------+

Similarly, you can use the DESC option to perform a sorting in descending order. The following statement will orders the result set by the numeric salary column in descending order.

Example

SELECT * FROM employees 
ORDER BY salary DESC;

This time, you’ll get the result set something like this:

+--------+--------------+------------+--------+---------+
| emp_id | emp_name     | hire_date  | salary | dept_id |
+--------+--------------+------------+--------+---------+
|      3 | Sarah Connor | 2005-10-18 |   8000 |       5 |
|      4 | Rick Deckard | 2007-01-03 |   7200 |       3 |
|      2 | Tony Montana | 2002-07-15 |   6500 |       1 |
|      5 | Martin Blank | 2008-06-24 |   5600 |    NULL |
|      1 | Ethan Hunt   | 2001-05-01 |   5000 |       4 |
+--------+--------------+------------+--------+---------+

Sorting Multiple Columns

You can also specify multiple columns while sorting. However, the change in result set will not visible until you’ve some duplicate values in your table. Well, let’s find out:

To understand the multi-column sorting in a better way, let’s assume that we’ve a table named trainees in our database with the following records:

+----+------------+------------+-------------+--------+
| id | first_name | last_name  | birth_date  | gender |
+----+------------+------------+-------------+--------+
|  1 | Peter      | Parker     | 1998-03-04  |  M     |
|  2 | Harry      | Potter     | 2001-08-30  |  M     |
|  3 | Peter      | Pan        | 2004-09-19  |  M     |
|  4 | Alice      | Kingsleigh | 1999-07-02  |  F     |
|  5 | John       | Connor     | 2002-01-15  |  M     |
+----+------------+------------+-------------+--------+

If you see the table carefully, you’ll find that we’ve some duplicate values. However, the full name of the trainee “Peter Parker” and “Peter Pan” are different but their first names are same.

Now execute the following command which orders the result set by the first_name column.

Example

SELECT * FROM trainees 
ORDER BY first_name;

After execution, you’ll get the output something like this:

+----+------------+------------+-------------+--------+
| id | first_name | last_name  | birth_date  | gender |
+----+------------+------------+-------------+--------+
|  4 | Alice      | Kingsleigh | 1999-07-02  |  F     |
|  2 | Harry      | Potter     | 2001-08-30  |  M     |
|  5 | John       | Connor     | 2002-01-15  |  M     |
|  1 | Peter      | Parker     | 1998-03-04  |  M     |
|  3 | Peter      | Pan        | 2004-09-19  |  M     |
+----+------------+------------+-------------+--------+

Now execute this statement which orders the result set by first_name and last_name columns.

Example

SELECT * FROM trainees 
ORDER BY first_name, last_name;
+----+------------+------------+-------------+--------+
| id | first_name | last_name  | birth_date  | gender |
+----+------------+------------+-------------+--------+
|  4 | Alice      | Kingsleigh | 1999-07-02  |  F     |
|  2 | Harry      | Potter     | 2001-08-30  |  M     |
|  5 | John       | Connor     | 2002-01-15  |  M     |
|  3 | Peter      | Pan        | 2004-09-19  |  M     |
|  1 | Peter      | Parker     | 1998-03-04  |  M     |
+----+------------+------------+-------------+--------+

Did you notice the difference between the previous and the current result set — this time the record of the trainee “Peter Parker” comes after the “Peter Pan”.

Since the first name of both the trainees are same which is “Peter”, so the second level ordering is performed at the last_name column for these two trainees that’s why the record of the trainee “Peter Parker” comes after the “Peter Pan”.

 

Beginners Guide to SQL – SQL ORDER BY Clause

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!