Lesson 5 β€’ Beginner

    ORDER BY & Sorting

    Sort query results by one or more columns, handle NULL values, and combine sorting with filtering for powerful queries.

    🎯 What You'll Learn

    • Sort ascending (ASC) and descending (DESC)
    • Sort by multiple columns for sub-sorting
    • Handle NULL values in sorted results
    • Combine WHERE + ORDER BY + LIMIT for real-world queries

    Basic Sorting

    ORDER BY sorts your results. By default, it sorts in ascending order (A→Z, 1→100, oldest→newest).

    πŸ“š Real-World Analogy

    ORDER BY is like the "Sort" button on Amazon. Sort by "Price: Low to High" = ORDER BY price ASC. Sort by "Price: High to Low" = ORDER BY price DESC.

    Without ORDER BY, SQL returns rows in an undefined order β€” it could be different every time! Always sort if order matters.

    Basic Sorting

    Sort results ascending and descending

    Try it Yourself Β»
    SQL
    -- Ascending order (default)
    SELECT * FROM products ORDER BY price;
    SELECT * FROM products ORDER BY price ASC;
    
    -- Descending order
    SELECT * FROM students ORDER BY grade DESC;
    
    -- Sort alphabetically
    SELECT first_name, last_name
    FROM employees
    ORDER BY last_name ASC;

    Multi-Column Sorting

    Sort by multiple columns to create a hierarchy. The second column only matters when the first has ties.

    πŸ’‘ Pro Tip

    Each column can have its own sort direction: ORDER BY department ASC, salary DESC groups by department alphabetically, then shows highest salary first within each department.

    ⚠️ Common Mistake

    Sorting by column position (ORDER BY 3) is fragile β€” if you add a column, the sort changes silently. Always use column names.

    Multi-Column & Calculated Sorting

    Sort by multiple columns and computed values

    Try it Yourself Β»
    SQL
    -- Sort by department, then salary within each dept
    SELECT name, department, salary
    FROM employees
    ORDER BY department ASC, salary DESC;
    
    -- Sort by calculated value
    SELECT product_name, price, price * 0.9 AS sale_price
    FROM products
    ORDER BY sale_price ASC;
    
    -- Sort by column position (not recommended)
    SELECT name, age, grade FROM students
    ORDER BY 3 DESC;  -- sorts by 3rd column (grade)

    NULL Handling in Sorting

    Control where NULL values appear in sorted results

    Try it Yourself Β»
    SQL
    -- NULL values in sorting
    -- NULLs appear first in ASC, last in DESC (varies by DB)
    SELECT name, bonus FROM employees
    ORDER BY bonus ASC;
    
    -- Force NULLs to the end (PostgreSQL)
    -- SELECT name, bonus FROM employees
    -- ORDER BY bonus ASC NULLS LAST;
    
    -- Workaround for MySQL: use COALESCE
    SELECT name, bonus
    FROM employees
    ORDER BY COALESCE(bonus, 0) DESC;

    The Complete Query Pattern

    Here's the order SQL clauses must appear in:

    SELECT columns
    FROM table
    WHERE conditions      -- filter rows
    ORDER BY columns      -- sort results
    LIMIT n OFFSET m;     -- paginate

    ⚠️ Common Mistake

    Putting ORDER BY before WHERE. SQL clauses have a strict order: SELECT β†’ FROM β†’ WHERE β†’ ORDER BY β†’ LIMIT.

    Real-World Combined Queries

    Build production-quality queries combining WHERE, ORDER BY, and LIMIT

    Try it Yourself Β»
    SQL
    -- Combine WHERE + ORDER BY + LIMIT
    -- Top 5 most expensive electronics
    SELECT product_name, price, rating
    FROM products
    WHERE category = 'Electronics'
      AND rating >= 4.0
    ORDER BY price DESC
    LIMIT 5;
    
    -- Latest 10 orders from VIP customers
    SELECT order_id, customer_name, total, order_date
    FROM orders
    WHERE customer_type = 'VIP'
    ORDER BY order_date DESC
    LIMIT 10;
    
    -- Remember: WHERE β†’ ORDER BY β†’ LIMIT
    -- This order matters!

    πŸ“˜ Quick Reference

    SyntaxResult
    ORDER BY colAscending (default)
    ORDER BY col DESCDescending
    ORDER BY a, b DESCa ascending, then b descending
    COALESCE(col, 0)Replace NULL with 0 for sorting
    NULLS LASTNULLs at end (PostgreSQL)

    πŸŽ‰ Lesson Complete!

    You can now sort results in any order and combine sorting with filtering. Next, you'll learn JOIN operations β€” combining data from multiple tables!

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy β€’ Terms of Service