Code has been added to clipboard!

Using SQL ORDER BY and SORT BY

Reading time 2 min
Published Aug 9, 2017
Updated Oct 11, 2019

SQL ORDER BY Keyword: Main Tips

  • The keyword ORDER BY is used for sorting the result-set that is created using the SELECT statement.
  • Using this statement you can sort the result-set by one or multiple columns in an ascending or descending order.
  • ORDER BY sorts in an ascending order by default.

Syntax of SQL ORDER BY Keyword

Example
SELECT * FROM users ORDER BY email ASC, username DESC;

Demo Database

In this example, we are using a basic SQL database.

Right here we have a section from the table called "Users":

ID Username Email Password
1 alfredfutter alfredfutter@gmail.com secret1
2 atrujillo atrujillo@gmail.com secret2
3 moreno.antonio moreno.antonio@yahoo.com secret3
4 hardythomas thomas.hardy@gmail.com secret4
5 bergluns bergluns@gmail.com secret5

The following SQL statement selects all users from the "users" table, sorted by the "email" column:

Example
SELECT * FROM users ORDER BY email;

SQL ORDER BY Keyword ORDER BY DESC

This statement will select every user from the table called "users", and sort them in a descending order by the "email" column:

Example
SELECT * FROM users ORDER BY email DESC;

SQL ORDER BY Keyword ORDER BY Several Columns

This statement will select every user from the table called "users", and sort them in an ascending order by the "email" and the "username" columns:

Example
SELECT * FROM users ORDER BY email, username;

This statement will select every user from the table called "users", and sort them in a descending order by the "email" and the "username" columns:

Example
SELECT * FROM users ORDER BY email ASC, username DESC;
Learn SQL
Introduction
Syntax
Data Types
Server Data Types
Commands
Commands List
Wildcards
Constraints
Aggregate Functions
Date Functions
Date Format
Injection
SQL Server Hosting
Views
Auto-incrementation
SQL Operators
AS
AND & OR
IN
BETWEEN
WHERE
GROUP BY
HAVING
ORDER BY
LIKE
NOT
NOT EQUAL
UNION
NULL
NOT NULL
DEFAULT
UNIQUE
FOREIGN KEY
PRIMARY KEY
CHECK
Indexes
ALTER TABLE
CREATE DATABASE
CREATE TABLE
DELETE
DROP
INSERT INTO SELECT
INSERT INTO
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
UPDATE
FULL OUTER JOIN
INNER JOIN
JOIN
LEFT JOIN
RIGHT JOIN
AVG()
COUNT
FIRST
LAST
MAX
MIN()
SUM()
LEN
UCASE
MID
NOW
ROUND
FORMAT
LOWER
CONVERT
ISNULL