What is ORDER BY in MySQL?

ORDER BY in MySQL is the keyword used to get the records in the defined order, Ascending or descending for any particular column.

We can order by one or multiple columns based on the requirements.

We will use the same student table we have created in MySQL SELECT Statement.

By default when we do order by, the order will be returned in ascending order. To get the order in descending order we need to use the DESC keyword. We can also use the ASC keyword if we want our code to be more readable.

Following is the syntax for the ORDER BY:

SELECT column_name1, column_name2, ….
FROM schema.table_name
ORDER BY column_column1, column_name2, …. ASC|DESC;

Now we will see an example to get the student’s details order by class in ascending order.

select * from students order by class;

OR 

select * from students order by class asc;

Example to get the student’s details order by class in descending order.

select * from students order by class desc;

Example for multiple columns order by class and marks both ascending.

select * from students order by class, marks;

Example for multiple columns order by class ascending and marks in descending order

select * from students order by class, marks desc;

Example for both in descending order.

select * from students order by class desc, marks desc;

Order by on varchar columns:

select * from students order by name;

Order by with where condition:

Where condition in select statement comes before the ORDER BY keyword as shown in the following example.

select * from students where class > 3 order by name;

We can check multiple ORDER BY conditions on different columns and check how it behaves. we can add as many columns as we want in the order by expression.

-A blog by Shwetali Khambe

Related Posts