A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

4.3 ORDER BY clause

 The ORDER BY clause in SQL is used to sort the result set of a query in ascending or descending order based on one or more columns. It is often used with the SELECT statement to present the data in a more organized and meaningful way.

4.3.1 Basic Syntax

The basic syntax of the ORDER BY clause is as follows:

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

  • column1, column2, ...: The columns you want to retrieve.
  • table_name: The name of the table.
  • ORDER BY: Specifies the sorting order.
  • column1, column2, ...: The columns by which the result set should be sorted.
  • ASC: Ascending order (default).
  • DESC: Descending order.

4.3.2 Example Queries

Consider a table named employees with the following data:

emp_idemp_nameemp_salary
1Alice50000
2Bob60000
3Charlie45000
4David70000

Example 1: Sorting in Ascending Order

SELECT emp_id, emp_name, emp_salary
FROM employees
ORDER BY emp_salary ASC;
emp_idemp_nameemp_salary
3Charlie45000
1Alice50000
2Bob60000
4David70000

Example 2: Sorting in Descending Order

SELECT emp_id, emp_name, emp_salary
FROM employees
ORDER BY emp_salary DESC;

emp_idemp_nameemp_salary
4David70000
2Bob60000
1Alice50000
3Charlie45000

4.3.3 Sorting by Multiple Columns

You can also sort the result set by multiple columns. Consider a table named sales:

product_idsalespersonsale_amount
1Alice200
2Bob150
1Charlie180
2Alice220

Example 3: Sorting by Multiple Columns

SELECT product_id, salesperson, sale_amount
FROM sales
ORDER BY product_id, sale_amount DESC;

product_idsalespersonsale_amount
1Charlie180
1Alice200
2Alice220
2Bob150

In this example, the result set is first sorted by product_id in ascending order and then by sale_amount in descending order.

The ORDER BY clause is a powerful tool for organizing and presenting data in a way that best suits your needs. Experiment with different columns and sorting orders to refine your queries.