Back to cookbooks list Articles Cookbook

How to Order Alphabetically in SQL

Problem:

You want to display records from a table in alphabetical or reverse-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.

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

Let’s display each customer’s information, sorted in ascending order by their last name.

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 select records from a table but would like to see them sorted 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.

or

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.

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: