SQL Sorting Rows
How Sorting Rows work in SQL?
You can use the ORDER BY clause to sort the rows in the result set based on one or more columns.
Syntax:
Let's see the syntax below:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
- Replace column1, column2, ... with the names of the columns you want to select.
- Replace table_name with the name of the table.
- Use ORDER BY followed by the column names to specify the sorting order.
- ASC (ascending) is the default sorting order. You can also use DESC (descending).
Example:
Assuming you have a table called "employees":
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
INSERT INTO employees VALUES
(1, 'John', 'Doe', 'HR', 50000.00),
(2, 'Jane', 'Smith', 'IT', 60000.00),
(3, 'Bob', 'Johnson', 'Finance', 55000.00);
To select all employees and order them by last_name in ascending order:
SELECT * FROM employees ORDER BY last_name ASC;
This query will return:
Employee ID | First Name | Last Name | Department | Salary |
---|---|---|---|---|
3 | Bob | Johnson | Finance | 55000.0 |
1 | John | Doe | HR | 50000.0 |
2 | Jane | Smith | IT | 60000.0 |
Sorting by Multiple Columns:
You can sort by multiple columns by specifying multiple column names in the ORDER BY clause:
SELECT * FROM employees ORDER BY department ASC, salary DESC;
This query will return employees sorted first by department in ascending order and then by salary in descending order.
Tips:
- Use the ORDER BY clause to sort the result set based on one or more columns.
- By default, sorting is done in ascending order. Use ASC explicitly for clarity.
- Use DESC to sort in descending order.
- Consider the impact on performance when sorting large result sets.