Dear readers of our blog, we'd like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.
 
SQLS*Plus - best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.
 

REQUEST COMPLIMENTARY SQLS*PLUS LICENCE

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

SQL Server ORDER BY operator

26 June 2020

SQL Server ORDER BY

SQL Server operator ORDER BY is used to sort records in the SELECT query result set.

Syntax for ORDER BY statement in SQL

Sorting by one field:

SELECT * FROM tab n WHERE condition ORDER BY F1

You can sort by many fields, not one at a time:

SELECT * FROM tab n WHERE condition ORDER BY F1, F2...

By default, records are sorted in ascending order to be sorted in descending order – set DESC:

SELECT * FROM tab n WHERE condition ORDER BY F DESC

By default the sorting will be as if ASC was supplied:

SELECT * FROM tab n WHERE condition ORDER BY F ASC

A condition where it is not necessary – if it is not set, all records will be selected:

SELECT * FROM tab n ORDER BY F

Overall view:

SELECT list
  FROM tab
  [WHERE conditions]
  ORDER BY list [ ASC | DESC ];

where:

  • list – Columns or calculations that you want to get
  • tab – The tables from which you want the records. The FROM sentence must contain at least one table
  • WHERE conditions – optional. Conditions to be met for entries to be selected
  • ASC – optional. ASC sorts the result set in ascending order. Default behavior if not specified.
  • DESC – optional. DESC sorts the result set in descending order.

Note:
When ASC or DESC is not used in the ORDER BY, the results will be ordered in ascending order. This is same as ORDER BY ASC.

Sorting results in ascending order

To sort the results in ascending order, you can specify the ASC attribute. If no value (ASC or DESC) is specified after the field in the ORDER BY sentence, the sort order will be in ascending order by default. Let’s look at this further.
In this example, we have a table with the following data:

cust_idf_namel_namefav_website
4000JustinBiebergoogle.com
5000SelenaGomezbing.com
6000 MilaKunisyahoo.com
7000TomCruiseoracle.com
8000JohnnyDeppNULL
9000RussellCrowegoogle.com

Enter the following SQL statement:

SELECT *
   FROM cust
  ORDER BY l_name;

Six records will be selected. Here are the results that you should get.

cust_idf_namel_namefav_website
4000JustinBiebergoogle.com
9000RussellCrowegoogle.com
7000TomCruiseoracle.com
8000JohnnyDeppNULL
5000SelenaGomezbing.com
6000 MilaKunisyahoo.com

In this example, all records from the customer table will be returned, sorted by l_name field in ascending order, and will be equivalent to the next ORDER BY SQL sentence.

SELECT *
   FROM cust
  ORDER BY l_name ASC;

Most programmers skip the ASC attribute when sorting in ascending order.

Sorting results in descending order

When sorting a set of results in descending order you use the DESC attribute in the ORDER BY sentence. Let us take a closer look.
In this example, we have a table with the following data:

sup_idsup_namecity_namestate_name
100YandexMoscowRussian
200GoogleLansingMichigan
300OracleRedwood CityCalifornia
400BingRedmondWashington
500YahooSunnyvaleWashington
600DuckDuckGoPaoliPennsylvania
700QwantParisFrance
800FacebookMenlo ParkCalifornia
900Electronic ArtsSan FranciscoCalifornia

Enter the following SQL statement:

SELECT *
   FROM sup
  WHERE sup_id > 40
  ORDER BY sup_id DESC;

Five records will be selected. Here are the results that you should get.

sup_idsup_namecity_namestate_name
900Electronic ArtsSan FranciscoCalifornia
800FacebookMenlo ParkCalifornia
700QwantParisFrance
600DuckDuckGoPaoliPennsylvania
500YahooSunnyvaleWashington

In this example, the set of results will be sorted by field sup_id in descending order.

Sorting results by relative position

You can also use the ORDER BY SQL statement to sort by relative position in the result set, where the first field in the result set is f1, the second f2, the third f3, etc.
In this example, we have a table of products with the following data:

prod_idprod_namecat_id
1Pear50
2Banana50
3Orange50
4Apple50
5Bread75
6Sliced Ham25
7KleenexNULL

