ORDER BY clause is used in an SQL statement to sort the result set based on one or more columns. The basic syntax of the ORDER BY clause is as follows:
SELECT column1, column2, ..., column_n
FROM table_name
ORDER BY column_name ASC/DESC;
In this syntax, column_name
represents the name of the column that you want to use to sort the result set, and ASC
or DESC
represents the sort order, either ascending or descending. By default, the sort order is ascending if you do not specify either ASC
or DESC
.
Let’s take a look at a few examples to understand the ORDER BY clause better:
Example 1:
SELECT name, age, city
FROM students
ORDER BY age DESC;
In this example, the ORDER BY clause sorts the result set by the age
column in descending order. The result of this query will be a table that displays the name, age, and city of all the students in the students
table, sorted by age in descending order.
Example 2:
SELECT name, marks, subject
FROM marks
ORDER BY marks ASC, subject DESC;
In this example, the ORDER BY clause sorts the result set by the marks
column in ascending order, and then by the subject
column in descending order. The result of this query will be a table that displays the name, marks, and subject of all the students in the marks
table, sorted first by marks in ascending order, and then by subject in descending order.
Example 3:
SELECT students.name, marks.subject, marks.marks
FROM students
JOIN marks
ON students.student_id = marks.student_id
ORDER BY marks.marks DESC;
In this example, the ORDER BY clause sorts the result set by the marks
column in descending order. The result of this query will be a table that displays the name of the student, the subject, and the marks for all the students in the students
and marks
tables, sorted by marks in descending order.
In conclusion, the ORDER BY clause is a useful tool for sorting the result set in SQL statements. It provides a way to sort the data based on one or more columns, making it easier to view and analyze the data.
Also check WHAT IS GIT ? It’s Easy If You Do It Smart
You can also visite the Git website (https://git-scm.com/)