Reading Time: 2 minutes
Good afternoon, friends!
Today, I’m going to talk to you about the SQL keyword ORDER BY. Are you ready?
Let’s get started.
SQL is a programming language used to work with databases. The “ORDER BY” command is used to sort the results of a query in ascending or descending order based on a specific column.
Example 1:
Suppose we have a table called “Employees” with the following columns: “ID”, “Name”, “Last Name,” and “Salary.” If we want to sort the employees in alphabetical order by last name, we could use the following query:
SELECT * FROM Employees ORDER BY Last Name;
In this case, we select all columns (*) from the “Employees” table and sort the results by the “Last Name” column. By default, the order will be ascending.
Example 2:
Now, suppose we want to sort the employees by salary in descending order. We could use the following query:
SELECT * FROM Employees ORDER BY Salary DESC;
In this case, we select all columns (*) from the “Employees” table and sort the results by the “Salary” column in descending order.
Example 3:
If we want to sort the employees by name and then by salary, we could use the following query:
SELECT * FROM Employees ORDER BY Name, Salary;
In this case, we select all columns (*) from the “Employees” table and sort the results first by the “Name” column and then by the “Salary” column.
In addition to sorting by specific columns, it’s also possible to sort the results using expressions.
For example, if we want to sort the employees by their annual salary (which is calculated by multiplying the monthly salary by 12), we could use the following query:
SELECT *, Salary * 12 AS AnnualSalary FROM Employees ORDER BY AnnualSalary;
In this case, we select all columns (*) from the “Employees” table and also calculate a new column called “AnnualSalary,” which is the result of multiplying the monthly salary by 12. Then, we sort the results by the “AnnualSalary” column.
Another example is if we want to sort the employees by their full name (concatenating the first name and last name). We could use the following query:
SELECT *, CONCAT(Name, ' ', Last Name) AS Full Name FROM Employees ORDER BY Full Name;
In this case, we select all columns (*) from the “Employees” table and also concatenate the values of the “Name” and “Last Name” columns into a new column called “Full Name.” Then, we sort the results by the “Full Name” column.
It’s also possible to use aggregate functions, such as SUM or COUNT, in the “ORDER BY” clause. For example, if we want to sort departments by the total salaries of their employees, we could use the following query:
SELECT Department, SUM(Salary) FROM Employees GROUP BY Department ORDER BY SUM(Salary) DESC;
In this case, we select the “Department” column and sum the values of the “Salary” column grouped by “Department.” Then, we sort the results by the “SUM(Salary)” column in descending order.
I hope you like it! 😊
💪