SQL Tutorial
In SQL, the ORDER BY
keyword is used to sort the result-set in ascending or descending order. It sorts the records in a result set by one or more columns.
The ORDER BY
keyword sorts the records in ascending order by default. If you want to sort the records in a descending order, you can use the DESC
keyword.
Here's the basic syntax:
SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Examples:
Consider the following Employees
table:
EmployeeID | FirstName | LastName |
---|---|---|
1 | John | Doe |
2 | Jane | Smith |
3 | Alice | Johnson |
4 | Charlie | Brown |
5 | David | Thompson |
FirstName
:SELECT * FROM Employees ORDER BY FirstName ASC;
This SQL statement selects all data from the "Employees" table, sorted in ascending order by the "FirstName" column.
LastName
:SELECT * FROM Employees ORDER BY LastName DESC;
This SQL statement selects all data from the "Employees" table, sorted in descending order by the "LastName" column.
SELECT * FROM Employees ORDER BY FirstName ASC, LastName DESC;
This SQL statement selects all data from the "Employees" table, sorted in ascending order by the "FirstName" and then in descending order by the "LastName".
Note:
ORDER BY
clause is not specified, the order of the rows in the result-set is undefined.ORDER BY
clause at the end of your SQL statement.How to Use ORDER BY in SQL:
ORDER BY
clause is used to sort the result set in ascending (default) or descending order based on one or more columns.SELECT column1, column2 FROM example_table ORDER BY column1;
SQL ORDER BY Ascending and Descending:
ASC
(ascending) or DESC
(descending) in the ORDER BY
clause.SELECT column1, column2 FROM example_table ORDER BY column1 DESC;
Sorting Multiple Columns in SQL ORDER BY:
ORDER BY
clause.SELECT column1, column2, column3 FROM example_table ORDER BY column1 ASC, column2 DESC;
ORDER BY with NULL Values in SQL:
NULLS LAST
to sort them last.SELECT column1, column2 FROM example_table ORDER BY column1 NULLS LAST;
SQL ORDER BY String and Numeric Sorting:
SELECT column1, column2 FROM example_table ORDER BY column1, column2;
Custom Sorting in SQL ORDER BY:
CASE
statement in the ORDER BY
clause for custom sorting logic.SELECT column1, column2 FROM example_table ORDER BY CASE WHEN column1 = 'CustomValue' THEN 0 ELSE 1 END, column2;
Sorting by Date in SQL ORDER BY:
ORDER BY
just like other data types.SELECT column1, column2, date_column FROM example_table ORDER BY date_column DESC;
Limiting Rows with TOP and ORDER BY in SQL:
TOP
(SQL Server) or LIMIT
(for other databases) with ORDER BY
to limit the number of rows returned.SELECT TOP 5 column1, column2 FROM example_table ORDER BY column1 DESC;
Sorting Results of JOIN in SQL:
ORDER BY
to sort the combined result set based on columns from any joined table.SELECT table1.column1, table2.column2 FROM table1 INNER JOIN table2 ON table1.id = table2.id ORDER BY table1.column1 ASC, table2.column2 DESC;