The Wayback Machine - https://web.archive.org/web/20241004123547/https://www.geeksforgeeks.org/mysql-order-by-clause/
Open In App

MySQL ORDER BY Clause

Last Updated : 12 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In MySQL, the ORDER BY Clause is used to sort the result set either in ascending order or descending order. By default, the ORDER BY sorts the displayed data in ascending order. If you want your data displayed in descending order we need to use the DESC keyword along with the ORDER BY Clause.

To make any analysis, sorted data can save much time and that can be achieved by ORDER BY Clause. It is very useful in organizing displayed data in a very meaningful way.

ORDER BY Clause

The ORDER BY Clause in MySQL is a powerful tool that allows you to sort the result set of a query in ascending or descending order based on one or more columns.

It is an essential part of querying databases when you want to retrieve data in a specific order. In this article, we will explore the syntax and usage of the MySQL ORDER BY Keyword.

Syntax:

SELECT column1, column2, ...
FROM table
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;

Where,

  • ASC (default): Sorts the result set in ascending order.
  • DESC: Sorts the result set in descending order.

Demo MySQL Database

We will be using the following MySQL table for our examples on ORDER BY.

mysql table
table – geeksforgeeks

To use this table on your system, write the following MySQL queries:

Create Table:

CREATE TABLE geeksforgeeks(
user_id varchar(100) PRIMARY KEY,
name varchar(100),
rank int,
courses_enrolled int,
questions_solved int
);

Insert the value in geeksforgeeks Table:

INSERT INTO geeksforgeeks(user_id,name,rank,courses_enrolled,questions_solved)
VALUES('vish3001','Vishu',01,10,150);

INSERT INTO geeksforgeeks(user_id,name,rank,courses_enrolled,questions_solved)
VALUES('neeraj119','Neeraj',02,09,125);

INSERT INTO geeksforgeeks(user_id,name,rank,courses_enrolled,questions_solved)
VALUES('ayush105','Aayush',03,08,110);

INSERT INTO geeksforgeeks(user_id,name,rank,courses_enrolled,questions_solved)
VALUES('sumit85','Sumit',04,07,100);

INSERT INTO geeksforgeeks(user_id,name,rank,courses_enrolled,questions_solved)
VALUES('harsh05','Harsh',05,06,95);

ORDER BY Clause Examples

Now let’s look at some examples of the ORDER BY clause, and understand its workings in different scenarios.

Example 1: ORDER BY CLAUSE Using ASC/DESC Attribute

We can use the ASC attribute to sort in ascending order and the DESC attribute to sort in descending order. These are both very useful attributes of the ORDER BY clause.

  • Using ASC Attribute

CASE 1: Let’s sort the displayed data in the table in ascending order for the “courses enrolled” column, but for this time we are going to use the ASC keyword along with the ORDER BY clause.

Query:

SELECT * from 
geeksforgeeks ORDER BY courses_enrolled ASC;

Output:

order by with asc attribute
Result – CASE 01

Explanation: The query retrieves all columns from the geeksforgeeks table and sorts the results in ascending order based on the courses_enrolled column. Rows with fewer courses enrolled appear first, followed by those with more courses.

  • Using DESC Attribute

CASE 2: Let’s sort the displayed data with respect to the courses enrolled column but this time we are displaying the data in descending order.

Query

SELECT * FROM 
geeksforgeeks ORDER BY courses_enrolled DESC;

Output:

order by with desc attribute
Result – CASE 02

Explanation: The query retrieves all columns from the geeksforgeeks table and sorts the results in descending order based on the courses_enrolled column. Rows with fewer courses enrolled appear first, followed by those with more courses.

Example 2: ORDER BY CLAUSE With Multiple Columns

In this example, we are going to implement ORDER BY clause in multiple columns in a single query.

Before implementing this we will add some more data in our table with duplicate ranks for a clear understanding of how this will work with multiple columns.

Query:

INSERT INTO geeksforgeeks(user_id,name,rank,courses_enrolled,questions_solved)
VALUES('vaibhav455','Vaibhav',05,08,110);

