SQL ORDER BY Clause Tutorial
Example Table
We will use the following table named products
for our examples:
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(50),
category VARCHAR(50),
price DECIMAL(10, 2)
);
INSERT INTO products (product_id, product_name, category, price) VALUES
(1, 'Laptop', 'Electronics', 1200.00),
(2, 'Desk', 'Furniture', 300.00),
(3, 'Chair', 'Furniture', 150.00),
(4, 'Smartphone', 'Electronics', 800.00),
(5, 'Monitor', 'Electronics', 200.00);
Products Table
product_id | product_name | category | price |
---|---|---|---|
1 | Laptop | Electronics | 1200.00 |
2 | Desk | Furniture | 300.00 |
3 | Chair | Furniture | 150.00 |
4 | Smartphone | Electronics | 800.00 |
5 | Monitor | Electronics | 200.00 |
Using the SQL ORDER BY Clause
The SQL ORDER BY clause is used to sort the result set of a query by one or more columns. By default, it sorts the results in ascending order. You can also specify descending order using the DESC
keyword.
Example: Ordering by Price (Ascending)
To sort the products by price in ascending order, use the following query:
SELECT product_name, category, price
FROM products
ORDER BY price;
Result:
product_name | Chair |
---|---|
category | Furniture |
price | 150.00 |
product_name | Monitor |
category | Electronics |
price | 200.00 |
product_name | Desk |
category | Furniture |
price | 300.00 |
product_name | Smartphone |
category | Electronics |
price | 800.00 |
product_name | Laptop |
category | Electronics |
price | 1200.00 |
Example: Ordering by Category (Ascending) and Price (Descending)
To sort the products first by category in ascending order and then by price in descending order within each category, use the following query:
SELECT product_name, category, price
FROM products
ORDER BY category, price DESC;
Result:
product_name | Laptop |
---|---|
category | Electronics |
price | 1200.00 |
product_name | Smartphone |
category | Electronics |
price | 800.00 |
product_name | Monitor |
category | Electronics |
price | 200.00 |
product_name | Desk |
category | Furniture |
price | 300.00 |
product_name | Chair |
category | Furniture |
price | 150.00 |