SQL ORDER BY Keyword

SQL ORDER BY Keyword

SQL ORDER BY Keyword

The SQL ORDER BY keyword is used to sort the result set of a SELECT statement in ascending or descending order based on one or more columns.

The syntax of the ORDER BY keyword is as follows:

				
					SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

				
			

Here, column1, column2, etc. are the names of the columns that you want to retrieve from the table_name. The ORDER BY keyword is followed by the name of the column(s) that you want to sort the result set by. The [ASC|DESC] clause specifies the sort order – ascending (ASC) or descending (DESC).

Examples:

  1. Sort the customers table in ascending order by last_name and then by first_name.
				
					SELECT * FROM customers
ORDER BY last_name, first_name;

				
			

In this example, the customers table is sorted in ascending order by last_name. If two or more rows have the same last_name, then they are sorted in ascending order by first_name.

 

  1. Sort the orders table in descending order by order_date.
				
					SELECT * FROM orders
ORDER BY order_date DESC;

				
			
  1. Sort the products table in ascending order by category and then in descending order by price.
				
					SELECT * FROM products
ORDER BY category, price DESC;

				
			

In this example, the products table is sorted in ascending order by category. If two or more rows have the same category, then they are sorted in descending order by price.

By using the ORDER BY keyword, you can sort the result set of a SELECT statement based on one or more columns and retrieve the data in a more meaningful and useful way.

Join To Get Our Newsletter
Spread the love