Tuesday, December 17, 2024

SQL ORDER BY Keyword

 The ORDER BY keyword in SQL is used to sort the result set of a query in either ascending or descending order. By default, the ORDER BY clause sorts the results in ascending order (ASC). If you want to sort in descending order, you can specify DESC.

Syntax:

SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
  • column1, column2, ...: The columns you want to sort by.
  • ASC: Sorts the result set in ascending order (this is the default behavior if not specified).
  • DESC: Sorts the result set in descending order.

Example 1: Sorting in Ascending Order

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

This query retrieves the list of employees and sorts them by age in ascending order.

Example 2: Sorting in Descending Order

SELECT first_name, last_name, salary FROM employees ORDER BY salary DESC;

This query retrieves the list of employees and sorts them by salary in descending order (highest to lowest salary).

Example 3: Sorting by Multiple Columns

SELECT first_name, last_name, age, salary FROM employees ORDER BY age ASC, salary DESC;

This query sorts the employees first by age in ascending order. If two employees have the same age, it sorts them by salary in descending order.

Key Points:

  • Default Sorting: If you don't specify ASC or DESC, ORDER BY will default to ascending order (ASC).
  • Sorting Null Values: When sorting data, NULL values are typically sorted either at the beginning or the end, depending on the database system. Most databases place NULL values first when sorting in ascending order and last when sorting in descending order, but this behavior may vary.
  • Performance Considerations: Sorting data can affect performance, especially on large datasets, so it's a good idea to ensure indexes are in place on the columns used for sorting when dealing with large tables.

Example: Sorting with NULL Values

SELECT id, name, email FROM customers ORDER BY email ASC;

If some of the email values are NULL, the behavior of the sorting may vary depending on the database, but usually, NULL values will either appear at the start or the end of the sorted list.

Let me know if you'd like to dive deeper into any specific part of ORDER BY or sorting techniques in SQL!

No comments:

Post a Comment