Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Order By Clause in SQL

Order By Clause in SQL

ORDER BY Clause in SQL

The ORDER BY clause is used to sort the result set of a SQL query based on one or more columns. You can sort in ascending or descending order.


Syntax:

SELECT column1, column2, ...FROM table_nameORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
  • ASC = Ascending order (smallest to largest, A to Z). This is the default.

  • DESC = Descending order (largest to smallest, Z to A).


Example:

Retrieve all employees sorted by their salary from highest to lowest:

SELECT employee_name, salaryFROM employeesORDER BY salary DESC;

Example with multiple columns:

Sort employees by department ascending, then by salary descending within each department:

SELECT employee_name, department_id, salaryFROM employeesORDER BY department_id ASC, salary DESC;

Important Points:

  • The ORDER BY clause comes after the WHERE and GROUP BY clauses (if used).

  • If you omit ASC or DESC, ASC is assumed by default.

  • You can order by column name, alias, or column position (e.g., ORDER BY 1 orders by the first selected column).

  • Sorting on text columns is usually case-insensitive, but this depends on the database collation settings.


If you want, I can provide examples on how ORDER BY works with NULL values or how it affects query performance.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql