TOP

SQL-Lesson 3. Sorting data (ORDER BY)

In the future, we may need to sort our selection - alphabetically for text or ascending/descending - for numeric values. For such purposes, SQL has a special operator ORDER BY.

The SQL operator ORDER BY can sort both from smaller to larger, i.e. in ascending order, and in the reverse order - from larger to smaller.


1. Sorting the selected data

Let's sort our entire table by the amount of product sales, namely by the Amount column.

Run SQLSELECT * 
FROM Sumproduct 
ORDER BY Amount

We see that the query sorted the records in ascending order in the Amount field. It is necessary to observe the sequence of the arrangement of operators, that is, the operator ORDER BY must go at the very end of the request. Otherwise, an error message will be received.

Also, a feature of the ORDER BY operator is that it can sort data by a field that we did not select in the query, that is, it is enough that it is in the database at all.

2. Sorting by several fields

Now let's sort our example additionally by one more field. Let it be the field City, which displays the place of sale of products.

Run SQLSELECT * 
FROM Sumproduct 
ORDER BY Amount, City

The order of sorting will depend on the order of the fields in the query. That is, in our case, the data will first be sorted by the Amount column, and then by City.

3. Direction of sorting

Although by default the ORDER BY operator sorts in ascending order, we can also write the values in descending order. To do this, we put the DESC operator (which is an abbreviation of the word DESCENDING) at the end of each field.

Run SQLSELECT * 
FROM Sumproduct 
ORDER BY Amount DESC, City

In this example, the values in the Amount field were sorted in descending order, and in the City field - in ascending order. The DESC operator applies only to one column, so if necessary, it must be written after each field that participates in sorting.