Now enter the following SQL statement:

SELECT prod_id,
    prod_name
  FROM prod
  WHERE prod_name <> 'Bread'
 ORDER BY 1 DESC;

Six records will be selected. Here are the results that you should get.

prod_idprod_name
7Kleenex
6Sliced Ham
4Apple
3Orange
2Banana
1Pear

In this example, the results are sorted by the prod_id field in descending order, since the prod_id field is at position #1 in the result set and will be equivalent to the next SQL statement ORDER BY.

SELECT prod_id,
    prod_name
  FROM prod
  WHERE prod_name <> 'Bread'
 ORDER BY prod_id DESC;

Using ASC and DESC Attributes

When sorting a result set using ORDER BY SQL sentence you can use ASC and DESC attributes in one SELECT statement.
In this example, let’s use the same table of products as in the previous example.

prod_idprod_namecat_id
1Pear50
2Banana50
3Orange50
4Apple50
5Bread75
6Sliced Ham25
7KleenexNULL

Now enter the following SQL statement:

SELECT *
    FROM prod
  WHERE prod_id <>
  ORDER BY cat_id DESC,
     prod_name ASC;

Six records will be selected. Here are the results that you should get.

prod_idprod_namecat_id
5Bread75
4Apple50
2Banana50
3Orange50
1Pear50
6Sliced Ham25

In this example, the records are returned sorted by the cat_id field in descending order and the secondary sorting by the prod_name field in ascending order.

Examples:

All examples will be on this table unless otherwise stated:

idnameagesalary
1Justin23400
2Selena25500
3Mila23500
4Tom301000
5Johnny27500
6Russell281000

Example №1
Let’s get all the records from the table and sort them by age:

SELECT * FROM workers_1 WHERE id>0 ORDER BY age

The SQL query will select the strings in the following order:

f_idf_namef_agef_salary
1Justin23400
3Mila23500
2Selena25500
5Johnny27500
6Russell281000
4Tom301000

Since all records are selected, the WHERE block may not be specified:

SELECT * FROM workers_1 ORDER BY f_age

You can also specify the sort type explicitly – ASC – the result will not change:

SELECT * FROM workers_1 ORDER BY f_age ASC

Example №2
Let’s now sort the records by decreasing age:

SELECT * FROM workers_1 ORDER BY f_age DESC

The SQL query will select the strings in the following order:

f_idf_namef_agef_sal
4Tom301000
6Russell281000
5Johnny27500
2Selena25500
1Justin23400
3Mila23500

Example №3
Let’s now sort the records by age and wage at the same time.

The records will be sorted by age first, and those records, where the age is the same (in our case – 23), will be located in the descending wages:

SELECT * FROM workers_1 WHERE id>0 ORDER BY f_age ASC, f_sal DESC

The SQL query will select the strings in the following order:

f_idf_namef_agef_sal
3Mila23500
1Justin23400
2Selena25500
5Johnny27500
6Russell281000
4Tom301000

Example №4
Under the same conditions (i.e. first sorting by f_age), let us sort by salary increase.

Now the first and second entries will be swapped so that first the f_sal is lower and then the f_sal is higher:

SELECT * FROM workers_1 WHERE f_id>0 ORDER BY f_age ASC, f_sa DESC

The SQL query will select the strings in the following order:

f_idf_namef_agef_sal
1Justin23400
3Mila23500
2Selena25500
5Johnny27500
6Russell281000
4Tom301000

Sql Training Online – Sql Order By – Sorting

 
Tags: , , , , ,

MORE NEWS

 

Preamble​​NoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...

Preamble​​MongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...

5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...

The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...

Preamble​​MS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...

First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...

Preamble​​Atom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...

Preamble​​MongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...

FlexibilityOne of the most advertised features of MongoDB is its flexibility.  Flexibility, however, is a double-edged sword. More flexibility means more...

Preamble​​SQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...

Preamble​​Writing an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...

Preamble​​Oracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...

Preamble​​IBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...

  What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....

Preamble​​If you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...

Preamble​​Starting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...