SQL ORDER BY - GeeksforGeeks (2024)

SQL ORDER BY clause sorts the result of the SELECT statement either in ascending or descending order.

In this article, we’ll explore the ORDER BY clause, exploring its syntax, functionality, and usage with detailed examples.

ORDER BY in SQL

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns.It is very useful to present data in a structured manner.

SQL ORDER BY default mode is sorting data into ascending order. To sort data in descending order use the DESC keyword with ORDER BY clause.

Syntax

The syntax to use ORDER BY clause in SQL is:

SELECT * FROM table_name ORDER BY column_name ASC | DESC

Key Terms:

  • table_name: name of the table.
  • column_name: name of the column according to which the datais needed to be arranged.
  • ASC: to sort the data in ascending order.
  • DESC: to sort the data in descending order.

SQL ORDER BY Clause Examples

Let’s look at some examples of the SQL ORDER BY clause to understand it’s working in SQL.

We will use the following table in examples.

SQL ORDER BY - GeeksforGeeks (1)

Student_Table

To create this table, write the following SQL queries:

SQL
CREATE TABLE students ( roll_no INT NOT NULL, age INT NOT NULL, name VARCHAR(50) NOT NULL, address VARCHAR(100) NOT NULL, phone VARCHAR(20) NOT NULL, PRIMARY KEY (roll_no));INSERT INTO students (roll_no, age, name, address, phone)VALUES  (1, 18, 'Shubham Thakur', '123 Main St, Mumbai', '9876543210'), (2, 19, 'Aman Chopra', '456 Park Ave, Delhi', '9876543211'), (3, 20, 'Naveen Tulasi', '789 Broadway, Ahmedabad', '9876543212'), (4, 21, 'Aditya arpan', '246 5th Ave, Kolkata', '9876543213'), (5, 22, 'Nishant Jain', '369 3rd St, Bengaluru', '9876543214')

Now consider the above database table and find the results of different queries.

Sort According To a Single Column using ORDER BY Clause Example

In this example, we will fetch all data from the table Student and sort the result in descending order according to the column ROLL_NO.

Query:

SELECT * FROM students ORDER BY ROLL_NO DESC;

Output:

SQL ORDER BY - GeeksforGeeks (2)

In the above example, if we want to sort in ascending order we have to use ASC in place of DESC.

Sort According To Multiple Columns using ORDER BY Clause Example

To sort according to multiple columns, separate the names of columns by the (,) operator.

Syntax:

SELECT * FROM table_name ORDER BY column1 ASC|DESC , column2 ASC|DESC

In this example, we will fetch all data from the table Student and then sort the result in descending order first according to the column age. and then in ascending order according to the column name.

Query:

SELECT * FROM students ORDER BY age DESC , name ASC;

Output:

SQL ORDER BY - GeeksforGeeks (3)

Sort_Multiple_Column

In the above output, we can see that first the result is sorted in descending order according to Age. There are multiple rows of having the same Age. Now, sorting further this result-set according to name will sort the rows with the same Age according to name in ascending order.

Note:

ASC is the default value for the ORDER BY clause. So, if we don’t specify anything after the column name in the ORDER BY clause, the output will be sorted in ascending order by default.

Sorting By Column Number (instead of name)

An integer that identifies the number of the column in theSelectItemsin the underlying query of theSELECT statement.Columnnumbermust be greater than 0 and not greater than the number of columns in the result table. In other words, if we want to order by a column, that column must be specified in the SELECT list.

The rule checks for ORDER BY clauses that reference select list columns using the column number instead of the column name. The column numbers in the ORDER BY clause impair the readability of the SQL statement. Further, changing the order of columns in the SELECT list has no impact on the ORDER BY when the columns are referred to by names instead of numbers.

Syntax

The Syntax to use ORDER BY Clause with Column Number

ORDER BY Column_Number asc/desc

Sorting By Column Number Example

Here we take an example to sort a database table according to column 1 i.e Roll Number. For this a query will be:

Query:

CREATE TABLE studentinfo( Roll_no INT,NAME VARCHAR(25),Address VARCHAR(20),CONTACTNO BIGINT NOT NULL,Age INT ); INSERT INTO studentinfoVALUES (7,'ROHIT','GHAZIABAD',9193458625,18),(4,'DEEP','RAMNAGAR',9193458546,18),(1,'HARSH','DELHI',9193342625,18),(8,'NIRAJ','ALIPUR',9193678625,19),(5,'SAPTARHI','KOLKATA',9193789625,19),(2,'PRATIK','BIHAR',9193457825,19),(6,'DHANRAJ','BARABAJAR',9193358625,20),(3,'RIYANKA','SILIGURI',9193218625,20);SELECT Roll_no, Name, AddressFROM studentinfoORDER BY 1

