Order By
Order by keyword sort the result-set either in ascending or descending order. This clause sorts the result set in ascending order by default. In order to sort the result-set in descending order DESC keyword is used.
Syntax
SELECT column_1, column_2, column_3………..
FROM Table_Name
ORDER BY column_1, column_2, column_3……. ASC|DESC;
Table_Name: Name of the table.
ASC: keyword for ascending order.
DESC: keyword for descending order.
employees table creation –
Here, we create an employees table with employee_id,first_name, and salary and with the help of order by clause, we can sort the element by their specific column.
Query
create table employees(
employee_id INT PRIMARY KEY ,
first_name VARCHAR(50) ,
salary INT);
INSERT INTO employees(employee_id,first_name,salary)
VALUES
(100,'Steven',24000),
(101,'Neena',17000),
(102,'Lex',17000),
(103,'John',11000),
(104,'Robert',12000),
(105,'Leo',10000);
Output
Query
It sorts the records automatically in ascending order if we want to show the records in descending order then we use DESC.
select * from employees ORDER BY salary;
Output
Query
select * from employees ORDER BY salary DESC;
Output
Difference between order by and group by clause in SQL
ORDER BY clause is used to sort the result set either in ascending or descending order and GROUP BY the statement is used to group the rows that have the same value and it is used with aggregate functions like SUM(), AVG(), MAX(), etc. In this article, we are going to discuss both of these clauses in detail. Let’s start with Order by first.