- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL ORDER BY
In the world of databases, data is often stored in an unpredictable order. When you run a simple SELECT statement, the database returns rows in whatever order it finds them most efficient to retrieve. To present data in a meaningful way such as listing customers alphabetically or showing the most recent transactions first we use the ORDER BY clause.
The ORDER BY clause allows you to sort your result set based on one or more columns. You can choose to arrange your data in Ascending (low to high) or Descending (high to low) order.
ORDER BY clause, the order of the returned rows is never guaranteed. Even if the data looks sorted now, it might change later as the database grows or undergoes maintenance.
Basic Syntax of ORDER BY
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
column1, column2, ...: These are the columns you want to use as the sorting criteria.ASC: Short for "Ascending." It sorts data from smallest to largest (A-Z, 1-10). This is the default setting.DESC: Short for "Descending." It sorts data from largest to smallest (Z-A, 10-1).
ASC is the default, explicitly writing it out in complex queries can make your code much easier for other developers to read and understand quickly.
Key Features of ORDER BY Clause
1. Sorting in Ascending Order
Ascending order is the most common way to sort. It organizes strings alphabetically, numbers from lowest to highest, and dates from oldest to newest.
SELECT * FROM employees
ORDER BY salary ASC;
This query retrieves all employees and places the person with the lowest salary at the very top of the list.
ORDER BY changes the data in the actual table. It doesn't! It only changes how the data is displayed in your current query result.
2. Sorting in Descending Order
Descending order is perfect for "Top 10" lists, finding the most expensive products, or seeing the most recent activity in an application.
SELECT * FROM employees
ORDER BY salary DESC;
By using DESC, the employee with the highest salary will appear first. This is a standard approach for building leaderboards or high-value reporting dashboards.
3. Sorting by Multiple Columns
Sometimes, one column isn't enough to organize your data. If you sort by last_name and two people have the same name, which one comes first? Multiple column sorting acts as a "tie-breaker."
SELECT * FROM employees
ORDER BY department ASC, salary DESC;
In this example, the database first groups everyone by their department (A to Z). Inside each specific department, it then sorts the employees by their salary, putting the highest earners at the top of their respective department groups.
4. Sorting by Column Position
You can use a shorthand by referencing the column's numerical position in your SELECT list. For example, 1 refers to the first column mentioned after SELECT.
SELECT first_name, last_name, salary
FROM employees
ORDER BY 3 DESC;
Since salary is the third item in our selection, ORDER BY 3 DESC tells the database to sort by salary in descending order.
ORDER BY 3) saves typing, it can cause bugs. If a teammate later adds a new column to the beginning of the SELECT statement, your sort will point to the wrong data!
Example Queries
1. Sort Employees by Salary in Ascending Order
This is useful for identifying the lowest entry-level pay grades in a company.
SELECT * FROM employees
ORDER BY salary ASC;
2. Sort Employees by Name in Alphabetical Order
When generating a staff directory, you typically want to sort by last name first, then first name.
SELECT * FROM employees
ORDER BY last_name ASC, first_name ASC;
3. Sort Employees by Department and Salary
This provides a clear view of the pay distribution within individual departments.
SELECT * FROM employees
ORDER BY department ASC, salary DESC;
4. Sort Employees by Date of Joining (Newest First)
To see who recently joined the team, we sort the join_date by descending order.
SELECT * FROM employees
ORDER BY join_date DESC;
DESC gives you the most recent (newest) dates first, while ASC gives you the oldest (chronological) order.
5. Sort Employees by ID (Ascending Order)
Sorting by a primary key like employee_id is often the default way developers view raw data to ensure a consistent, predictable list.
SELECT * FROM employees
ORDER BY employee_id ASC;
NULL values. In many SQL versions (like PostgreSQL or Oracle), NULL values are treated as the "largest" values and appear at the end of an ASC sort. In others (like MySQL), they might appear at the start.
Summary
The ORDER BY clause is a fundamental tool for any developer working with SQL. Whether you're organizing a simple list or building complex financial reports, mastering how to sort by single columns, multiple columns, and different directions is essential. By combining ASC and DESC, you can control exactly how your data is presented to the end user.