0% found this document useful (0 votes)
25 views

SQL Order By

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

SQL Order By

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

SQL ORDER BY

Sorting the result after extracting the data from the dataset is one of the most basic thing we do to
get the pattern or highest/lowest values in a particular field (column). In SQL sorting is done
using ORDER BY clause. So in this article we will explore how to use ORDER BY clause in
SQL.

SQL ORDER BY
SQL ORDER BY clause is used after the WHERE clause (i.e. after filtering the data) to sort the
result in either Ascending or Descending order.
ASC: Keyword is used to arrange the result in Ascending Order
DESC: Keyword is used to arrange the result in Descending Order.
Note:
 Ascending is a default sort order.
 ORDER BY clause comes after the WHERE, GROUP BY, and HAVING clause (if present
in query)

Syntax:
SELECT column_list
FROM table_name
WHERE conditions
ORDER BY column_names [ASC | DESC];

Now we will use the Employee dataset (that contains Employee ID, Name, Gender, Department,
Education, Month of Joining, and CTC) to do some examples to get a clear understanding of how
to use the ORDER BY clause in SQL.

Employee ID Name Gender Department Education Month of Joining CTC(in Lacs)


1001 Ajay M Engineering Doctoral January 25
1002 Babloo M Engineering UG February 23
1003 Chhavi F HR PG March 15
1004 Dheeraj M HR UG January 12
1005 Evina F Marketing UG March 16
1006 Garima M Sales UG December 10
1007 Fredy F Sales PG March 10
1008 Hans M Admin PG November 8
1009 Ivanka F Admin Intermediate April 7
1010 Jai M Peon December 4
Sort According to Single Column
Example 1: Arrange the CTC of the employee in descending order.
Query
SELECT *
FROM Employee
ORDER BY CTC DESC;

Output
Employee ID Name Gender Department Education Month of Joining CTC(in Lacs)
1001 Ajay M Engineering Doctoral January 25
1002 Babloo M Engineering UG February 23
1005 Evina F Marketing UG March 16
1003 Chhavi F HR PG March 15
1004 Dheeraj M HR UG January 12
1006 Garima M Sales UG December 10
1007 Fredy F Sales PG March 10
1008 Hans M Admin PG November 8
1009 Ivanka F Admin Intermediate April 7
1010 Jai M Peon December 4

ORDER BY with WHERE


Example 2: Arrange the CTC (in decreasing) of the employees who joined in the month of
March.
Query
SELECT *
FROM Employee
WHERE Month of Joining= ‘March’
ORDER BY CTC DESC;
Output
Employee ID Name Gender Department Education Month of Joining CTC(in Lacs)
1005 Evina F Marketing UG March 16
1003 Chhavi F HR PG March 15
1007 Fredy F Sales PG March 10
Sort According to Multiple Columns
Example 3: Sort the employee table:
 CTC in Descending Order
 Name in Ascending Order
SELECT *
FROM Employee
WHERE Department IN (‘Engineering’, ‘Marketing’, ‘Sales’)
ORDER BY CTC DESC, Name ASC;
Output
Employee ID Name Gender Department Education Month of Joining CTC(in Lacs)
1001 Ajay M Engineering Doctoral January 25
1002 Babloo M Engineering UG February 23
1005 Evina F Marketing UG March 16
1006 Fredy M Sales UG December 10
1007 Garima F Sales PG March 10

Now if you look closely, you will get that firstly the result is sorted in descending order
of CTC and since in the sales department both the employees are getting the same salary (10
lacs). So sorting further the result according to the Name will sort the rows with the same CTC
according to Name in Ascending Order.

Note
 In the ORDER BY clause, instead of using the Column name, you can use column number
 Using the ORDER BY clause, you can sort the results on a column not defined in the
SELECT statement.

Order of Execution in SQL


SQL, or Structured Query Language, is a standard language for managing data
(create/read/update/delete) in a relational database. Using SQL, you can create a new table (or
database) and insert, update, retrieve, or delete data from the existing table.
However, you must follow an order when writing any SQL query to fetch or insert data from the
table. The order of Execution in SQL is similar to the mathematical operation BODMAS.

Defining Order of Execution in SQL


An SQL query comprises various clauses like SELECT, FROM, WHERE, GROUPBY,
HAVING, and ORDERBY clauses. Each clause has a specific role in the query. Let’s understand
each of them briefly.
When you write any query, your query is processed in the following steps:
 Getting Data (FROM/JOIN)
 Row Filter (WHERE)
 Grouping (GROUP BY)
 Group Filter (HAVING)
 Return Expression (SELECT)
 Order & Paging (ORDER BY & LIMIT/OFFSET)
