Back to cookbooks list Articles Cookbook

How to Order Alphabetically in SQL

Problem

You want to display records from a table in alphabetical order according to given column.

Example

Our database has a table named customer. The customer table contains data in the id, first_name, and last_name columns. We want to display customer’s information, sorted in ascending order by their last name.

id first_name last_name
1 Susan Thomas
2 John Michael
3 Tom Muller

Solution

SELECT 
  id,  
  first_name,
  last_name, 
FROM customer
ORDER BY last_name ASC;
 

This query returns sorted alphabetically records:

id first_name last_name
2 John Michael
3 Tom Muller
1 Susan Thomas

Discussion

If you want to sort the records according to a given column, you can simply use the ORDER BY clause at the end of a SELECT statement. It doesn’t matter how complicated or long your SQL query is—ORDER BY should always be at the end of the command.

After the ORDER BY keyword, you name the column by which the records should be sorted. In our query, we sort by the last name of the customer.

By default, ORDER BY without any additional specifier sorts in ascending order (equivalent to using the ASC keyword explicitly). As you can probably guess, ASC stands for “ascending.” If you’d like to sort in descending order, simplify specify the DESC keyword after the column name.

Example 2: Sorting in descending order

The query below is similar to the previous but returns a list of customers sorted in descending order by their last name:

  SELECT id,  
    first_name,
    last_name, 
  FROM customer
  ORDER BY last_name DESC;
id first_name last_name
1 Susan Thomas
3 Tom Muller
2 John Michael

Recommended courses:

Recommended articles:

See also: