Share This Tutorial

Views 20

Ordering Data with SQL: ORDER BY ASC and DESC

Author Zak  |  Date 2024-10-15 18:08:05  |  Category Computer Science
Back Back

Ordering Data with SQL: ORDER BY ASC and DESC

The ORDER BY clause in SQL allows you to sort the results of your queries in a specific order. This is incredibly useful for organizing your data and making it easier to analyze.

Ascending Order (ASC)

The ASC keyword sorts the data in ascending order, from smallest to largest.

SELECT *
FROM customers
ORDER BY last_name ASC;

This query would return all customer data, sorted alphabetically by the last_name column.

Descending Order (DESC)

The DESC keyword sorts the data in descending order, from largest to smallest.

SELECT *
FROM orders
ORDER BY order_date DESC;

This query would return all order data, sorted by the order_date column, with the most recent orders at the top.

Multiple Sorting Columns

You can order by multiple columns by listing them after ORDER BY, separated by commas.

SELECT *
FROM products
ORDER BY category ASC, price DESC;

This query would first sort products by category in ascending order, then within each category, sort by price in descending order.

Ordering by Non-Numeric Columns

The ORDER BY clause can be used to sort by any column type, including text columns.

SELECT *
FROM employees
ORDER BY department ASC, first_name DESC;

This query would first sort employees by department in ascending order, then within each department, sort by first_name in descending order.

Note about NULLs

By default, NULL values are considered the smallest value when sorting in ascending order, and the largest value when sorting in descending order.

Conclusion

The ORDER BY clause is a fundamental part of SQL. It allows you to present your data in a meaningful and organized way, making it easier to analyze and understand.