Day 05 – SQL ORDER BY
The SQL ORDER BY clause is used to sort the results of a SELECT statement in either ascending or descending order based on one or more columns. The basic syntax of a SELECT statement with an ORDER BY clause is:
SELECT column1, column2, ... FROM table_name ORDER BY column_name [ASC|DESC];
In this syntax, column1, column2, etc. are the names of the columns that you want to retrieve data from, and table_name is the name of the table that you want to retrieve data from. The column_name specifies the column or columns that you want to sort the results by, and the optional ASC or DESC keyword specifies the order in which you want to sort the results.
Here’s an example of a SELECT statement with an ORDER BY clause that retrieves all the rows from a table named “employees” and sorts them in ascending order based on the “last_name” column:
SELECT * FROM employees ORDER BY last_name ASC;
In this example, the ORDER BY clause is used to sort the data in ascending order based on the “last_name” column.
You can also specify multiple columns to sort by in the ORDER BY clause. When you do this, the results are first sorted based on the first column, and then by the second column if there are any ties in the first column, and so on. Here’s an example:
SELECT * FROM employees ORDER BY department_id ASC, salary DESC;
In this example, the ORDER BY clause is used to sort the data first by the “department_id” column in ascending order, and then by the “salary” column in descending order.
The ORDER BY clause is a powerful tool for sorting and organizing data in a SELECT statement. It allows you to control the order in which the results are displayed, making it easier to analyze and interpret the data.