MySQL OrderBy

by Vincy. Last modified on July 4th, 2022.

MySQL “ORDER BY” clause is used to order results based on a column. This clause is used in select queries to do sort by specifying the column order (ASC, DESC). If no order is given, then ASC is the default order. Syntax,

SELECT * FROM table_name ORDER BY column_name desc

Using the “ORDER BY” clause we can get ordered results based on multiple columns.

Example: Sorting MySQL Table Records using ORDER BY

This is the student table containing student_name, student_email and applied_date columns.

First, we are going to write a query to order this table data by using a single column student_name in descending order. The query is like,

SELECT * FROM students ORDER BY student_name DESC

mysql_student_table

After running this query, the student’s table results will be as,

mysql_order_by_single_column

Next, we are writing a query in order by two columns applied_date and student_name. The query is,

SELECT * FROM students ORDER BY applied_date DESC, student_name DESC

This query will sort students’ records in descending order. If any number of these records have the same value for applied_date, then, these records will be sorted by the student_name column in descending order. Now, the result is,

mysql_order_by_more_column

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page