Introduction
We use GROUP BY to group similar data together and ORDER BY to sort the results. Combining them helps us see grouped data in a sorted way.
Jump into concepts and practice - no test required
SELECT column1, aggregate_function(column2) FROM table_name GROUP BY column1 ORDER BY column1 [ASC|DESC];
SELECT category, COUNT(*) FROM products GROUP BY category ORDER BY category ASC;
SELECT department, SUM(salary) FROM employees GROUP BY department ORDER BY SUM(salary) DESC;
SELECT city, AVG(age) FROM customers GROUP BY city ORDER BY AVG(age) ASC;
CREATE TABLE sales ( product VARCHAR(20), quantity INT ); INSERT INTO sales (product, quantity) VALUES ('Apple', 10), ('Banana', 5), ('Apple', 15), ('Banana', 7), ('Cherry', 20); SELECT product, SUM(quantity) AS total_quantity FROM sales GROUP BY product ORDER BY total_quantity DESC;
GROUP BY clause do in an SQL query?orders with columns customer_id and order_total, what will this query return?SELECT customer_id, COUNT(*) AS order_count FROM orders GROUP BY customer_id ORDER BY order_count ASC;
SELECT department, COUNT(*) FROM employees ORDER BY COUNT(*) DESC GROUP BY department;
sales table with columns region, salesperson, and amount. You want to find the total sales per region, but only show regions with total sales above 1000, sorted by total sales descending. Which query achieves this?