SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL Groupby SQL Having SQL In SQL Insert_into SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL OrderBy SQL Select SQL Select Into SQL Top Limit Fetch SQL Store Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL BackupDB SQL Check SQL Constrains SQL Create View SQL CreateDB SQL CreateTable SQL Data types SQL Dates SQL DefaultConstrain SQL DropDB SQL DropTable SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

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