SQL ORDER BY ASC


SQL ORDER BY ASC

The SQL ORDER BY ASC clause is used to sort the result set of a query in ascending order. This clause is essential for organizing data from the smallest to largest values, making it easier to analyze and understand.


Syntax

SELECT columns
FROM table_name
ORDER BY column1 ASC, column2 ASC, ...;

The ASC keyword sorts the records in ascending order. It is the default sorting order if no order is specified.


Example SQL ORDER BY ASC Queries

Let's look at some examples of SQL ORDER BY ASC queries using the employees table:

1. Basic ORDER BY ASC Example

SELECT first_name, last_name, hire_date
FROM employees
ORDER BY hire_date ASC;

This query retrieves the first name, last name, and hire date of employees, sorted by the hire_date column in ascending order.

2. ORDER BY ASC with Multiple Columns

SELECT first_name, last_name, department_id, hire_date
FROM employees
ORDER BY department_id ASC, hire_date ASC;

This query retrieves the first name, last name, department ID, and hire date of employees, sorted first by the department_id column in ascending order and then by the hire_date column in ascending order.

3. ORDER BY ASC with Aliases

SELECT first_name AS FirstName, last_name AS LastName, hire_date AS HireDate
FROM employees
ORDER BY HireDate ASC;

This query retrieves the first name, last name, and hire date of employees with column aliases, sorted by the HireDate column in ascending order.

4. ORDER BY ASC with Expressions

SELECT first_name, last_name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary ASC;

This query retrieves the first name, last name, and annual salary (calculated as salary * 12) of employees, sorted by the annual_salary column in ascending order.


Conclusion

The SQL ORDER BY ASC clause is a powerful tool for sorting query results in ascending order. Understanding how to use the ORDER BY ASC clause and its syntax is essential for writing effective queries that organize data in a meaningful way, making it easier to analyze and interpret.