✏️ Explanatory Question

What is the difference between the ORDER BY and GROUP BY clauses?

👁 7 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

21

What is the difference between the ORDER BY and GROUP BY clauses?

Level: Basic to Intermediate — Tests whether you understand sorting vs aggregating results.

Both clauses organize query results, but they serve completely different purposes:

  • ORDER BY: Sorts the result set in ascending (ASC) or descending (DESC) order. It does not combine rows.
  • GROUP BY: Groups rows that share the same value into summary rows, typically used with aggregate functions like COUNT(), SUM(), AVG().
Key point: GROUP BY collapses multiple rows into one per group (aggregation), while ORDER BY simply rearranges the existing rows without reducing their count.

Side-by-Side Comparison

Feature ORDER BY GROUP BY
Purpose Sorts rows Groups rows
Row count Unchanged Reduced (one per group)
Aggregate functions Not required Commonly used
Execution order Runs last (before LIMIT) Runs before ORDER BY
Directions ASC / DESC N/A

Where They Sit in Execution Order

EXECUTION ORDER
FROMWHEREGROUP BYHAVINGSELECTORDER BY

Quick Example

-- ORDER BY: just sort all rows by salary (highest first)
SELECT name, salary
FROM employees
ORDER BY salary DESC;

-- GROUP BY: one summary row per department
SELECT dept_id, COUNT(*) AS emp_count
FROM employees
GROUP BY dept_id;

-- Both together: group first, then sort the groups
SELECT dept_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY dept_id          -- collapse into one row per dept
ORDER BY avg_salary DESC; -- then sort those group results
Interviewer tip: The one-liner they want — "GROUP BY aggregates rows into groups (reducing row count), while ORDER BY sorts the result set without changing how many rows are returned."