SQL – ORDER BY clause

Prev     Next

  • ORDER BY clause in SQL is used to sort the data selected from a table. ORDER BY clause sorts the data either in ascending order or descending order using one or more columns.
  • By default, the result set of the query is sorted by ascending order.
  • Syntax for SQL ORDER BY statement is given below.

Syntax for SQL ORDER BY clause:

Syntax to sort in ascending order SELECT column_name1,
column_name2, etc
FROM table_name
ORDER BY column_name1,
column_name2, etc ASC;
Syntax to sort in descending order SELECT column_name1,
column_name2, etc
FROM table_name
ORDER BY column_name1,
column_name2, etc DESC;

Note:

  • To sort in ascending order, we no need to use keyword “ASC” at the end of the query as all SQL query results are sorted by ascending order by default.
  • The columns name those we sort using ORDER BY, should be available in columns list we select.

Example for how to use SQL ORDER BY clause:

Please consider the following table with few records as given below.

Table name (for example): student
Column names in this table: Student_ID, Student_name, City and Age
Available records: 4 rows

sql-table16

  • To sort the data in ascending order, please execute below query. This query will fetch all records available in this table and then will sort by ascending order.

SQL query:

SELECT * from student
ORDER BY Student_name ASC;

SQL query Output:

sql-table17

  • To sort the data in descending order, please execute below query. This query will fetch all records available in this table and then will sort by descending order.

SQL query:

SELECT * from student
ORDER BY Student_name DESC;

SQL query Output:

sql-table18

Prev     Next

Share this website !!!
Facebook Twitter Linkedin

1. Online Compilers - Compile & Run your C/C++ programs:

✅ Online Compilers

2. Ask your questions or clarify your/others doubts from,

✅ Online Discussion Forums by Fresh2Refresh.com





Close
We Support JALLIKATTU !!!
We Support JALLIKATTU!
By Fresh2Refresh.com
Show Your Support as well. Thanks!