Sql Order By clause

Sql Order By clause

Blog Bustle 22/03/2020

Sql order by clause is used to show sql query results in ascending or descending order. Sql order by clause shows sql query results in ascending order by default. We use sql order by clause with select sql query.

Sql Order By syntax

SELECT * from table_name ORDER BY column_name(s) ASC|DESC;

ASC keyword is used to show sql query results in ascending order and DESC keyword is used to show sql query results in descending order.

Note: Sql Order By clause is used after WHERE clause in sql query.

Sql ORDER BY with WHERE clause syntax

SELECT * FROM table_name WHERE condition
ORDER BY column_name(s) ASC|DESC;

Sql Order By examples

Let's look at some examples to understand sql order by clause.

I have employee table.

id name city country
1 justin New york US
2 robin Binghamton US
3 jessie Nottingham England
4 chris Manchester England

Sql Order By Ascending example

Fetch all employee records in ascending order and sql query will be

SELECT * FROM employee ORDER BY id asc;

or

SELECT * FROM employee ORDER BY id;

Sql Order By Descending example

Fetch all employee records in descending order and sql query will be

SELECT * FROM employee ORDER BY id desc;

After running this sql query, result will be

id name city country
4 chris Manchester England
3 jessie Nottingham England
2 robin Binghamton US
1 justin New york US

Sql Order By with WHERE clause example

Fetch those employees id who belong to US and show them in descending order

SELECT id FROM employee WHERE country = 'US' ORDER BY id desc;

After running this sql query, result will be

id
2
1

After looking at these examples, we can easily use sql order by clause. Hope you like this tutorial.

Other important links

Sql Aggregate Functions

Sql NOT IN operator

Sql IN operator

Sql LIKE Operator

Sql Order By clause searches:

Tags: #mysql