DbSchema Database Designer

DbSchema Tutorial | SQL ORDER BY KEYWORD

Publish on DbSchema Blog >>>

Structured Query Language (SQL) is an integral part of managing and handling data in relational databases. A critical feature of this versatile language is the ability to sort and organize data, which is where the ORDER BY keyword comes into play. This comprehensive guide will delve into the intricacies of the ORDER BY keyword, from its basic understanding to practical applications, common pitfalls, and more.

SQL alt >

Table of Contents

  1. Introduction to SQL
  2. What is SQL ORDER BY Keyword?
  3. Syntax of SQL ORDER BY
  4. How to Use SQL ORDER BY
  5. Sorting By Multiple Columns
  6. Common Mistakes Using ORDER BY
  7. Advanced Usage of ORDER BY
  8. FAQs About SQL ORDER BY
  9. Practice Questions
  10. Conclusion

Introduction to SQL

SQL, an acronym for Structured Query Language, is the standard language for interacting with a relational database management system (RDBMS). It allows users to create, modify, and extract data from databases, facilitating the manipulation and management of structured data.

SQL has various components, each designed to perform a specific task. These include SELECT, UPDATE, DELETE, INSERT INTO, and more. One such key component is the ORDER BY keyword, which we’ll explore in this guide.

What is SQL ORDER BY Keyword?

The ORDER BY keyword is used in SQL to sort the results in ascending or descending order according to one or more columns. By default, ORDER BY sorts data in ascending order. However, if you need to sort your results in descending order, you can do so using the DESC keyword.

Syntax of SQL ORDER BY

The general syntax for using ORDER BY is as follows:

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;

The ASC and DESC keywords define the sorting order. If neither is specified, ASC is assumed by default.

How to Use SQL ORDER BY

Let’s dive into some examples to understand how ORDER BY is used.

Example 1: Ascending Order

Suppose we have the following Employees table:

ID NAME SALARY
1 John 3000
2 Alex 5000
3 Sara 4000
4 Maria 6000

Now, we want to sort this data in ascending order of salary:

SELECT * FROM Employees ORDER BY Salary ASC;

The result will be:

ID NAME SALARY
1 John 3000
3 Sara 4000
2 Alex 5000
4 Maria 6000

Example 2: Descending Order

Let’s sort the same data in descending order of salary:

SELECT * FROM Employees ORDER BY Salary DESC;

The result will be:

ID NAME SALARY
4 Maria 6000
2 Alex 5000
3 Sara 4000
1 John 3000

Sorting By Multiple Columns

SQL allows us to sort data by more than one column. In such cases, the rows are first sorted by the first column specified. If two or more rows have the same value for the first column, those rows are then sorted by the second column, and so on.

Example 3: Sorting by Multiple Columns

Let’s add another column, Department, to our Employees table:

ID NAME SALARY DEPARTMENT
1 John 3000 Marketing
2 Alex 5000 Sales
3 Sara 4000 HR
4 Maria 6000 Sales
5 Tom 5000 Marketing

We can sort the table by Department and then by Salary:

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

This will sort the data first by Department in ascending order. Then, for rows where the Department is the same, it will sort by Salary in descending order.

The result will be :

ID NAME SALARY DEPARTMENT
3 Sara 4000 HR
1 John 3000 Marketing
5 Tom 5000 Marketing
4 Maria 6000 Sales
2 Alex 5000 Sales

The table is sorted by Department in ascending order (HR, Marketing, Sales), and within each Department, it’s sorted by Salary in descending order.

Common Mistakes Using ORDER BY

There are several common mistakes when using the ORDER BY clause:

  1. Not specifying ASC or DESC: When you don’t specify ASC or DESC after the ORDER BY clause, SQL orders the results in ascending order by default. This could lead to confusion if you intended to order in descending.

  2. Incorrect column reference: ORDER BY does not recognize column aliases used in the SELECT statement. You need to refer to the actual column names when using ORDER BY.

  3. Ordering by a non-selected column: While you can order by a column that isn’t selected in the SELECT statement, it can be confusing as the ordered column won’t be visible in the output.

Advanced Usage of ORDER BY

Apart from the basic usage of ORDER BY, there are more advanced techniques, such as ordering by a computed column or a function’s result. Let’s consider an example where we want to order employees by the length of their names:

SELECT * FROM Employees ORDER BY LENGTH(Name) ASC;

This query will return the employees ordered by the length of their names in ascending order.

ID NAME SALARY DEPARTMENT
5 Tom 5000 Marketing
1 John 3000 Marketing
3 Sara 4000 HR
2 Alex 5000 Sales
4 Maria 6000 Sales

In this example, “Maria” has the longest name with 5 letters, and “Tom” has the shortest with 3. The names are therefore sorted from shortest to longest.

FAQs About SQL ORDER BY

Q1: Can I order by more than one column?
Yes, you can. When sorting by more than one column, the result set is sorted by the first column, and then that ordered list is sorted by the second column, and so on.

Q2: Can I order by a column that is not in the SELECT statement?
Yes, you can order by a column that isn’t selected in the SELECT statement.

Q3: Does the ORDER BY clause always need to be at the end of the query?
Yes, ORDER BY is typically the last item in an SQL statement. The order cannot be changed.

Practice Questions

Test your understanding of the ORDER BY keyword with these practice questions:

  1. Write a SQL query to order the Employees table in ascending order by Name.

  2. Write a SQL query to order the Employees table in descending order by Salary.

  3. Write a SQL query to order the Employees table first by Name in ascending order and then by Salary in descending order.

  4. Write a SQL query to select the highest Salary from the Employees table.

Conclusion

SQL’s ORDER BY keyword is a powerful tool in the hands of anyone working with databases. It provides an efficient way to sort and analyze data, making it easier to understand and interpret. However, its power lies in understanding how to use it correctly and effectively, as illustrated in this guide.

We’ve covered the basics, advanced usage, and common pitfalls to help you effectively use the ORDER BY keyword in your SQL queries. Remember, the best way to learn is by practicing, so make sure to try the practice questions above.

Mastering SQL requires patience and persistence, so keep practicing and exploring. Happy querying!


Visually Manage Databases using DbSchema

DbSchema is a databases client and visual designer. DbSchema has a free Community Edition, which can be downloaded here.
DbSchema main features include:

DbSchema Designer alt >

Interactive Diagrams

Design tables, column and foreign keys directly in diagrams, by double-clicking them. Changes will be saved to the design model and, if DbSchema is connected to the database also into the database. More.


Connection Dialog alt >

Simple Connection Dialog

Choose the database location, the user and password, and simply get connected. Choose 'Edit Manually' into the JDBC URL combo to enter a custom URL. More.


Relational Data Explorer alt >

Relational Data Explorer

Explore data from multiple tables simultaneously, using foreign keys or virtual foreign keys. Double-click cells to edit the data. More.


Query Builder alt >

Query Builder

Create SQL Queries featuring JOINS, GROUP BY, ORDER BY just using the mouse. More.


SQL Query Editor alt >

SQL Query Editor

Edit and execute SQL Queries. The editor is autocompletion-enabled. More.


Schema Synchronization alt >

Design Schema in Team & Schema Deployment

DbSchema is using the design model, a copy of the schema structure, independent of the database.
The design model can be saved to file and shared in a team.
Connecting to another database you may compare the design model with the database, commit the differences or merge them in the design model. More.


Dark Theme alt >

Dark Theme

Configurable styles & dark theme. More.


Many features are available in the free Community edition.
The Pro edition adds capabilities to save the design to the model file, design schema in team and deploy the schema on multiple databases.


DbSchema can be downloaded for free. No registration is required.