sql-order-by-clause

Use Of SQL Order by Clause

In SQL order by clause is used to sort the result set of a query in ascending or descending order based on one or more columns.

`ASC` (ascending) is the default sorting order if nothing specified by user.

`DESC` (descending) is used to sort in descending order.

Syntax

SELECT column1, column2, so on

FROM tableName

ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], so on;

For example:

SELECT StaffName, Sale

FROM employees

ORDER BY Sale DESC;

This query retrieves the names and sale of staff from the “employees” table, sorted in descending order based on sale.

Use Of SQL Order By

Order by Descending

Records are typically sorted using the ORDER BY keyword in ascending order. Use the DESC keyword to sort the records in descending order.

Example

Sort the products from highest to lowest Cost:

SELECT * FROM Products

ORDER BY Cost DESC;

Order by Alphabetically

The ORDER BY keyword will sort string items alphabetically:

Example

Sort the products alphabetically by ProductType:

SELECT * FROM Products

ORDER BY ProductType;

Order by Alphabetically “DESC”

Use the DESC keyword to sort the table in reverse alphabetical order:

Example

Sort the products by ProductType in reverse order:

SELECT * FROM Products

ORDER BY ProductType DESC;

SQL Order by Multiple Columns or Several Column

The following SQL query sorts the “Cost” and “ProductType” columns to select all customers from the “Customers” table. This means that while it arranges by Cost, it orders rows by ProductType if several rows have the same cost:

Example

SELECT * FROM Customers

ORDER BY Cost, ProductType;

Use of Both ASC and DESC

By sorting the “City” and “FirstName” columns in both ascending and descending order, the following SQL query pulls all customers from the “Customers” table:

Example

SELECT * FROM Customers

ORDER BY City ASC, FirstNam DESC;

SQL Order By Date

To order a result set by date in SQL, you can use the `ORDER BY` clause along with the date column.

SELECT column1, column2, date_column

FROM your_table

ORDER BY date_column DESC/ASC;

This query selects specified columns from the table and orders the result set based on the date_column in descending order (`DESC`), meaning the most recent dates will appear first. If you want ascending order, you can use `ASC` instead.

For instance, if you have a table called `orders` with a date column named `order_date`, the query might look like this:

SELECT order_id, customer_name, order_date

FROM orders

ORDER BY order_date DESC;

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *