knowledgediarybd.com

Your Virtual Knowledge Campus







SQL Order By and Group By

SQL Order By and Group By  is another two important command in MySQL database and other database like: like SQL Server , MS Access , Oracle.

In this tutorial i will discuss about SQL Order By& Group By statement,their purpose , syntax  and suitable example.

I hope you will be benefited .

Purpose of SQL Order By:

1. The ORDER BY keyword is used to sort the result-set by a specified column.

2. The ORDER BY keyword  is used to  sorts the records in ascending  or descending order by default.

3. If we  want to sort the records in a table in descending order, we have to  use the DESC keyword.

4. If we  want to sort the records in a table in ascending order, we have to  use the ASC keyword.

Syntax of Order by:

SELECT clm_name  FROM tbl_name ORDER BY column_name   DESC or ASC

SQL Order by  ASC  Example :

The “teacher info” Table

after drop

Here  we want to select all the Teacher name from the table teacher info.  However , here we will  sort FIRST_NAME of all the Teacher   by  ascending order/ ASC..

We will  use the following SELECT statement with Order By:

SELECT * FROM `teacher info2`
ORDER BY FIRST_NAME ASC

The output looks Like Below:

ASSENDING

ORDER BY DESC Example

Now we want to select all the Teacher Salary  from the table teacher info.  However , here we will  sort SALARY  of all the Teacher   by  descending / DESC.

For this We will use the following SELECT statement:

SELECT * FROM `teacher info2` ORDER BY FIRST_NAME DESC
The output of the code looks like below:
DESENDING
Purpose of SQL Group By:

The Group By Statement is used in conjunction with  the aggregate function to Group the all result -set by one or more columns.

Syntax of Group By:

select column _name, aggregate_function(column_name) from table where column_name operator value GROUP BY  column_name

Example of GROUP BY:

SELECT FIRST_NAME, MIDDLE_NAME, LAST_NAME, TEACHER_ID
FROM `teacher info2`
GROUP BY FIRST_NAME

Output of the above statement:

group by

RELATED POST OR YOU MAY LIKE:


knowledgediarybd.com © 2017
shares