Clause Function
When you write any query, SQL starts by identifying the tables for the data retrieval
FROM / JOIN
and how they are connected.
WHERE It acts as a filter; it filters the record based on the conditions specified by the users.
GROUP BY The filtered data is grouped based on the specified condition.
HAVING It is similar to the WHERE clause but applied after grouping the data.
SELECT The clause selects the columns to be included in the final result.
Remove the duplicate rows from the result. Once you apply this clause, you are
DISTINCT
only left with distinct records.
It sorts the results (increasing/decreasing/A->Z/Z->A) based on the specified
ORDER BY
condition.
LIMIT /
It determines the number of records to return and from where to start.
OFFSET

Let’s consider a simple dataset with two tables: Customers and Orders.
 The Customers table has 5 columns: customer_id, first_name, last_name, age, and country.
 Orders Table has 4 columns: order_id, item, amount, customer_id

Customers Table
customer_id first_name last_name age country
1 John Doe 31 USA
2 Robert Luna 22 USA
3 David Robinson 22 UK
4 John Reinhardt 25 UK
5 Betty Doe 28 UAE
Orders Table
order_id item amount customer_id
1 Keyboard 400 4
2 Mouse 300 4
3 Monitor 12000 3
4 Keyboard 400 1
5 Mousepad 250 2

Problem Statement: Find the amount spent by each customer in the USA.
SELECT Customers.first_name, Customers.last_name, SUM(Orders.Amount) as Amount
FROM Customers
JOIN Orders ON Customers.customer_id = Orders.customer_id
WHERE Customers.country = 'USA'
GROUP BY Customers.first_name, Customers.last_name
ORDER BY Amount DESC;
Output
first_name last_name Amount
John Doe 400
Robert Luna 250

Explanation
 FROM and JOIN: We start by identifying the ‘Customers‘ and ‘Orders‘ tables and joining
them on ‘customer_id‘.
 WHERE: It will filter the record to include only those where ‘country‘ = ‘USA‘.
 GROUP BY: Group the remaining entries (after filtering by WHERE clause) by ‘first_name‘
and ‘last_name‘.
 SELECT: SELECT the ‘first_name‘, ‘last_name‘, and the sum of ‘Amount‘ for each group.
 ORDER BY: Finally, the result is sorted by ‘Amount‘ in descending order.

Case-1: Let you want to filter the record based on the ‘Amount’ using the WHERE clause.
SELECT Customers.first_name, Customers.last_name, SUM(Orders.Amount) as Amount
FROM Customers
JOIN Orders ON Customers.customer_id = Orders.customer_id
WHERE Orders.Amount >300
GROUP BY Customers.first_name, Customers.last_name
ORDER BY Amount DESC;
Output
first_name last_name Amount
David Robinson 12000
John Doe 400
John Reinhardt 400

Case-2: Filter the record based on the ‘Amount’ using the HAVING clause.
SELECT Customers.first_name, Customers.last_name, SUM(Orders.Amount) as Amount
FROM Customers
JOIN Orders ON Customers.customer_id = Orders.customer_id
GROUP BY Customers.first_name, Customers.last_name
HAVING Amount > 300
ORDER BY Amount DESC;
Output
first_name last_name Amount
David Robinson 12000
John Reinhardt 700
John Doe 400

Now, let’s see what happened in both cases:


Since the WHERE clause is processed before the SELECT clause in the Order of Execution, so,
in the first case, SQL won’t recognize the Amount and will give the error.
It just filters out the record of the customer who purchased orders greater than 300.
However, the best way to filter the aggregate function is to use the HAVING clause.
Since the HAVING clause is processed after the GROUP BY clause. So, in the second case, the
HAVING clause filters the group to include only those where the total Amount is greater than
300.
Tips for Writing Efficient SQL Queries
 The first thing you must know while writing the SQL queries is the correct order of SQL query
execution.
 Since a lot of people think SQL processes queries from top to bottom as they have written.
 But SQL processes queries in the order: FROM, JOIN, WHERE, GROUP BY, HAVING,
SELECT, DISTINCT, ORDER BY, and finally, LIMIT/OFFSET.
 One of the common mistakes is using aliases defined in the SELECT clause within the
WHERE clause.
 Because SQL processes the WHERE clause before the SELECT clause.
 Use the HAVING clause if you need to filter your query based on the result of an aggregate
function.
 While joining multiple tables, start with the smallest table or the table that allows you to filter
out the most data early on.

You might also like