Introduction
We use ORDER BY to sort data in a table by one column so it is easier to read or find what we want.
SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC];
SELECT name FROM students ORDER BY name;
SELECT price FROM products ORDER BY price DESC;
SELECT order_id, order_date FROM orders ORDER BY order_date DESC;
CREATE TABLE fruits (id INT, name VARCHAR(20), price DECIMAL(5,2)); INSERT INTO fruits VALUES (1, 'Apple', 0.99), (2, 'Banana', 0.59), (3, 'Cherry', 2.99); SELECT name, price FROM fruits ORDER BY price ASC;
ORDER BY do when used with a single column?ORDER BY clause is used to arrange the rows returned by a query in a specific order based on one or more columns.Employees by the column LastName in ascending order?ORDER BY column_name. To specify ascending order, use ASC (which is also default).ORDER BY LastName ASC. SELECT * FROM Employees SORT BY LastName; uses invalid keyword SORT BY. SELECT * FROM Employees ORDER LastName; misses BY. SELECT * FROM Employees ORDER BY LastName DESC; sorts descending, not ascending.Products with columns ProductID and Price, what will be the order of ProductID after running this query?SELECT ProductID FROM Products ORDER BY Price DESC;
ProductID: 1, 2, 3Price: 10, 30, 20Price in descending order, so highest price first.SELECT Name FROM Customers ORDER LastName;
BY after ORDER. The query uses ORDER LastName which is invalid.SELECT statement is valid, and Name is assumed to exist. ORDER BY can be used with SELECT. Only one column is needed for ORDER BY.Students with columns StudentID, Name, and Score. You want to list all students ordered by their Score from highest to lowest, but if two students have the same score, order them alphabetically by Name. Which query correctly achieves this?Score descending (highest first). Secondary sort for ties is by Name ascending (alphabetical).Score DESC then Name ASC, matching requirements. SELECT * FROM Students ORDER BY Name ASC, Score DESC; reverses order priorities. SELECT * FROM Students ORDER BY Score ASC, Name DESC; sorts Score ascending and Name descending, wrong directions. SELECT * FROM Students ORDER BY Score DESC; only sorts by Score DESC, no tie-breaker.Pass the test and this pattern moves unknown