Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
+1 vote
667 views
in Computer by (25.0k points)

Write the differences between order by and group by with example.

1 Answer

+1 vote
by (26.0k points)
selected by
 
Best answer

1. SQL ORDER BY Clause:

The SQL ORDER BY Clause is used in a SELECT statement to sort results either in ascending or descending order.

Syntax for using SQL ORDER BY clause to sort data is:
>SELECTcolumn-list FROM table_name ORDER BY column1, column2,.. columnN [DESC]];
For Example:
If you want to sort the employee table by salary of the employee, the SQL query would be.
> SELECT name, salary FROM employee ORDER BY salary;
By default, the ORDER BY Clause sorts data in  ascending order. If data to be sorted in descending order, the command would be as given below.
> SELECT name, salary FROM employee ORDER BY name, salary DESC;

2. SQL GROUP BY Clause:
The SQL GROUP BY Clause is used with the group functions to retrieve data grouped according to one or more columns.

The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2 FROM table name WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

For Example:

If you want to know the total amount of salary spent on each department, the query would be:
> SELECT dept, SUM (salary) FROM employee GROUP BY dept;
The group by clause should contain all the columns in the select list expect those used along with the group functions.
> SELECT location, dept, SUM (salary) FROM employee GROUP BY location, dept;

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 31, 2020 in Computer by Punit01 (25.0k points)
0 votes
1 answer
asked Mar 31, 2020 in Computer by Punit01 (25.0k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...