INSERT INTO geeksforgeeks(user_id,name,rank,courses_enrolled,questions_solved)
VALUES('karan565','Karan',05,07,100);

Now let’s implement our query of the ORDER BY clause in multiple columns

Query:

SELECT * FROM geeksforgeeks
ORDER BY rank, name desc;

Output:

orderby clause with multiple columns
Output – Order By in Multiple Columns

Here sorting of data displayed is done on a priority basis. Let’s see how this works

  • First, Sorting by rank in ascending order.
  • For rows with equal rank, sorting by name in descending order.

We can conclude this, the first column which is mentioned, after the ORDER BY clause gets higher priority than the next mentioned column, and so on..

Example 3: ORDER BY CLAUSE With NULL VALUES

To implement this example we need to add some NULL values in the rank column.

Lets update rank column values to NULL for user id = ‘ayush105’ or user id = ‘harsh05’. We will use the UPDATE statement to achieve this task.

Query:

UPDATE geeksforgeeks
SET rank = NULL
WHERE user_id = 'ayush105' or user_id = 'harsh05';

Now let’s display our table values in ascending order with respect to the rank column.

Query:

SELECT * 
from geeksforgeeks ORDER BY rank;

Output:

orderbynull
Output – ORDER BY NULL Values

Explanation: In MYSQL, NULL values are considered lower than any other non-NULL values. In the above example, we can observe that all the rows with NULL values in their rank column appeared first followed by non-null values in ascending order.

Conclusion

The MySQL ORDER BY clause is used to sort the result set by one or more columns in ascending (ASC) or descending (DESC) order. It helps organize data in a meaningful way, making it easier to analyze and understand. Proper use of the ORDER BY clause enhances data retrieval efficiency and readability.

FAQs on MySQL ORDER BY Clause

What is the MySQL ORDER BY clause?

The ORDER BY clause is used to sort the result set of a query by one or more columns in ascending (ASC) or descending (DESC) order.

How do you sort results in ascending order using ORDER BY?

By default, the ORDER BY clause sorts results in ascending order. You can explicitly specify ascending order using ORDER BY column_name ASC.

How do you sort results in descending order using ORDER BY?

To sort results in descending order, use the DESC keyword: ORDER BY column_name DESC.

Can you sort by multiple columns using ORDER BY?

Yes, you can sort by multiple columns by listing them separated by commas: ORDER BY column1 ASC, column2 DESC.



Previous Article
Next Article

Similar Reads

