SQL ORDER BY Clause




📌 ORDER BY Clause (Sorting Data)

The SQL ORDER BY clause is used to sort query results in either ascending (ASC) or descending (DESC) order. By default, results are sorted in ascending order.

1️⃣ Basic ORDER BY

SELECT FirstName, Salary
FROM Employees
ORDER BY Salary;

👉 Sorts employees by Salary in ascending order (lowest to highest).

2️⃣ ORDER BY Descending

SELECT FirstName, Salary
FROM Employees
ORDER BY Salary DESC;

👉 Displays the highest salaries first.

3️⃣ Sorting by Multiple Columns

SELECT FirstName, Department, Salary
FROM Employees
ORDER BY Department ASC, Salary DESC;

👉 First sorts by department name, then within each department, sorts by salary (highest first).

4️⃣ ORDER BY with Aliases

SELECT FirstName AS Name, Salary AS Income
FROM Employees
ORDER BY Income DESC;
Pro Tip: Always place ORDER BY at the end of your SQL query.

✅ Key Takeaways

  • ORDER BY sorts query results.
  • Default order = ASC (ascending).
  • Use DESC for descending order.
  • Can sort by multiple columns.
  • Works with column aliases too.

📚 Continue Learning

💬 Got a question about SQL ORDER BY? Drop it in the comments below!




Leave a Comment