Sort records in SQL - order by - Record Sorting

We can order the result of a "select" so that the records are shown ordered by some field, for this we use the "order by" clause.


The basic syntax is as follows:


 select * from TABLENAME

  order by FIELD;


For example, we retrieve the records from the "books" table ordered by title:


select * from books

 order by title;


The records are listed alphabetically by the specified field.


We can also place the order number of the field by which we want it to be ordered instead of its name, that is, reference the fields by their position in the selection list. For example, we want the result of the "select" ordered by "price":


 select title, author, price

  from books order by 3;


If we put a number greater than the number of fields in the selection list, an error message appears and the sentence is not executed.


By default, if we do not clarify in the sentence, it orders them in ascending order (from lowest to highest). We can order them from highest to lowest, for this we add the keyword "desc":


 select * books

  order by editorial desc;


We can also sort by several fields, for example, by "title" and "publisher":


 select * from books

  order by title, publisher;


We can even sort in different ways, for example, by "title" in ascending order and "editorial" in descending order:


 select * from books

  order by title asc, editorial desc;


It should be clarified next to each field, as these keywords affect the immediately preceding field.

It is possible to sort by a field that is not listed in the selection even by calculated columns.

You can use "order by" with fields of type character, numeric and date.

Comments

Popular posts from this blog

Data Consistency and Inconsistency - What is Difference

Cardinality in DBMS – max/minimum cardinality & examples

Relational Model in DBMS