ORDER BY in SQL

In this tutorial we are going to learn about what is Order By in SQL and how we are going to use the order by as well as what are the conditions when we have to use the order by. so let's start.

Order by clause is used in the query when we need the rows in a sorted manner during the result. Order by clause plays an important role during performing the task, it will help to increase the readability of the output.

Now let's see the syntax of the ORDER BY and some examples to see how we can use the Order By in the query. 

Syntax:

Select

[Column Name]

from

[Table Name]

Order By

[Name of the column by which you want to order the rows ],[ASC | DESC]

In the SQL Syntax

Now we are going to understand the syntax one by one

Select: Select command for selecting the column names

[Column Name]: Specify the names of the columns which you needed in the result set.

[Table Name]: Name of the table.

Order by: Order by clause.

[Name of the column]: Name of the columns by which row should be ordered.

  • Column Name Expression: Column names plays an important role in the ORDER BY. By this, you can define how you can order the rows according to the column name. You can order the rows by more than 1 column. ORDER BY more than the column, the first column order the rows and according to that other columns will order the rows.

Order 1, Order 2, Order 3

Order 1, Order 2, or Order 3 is the way by which we can represent the column in the selected list. 

Example:

Select Name from TblEmployee 
Order by Department

Select Name from TblEmployee 
Order by Column 4

SQL ORDER BY Clause Examples

A. Sorting the result set by using a single column in ascending order (ASC).

For seeing the ORDER BY ascending order we will use the following table as given below.


Use Case in ORDER BY 

Questions

Q.1 Can we use the aggregate function during the ORDER BY?

Ans. No

Q.2 Can we use ORDER BY when the column has the null values?

Ans.

Q.3 Can the ORDER BY clause work with the column containing the null values or at least one null value ?

Note:

1. Order by arranging the rows in the ascending ORDER BY default.

2. There is no need for a function for implementing the using the ORDER BY clause like group by.

3. Aggregate function can not be used in the ORDER BY directly, but we can use the aqqreqate function in ORDER BY by specifying the specific column name or entity in a table.

0 Comments