Difference Between Having Clause and Group by Clause
GROUP BY clause is used to aggregate rows with identical values appearing in specified columns. This clause is often used with aggregate functions like SUM, COUNT, MAX, MIN,Group etc. The HAVING clause filters groups of the GROUP BY clause and makes it possible to filter rows at the group level without destroying the information in the groups. In t
5 min read
Parameterize an MySQL IN Clause
In MySQL, the IN clause is a powerful tool for filtering data based on a specified list of values. To enhance flexibility and security, parameterizing the IN clause is a recommended practice. In this article, we will understand the Parameterize a MySQL IN clause with the practice of parameterizing a MySQL IN clause. We'll break down the syntax invo
5 min read
MySQL Can't Specify Target Table For Update in FROM Clause
The "MySQL can't specify target table for update in FROM clause" error is a common challenge encountered when attempting to update a table based on a subquery that refers to the same table in the FROM clause. This restriction is in place to prevent ambiguous or unintended updates that might arise from self-referencing subqueries. So, in this articl
3 min read
INNER JOIN ON vs WHERE clause in MySQL
When working with MySQL queries that involve multiple tables, understanding how to effectively use INNER JOIN ON versus the WHERE clause can significantly impact query performance and clarity. These two SQL constructs serve distinct purposes in combining data from different tables based on specific conditions. In this article, we will explore the d
5 min read
MySQL WHERE Clause
The MySQL WHERE clause is essential for filtering data based on specified conditions and returning it in the result set. It is commonly used in SELECT, INSERT, UPDATE, and DELETE statements to work on specific data. This clause follows the FROM clause in a SELECT statement and precedes any ORDER BY or GROUP BY clauses. Within the WHERE clause, you
5 min read
MySQL DISTINCT Clause
When working with databases, you often need to filter out duplicate records to get a clear and accurate result set. MySQL offers a straightforward solution for this with the DISTINCT clause. This clause helps you retrieve only unique rows from your query results, making it an essential tool for data analysis and reporting. In this article, we'll ex
4 min read
MySQL LIMIT Clause
MySQL consists of various clauses for performing efficient data retrieval, and the LIMIT clause is essential for controlling the number of rows returned in a query. By specifying a limit on the number of results, the LIMIT clause helps manage large datasets, optimize performance, and focus on relevant data. This article will explore the LIMIT claus
4 min read
MySQL HAVING Clause
In MySQL, the HAVING clause is used in conjunction with the GROUP BY clause to filter the results of a query based on aggregate functions. It provides a way to apply conditions to the grouped results, which cannot be achieved using the WHERE clause alone. The HAVING clause is essential when you need to filter groups of data that are returned by a G
3 min read
MySQL Group By Clause
In MySQL, the GROUP BY clause is a powerful tool for grouping rows with the same values into summary rows, enabling efficient data analysis. It is often used with aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform calculations on grouped data. In this article, We will learn about the MySQL Group By Clause by the understanding with th
4 min read
SQLite ORDER BY Clause
SQLite is the most popular database engine which is written in C programming language. It is a serverless, easy-to-use relational database system and it is open source and self-contained. In this article, you will gain knowledge on the SQLite ORDER BY clause. By the end of this article, you will get to know how to use the ORDER BY clause, where to
8 min read
PL/SQL ORDER BY Clause
In PL/SQL, the ORDER BY clause is a vital tool that allows for the sorting of query results by one or more columns, either in ascending or descending order. In this article, We will learn about ORDER BY clause in PL/SQL, its syntax, functionality, and practical usage through examples. Understanding ORDER BY in PL/SQLThe ORDER BY clause in PL/SQL is
8 min read
Using CASE in ORDER BY Clause to Sort Records By Lowest Value of 2 Columns in SQL
The CASE statement in SQL is a versatile tool for implementing conditional logic within queries, similar to IF-THEN-ELSE constructs in programming languages. The ORDER BY clause in SQL is used to sort the results of a query based on one or more columns, enhancing data readability and analysis. In this guide, we'll explore how to use the CASE statem
3 min read
Functions in MySQL | Numeric, String and Date Time Functions in MySQL
In MySQL, functions play a crucial role in performing various operations on data, such as calculations, string manipulations, and date handling. These built-in functions simplify complex queries and data transformations, making it easier to manage and analyze data within a database. In this article, we will look at these different categories of MyS
4 min read
WHERE Clause in MariaDB
MariaDB uses SQL (Structured Query Language) and it is an open-source relational database management system (RDBMS) for managing and manipulating data. The WHERE clause in SQL queries is used to filter and obtain specific data. The ability to remove and retrieve specific data using the WHERE clause in SQL queries is one of the main features that ma
3 min read
BETWEEN Clause in MariaDB
MariaDB uses SQL (Structured Query Language) and is an open-source relational database management system (RDBMS) for managing and manipulating data. With the help of the MariaDB DISTINCT clause, you can efficiently extract unique values ​​from a given column or collection of columns in query results. In SELECT queries, this clause is frequently use
2 min read
DISTINCT Clause in MariaDB
MariaDB uses SQL (Structured Query Language) and is an open-source relational database management system (RDBMS) for managing and manipulating data. With the help of the MariaDB DISTINCT clause, you can efficiently extract unique values ​​from a given column or collection of columns in query results. In SELECT queries, this clause is frequently use
2 min read
LIKE Clause in MariaDB
The LIKE clause is a powerful tool in database querying that allows users to perform flexible and dynamic searches based on pattern matching. In MariaDB, the LIKE clause is a valuable asset for searching and retrieving data from tables. The features, syntax, and effective uses of the LIKE clause in MariaDB will all be covered in this article. LIKE
3 min read
SQL Server - OVER Clause
The OVER clause is used for defining the window frames of the table by using the sub-clause PARTITION, the PARTITION sub-clauses define in what column the table should be divided into the window frames. The most important part is that the window frames are then used for applying the window functions like Aggregate Functions, Ranking functions, and
6 min read
SQLite WHERE Clause
SQLite is the serverless database engine that is used most widely. It is written in c programming language and it belongs to the embedded database family. In this article, you will be learning about the where clause and functionality of the where clause in SQLite. Where ClauseSQLite WHERE Clause is used to filter the rows based on the given query.
3 min read
MariaDB GROUP BY Clause
An important feature in MariaDB, and SQL in general, is the GROUP BY clause. This article explains the important features of the GROUP BY clause in MariaDB. This article explains you the syntax of the GROUP BY clause and its practical applications. Examples include using the aggregate functions, grouping by single and multiple columns, and using GR
6 min read
MariaDB Having Clause
The HAVING clause is crucial for filtering and aggregating data in database queries. The MariaDB HAVING clause syntax is outlined. It breaks down into components. These include the SELECT clause, aggregate functions, and the GROUP BY clause. The SELECT clause specifies columns. Aggregate functions perform calculations on data. The GROUP BY clause g
6 min read
SQLite Limit clause
SQLite is the most popular and most used database engine which is written in c programming language. It is serverless and self-contained and used for developing embedded software devices like TVs, Mobile Phones, etc. In this article, we will be learning about the SQLite Limit Clause using examples simply and understandably. How does the SQLite limi
5 min read
SQLite HAVING Clause
SQLite is a server-less database engine and it is written in c programming language. The main moto for developing SQLite is to escape from using complex database engines like MySQL etc. It has become one of the most popular database engines as we use it in Television, Mobile Phones, web browsers, and many more. It is written simply so that it can b
5 min read
SQLite Group By Clause
SQLite is a server-less database engine and it is written in C programming language. It is developed by D. Richard Hipp in the year 2000. The main moto for developing SQLite is to escape from using complex database engines like MYSQL etc. It has become one of the most popular database engines as we use it in Television, Mobile Phones, Web browsers,
6 min read
SQLite GLOB Clause
SQLite is a server-less database engine and it is written in C programming language. The main moto for developing SQLite is to escape from using complex database engines like MYSQL etc. It has become one of the most popular database engines as we use it in Television, Mobile Phones, web browsers, and many more. It is written simply so that it can b
5 min read
Parameterize IN Clause PL/SQL
PL/SQL stands for Procedural Language/ Structured Query Language. It has block structure programming features.PL/SQL supports SQL queries. It also supports the declaration of the variables, control statements, Functions, Records, Cursor, Procedure, and Triggers. PL/SQL contains a declaration section, execution section, and exception-handling sectio
7 min read
How to Parameterize an SQL Server IN clause
SQL Server IN Clause is used to filter data based on a set of values provided. The IN clause can be used instead of using multiple OR conditions to filter data from SELECT, UPDATE, or DELETE query. The IN clause with parameterized data mainly inside Stored Procedures helps filter dynamic data using SQL Queries efficiently. In this article, we will
5 min read
How to Solve Must Appear in the GROUP BY Clause in SQL
SQL error “Must Appear in GROUP BY Clause” is one of the most common SQL errors encountered by database developers and analysts alike. This error occurs when we attempt to run queries that include grouping and aggregation without taking proper account of the structure of the SELECT statement. In this article, we’ll look at the source of the SQL GRO
5 min read
How to Solve Must Appear in the GROUP BY Clause in SQL Server
In SQL when we work with a table many times we want to use the window functions and sometimes SQL Server throws an error like "Column 'Employee. Department' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." This error means that while selecting the columns you are aggregating the func
4 min read
How to Fix the “must appear in the GROUP BY clause” Error in PostgreSQL?
PostgreSQL is a powerful open-source relational database management system known for its robust features and reliability. However, like any database system, users may encounter errors during query execution. One common error is the "must appear in the GROUP BY clause" error. In this article, We will learn about How to Fix the “must appear in the GR
3 min read