Output:

SQL ORDER BY - GeeksforGeeks (4)

Sorting By Column Number

Explanation:

ORDER BY 1 means sorting values according to first column in the SELECT statement.

Important Points About ORDER BY Clause in SQL

  • The ORDER BY clause in SQL is used to sort the result set of a SELECT statement based on specified columns.
  • It is essential for organizing query results and presenting data in a structured manner.
  • It can sort data in either ascending (ASC) or descending (DESC) order.
  • Multiple columns can be specified for sorting, allowing for more complex sorting criteria.
  • We can use ORDER BY with WHERE clause, GROUP BY clause, and HAVING clause.


SQL ORDER BY - GeeksforGeeks (5)

GeeksforGeeks

Improve

Previous Article

SQL HAVING Clause with Examples

Next Article

SQL | GROUP BY

Please Login to comment...

SQL ORDER BY - GeeksforGeeks (2024)

FAQs

What is ORDER BY in SQL? ›

The ORDER BY command is used to sort the result set in ascending or descending order. The ORDER BY command sorts the result set in ascending order by default. To sort the records in descending order, use the DESC keyword.

What is the correct order of a SQL? ›

It also helps to predict the outcome of queries, troubleshoot issues, and optimize performance. What is the correct order of execution for a given query? The correct order of execution in SQL is FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT.

What is the difference between GROUP BY and ORDER BY? ›

A GROUP BY statement sorts data by grouping it based on column(s) you specify in the query and is used with aggregate functions. An ORDER BY allows you to organize result sets alphabetically or numerically and in ascending or descending order.

What is the ORDER BY rule in SQL? ›

The ORDER BY clause in SQL is used to sort the result set of a SELECT statement based on specified columns. It is essential for organizing query results and presenting data in a structured manner. It can sort data in either ascending (ASC) or descending (DESC) order.

What is the advantage of ORDER BY in SQL? ›

Benefits and Use Cases

The Order by Clause is advantageous for data processing and analytics because it: Improves data readability by organizing query results in a logical order. Enables efficient identification of trends and patterns by sorting data based on specific criteria.

What is ORDER BY vs sort in SQL? ›

The difference between "order by" and "sort by" is that the former guarantees total order in the output while the latter only guarantees ordering of the rows within a reducer.

Can we use ORDER BY without GROUP BY? ›

When we want to form a group of rows, we use the GROUP BY clause. If we want to organize data in ascending or descending order based on a particular column, we use the ORDER BY clause. They do not have any relationship because both are used for two different purposes.

Does ORDER BY come first or GROUP BY SQL? ›

The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

Can you use both GROUP BY and ORDER BY? ›

Both GROUP BY and ORDER BY are clauses (or statements) that serve similar functions; that is to sort query results. However, each of these serve very different purposes; so different in fact, that they can be employed separately or together.

Can we have two ORDER BY in SQL? ›

You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence. The following query and Figure 3 and the corresponding query results show nested sorts.

What comes after ORDER BY in SQL? ›

The first thing you'll learn in SQL is the order in which we write various clauses in our queries (SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, then LIMIT).

Can we use ORDER BY without WHERE clause? ›

The ORDER BY clause can be optionally followed by a LIMIT clause. Note: ORDER BY is not part of a WHERE clause and therefore cannot be used in filter expressions for iterators. TIBCO recommends using columns in the ORDER BY clause which are columns of a primary or secondary index defined for the table.

What is an example of ORDER BY clause? ›

ORDER BY Example

SELECT * FROM customers ORDER BY customer_name ASC; This query selects all columns from the customer's table and orders the results alphabetically by the customer_name column in ascending order (A-Z).

What is ORDER BY 4 in SQL? ›

You also may notice that the number 4 is specified in the order by clause. The number 4 specifies the position of the columns in the SQL query. In this case, position of BusinessEntityID is 1, FirstName is 2, MiddleName is 3 and LastName is 4.

What is ORDER BY 2 in SQL? ›

It means that if you have a table which consists of columns say Name, age, city, gender. Where age is the second column, then order by 2 will arrange the second column in ascending order. Here , age being the second column.

What is ORDER BY case in SQL? ›

SQL order by case can be used when we have to order the data on a conditional basis and define the criteria on which the ordering will be done based on a certain condition.

References

Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated:

Views: 5418

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.