The ORDER BY clause in SQL is used to sort the result set based on specified columns. It allows us to arrange data in ascending or descending order. Sorting query results enables better data comprehension, analysis, and presentation, making it a crucial tool in SQL queries.
--Order by
CREATE TABLE grades (name TEXT, subject TEXT, grade INTEGER);
INSERT INTO grades (name, subject, grade) VALUES
("John", "CompSci", 97), ("Eric", "CompSci", 88), ("Carol", "Arts", 99),
("John", "History", 93), ("Andrew", "History", 82), ("Eric", "History", 87),
("Steve", "Physics", 91), ("John", "Physics", 84), ("Barney", "Physics", 97);
SELECT DISTINCT name
FROM grades
ORDER by name;
To use the ORDER BY clause, we append it to the end of the SELECT statement and specify the column(s) by which we want to sort the data. We can sort by a single column or multiple columns, with each column having its own sort order.
--Descending Order
CREATE TABLE grades (name TEXT, subject TEXT, grade INTEGER);
INSERT INTO grades (name, subject, grade) VALUES
("John", "CompSci", 97), ("Eric", "CompSci", 88), ("Carol", "Arts", 99),
("John", "History", 93), ("Andrew", "History", 82), ("Eric", "History", 87),
("Steve", "Physics", 91), ("John", "Physics", 84), ("Barney", "Physics", 97);
SELECT name, subject, grade
FROM grades
ORDER by grade DESC;
The ORDER BY clause supports both ascending (ASC) and descending (DESC) sorting. Ascending order is the default, but we can explicitly specify the sort order to achieve descending sorting. This flexibility caters to various sorting requirements.
Order by Exercise Solution
--Code Completed
CREATE TABLE grades (name TEXT, subject TEXT, grade INTEGER);
INSERT INTO grades (name, subject, grade) VALUES
("John", "CompSci", 97), ("Eric", "CompSci", 88), ("Carol", "Arts", 99),
("John", "History", 93), ("Andrew", "History", 82), ("Eric", "History", 87),
("Steve", "Physics", 91), ("John", "Physics", 84), ("Barney", "Physics", 97);
SELECT DISTINCT subject
FROM grades
ORDER BY subject;
By utilizing the ORDER BY clause effectively, we can present data in a well-organized manner. Sorting allows us to highlight trends, identify outliers, and present information in a logical and user-friendly format.