SQL Standard

SQL Group By Order By

For this tutorial, we will discover and explore how to use the Order By and Group By clauses in SQL. We can order data from a result set using various parameters using these two clauses.

SQL Order By

The order by clause in SQL allows you to sort data based on a specific column within a table. You can either sort data in ascending or descending order.

NOTE: Unless explicitly specified, the order by clause will default to ascending order.

The syntax for the order by clause in SQL is as shown below:

SELECT column1, column2,…columnN
FROM TABLE_NAME
ORDER BY column1 ASC|DESC

The ASC and DESC parameters allow you to sort data in ascending and descending order.

For example, suppose we have a table containing employee information as shown below:

Suppose we want to sort the data based on the start date; we can run a query as shown:

SELECT *
FROM EMPLOYEES
ORDER BY START_DATE ASC;

The code above should sort the data from the earliest date to the latest. This is described in the ASC parameter.

To sort data from the latest date to the earliest, we can run:

SQL Group By

The SQL Group By clause is closely similar to the ORDER BY clause. The only difference is that the group by clause is applied to a data group. This allows you to organize data into a set of groups.

The syntax is as shown:

SELECT column1, COLUMN 2, … columnN
FROM TABLE_NAME
WHERE [condition]
GROUP BY COLUMN
ORDER BY COLUMN;

Suppose we have a table containing user information as shown:

We can get the total salary for the active users using the group by as shown:

SELECT ACTIVE,
    SUM(SALARY) AS TOTAL
FROM USERS
GROUP BY ACTIVE;

The query above will group the data into true and false. It will then apply the sum function on the salary column and return:

Keep in mind that you can use both group by and order by clauses in the same query.

Terminating

This article discussed the group by and order by clauses in SQL.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list