ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.
GROUP BY [col1],[col2],…,[coln]; Tels DBMS to group results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average
doubt inorder by and group by
Can we use Order By and Group By in the same query? If Yes, then how can we use it.
Difference between GROUP BY and ORDER BY in MySQL?
The ORDER BY clause is used to sort the rows.
ASC: ascending order (the default order)
DESC: descending order
Example:
SELECT last_name, job_id, hire_date FROM Employees ORDER BY hire_date;
SELECT last_name, job_id, hire_date FROM Employees ORDER BY hire_date DESC;
GROUP BY Clause divide the rows in table into smaller groups.
Syntax:
SELECT column, group function (column)
FROM table
[WHERE Condition]
[GROUP BY group_by_expression]
[ORDER BY column];
Here
group_by_expression: Specifies columns whose values determine the basis for grouping rows.
And Group Function are : AVG, COUNT, MAX, MIN, STDDEV, SUM, VARIANCE.
Example:
SELECT department_id, AVG (salary) FROM employees GROUP BY department_id;
Post new comment