0
0
SQLquery~5 mins

GROUP BY with ORDER BY in SQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the GROUP BY clause do in SQL?
It groups rows that have the same values in specified columns into summary rows, like grouping all sales by each product.
Click to reveal answer
beginner
Why do we use ORDER BY after GROUP BY?
To sort the grouped results in a specific order, such as sorting groups by total sales from highest to lowest.
Click to reveal answer
intermediate
Can you use aggregate functions like SUM() with GROUP BY? Give an example.
Yes. For example, SELECT product, SUM(sales) FROM sales_data GROUP BY product; sums sales for each product group.
Click to reveal answer
intermediate
What happens if you use ORDER BY on a column not in the GROUP BY clause?
You can order by aggregate results or columns in the SELECT list, but not by columns not grouped or aggregated, or it causes an error.
Click to reveal answer
beginner
Write a simple SQL query that groups sales by region and orders the result by total sales descending.
Example: SELECT region, SUM(sales) AS total_sales FROM sales_data GROUP BY region ORDER BY total_sales DESC;
Click to reveal answer
What is the purpose of the GROUP BY clause in SQL?
ATo delete duplicate rows
BTo sort rows in ascending order
CTo combine rows with the same values into groups
DTo filter rows based on a condition
Which clause should come first in a SQL query: GROUP BY or ORDER BY?
AORDER BY before GROUP BY
BGROUP BY before ORDER BY
CThey can be in any order
DOnly one of them can be used
What will this query do? SELECT city, COUNT(*) FROM customers GROUP BY city ORDER BY COUNT(*) DESC;
AGroup customers but not sort results
BSort customers by city name
CCount total customers without grouping
DCount customers per city and sort cities by count descending
Can you use ORDER BY on an aggregate function result like SUM(sales)?
AYes, to sort groups by the aggregate value
BNo, aggregate functions cannot be ordered
COnly if you use DISTINCT
DOnly if you use HAVING
If you group by department, which column can you order by?
AOnly columns in GROUP BY or aggregates
BAny column in the table
COnly columns not in GROUP BY
DOnly columns with unique values
Explain how GROUP BY and ORDER BY work together in a SQL query.
Think about grouping first, then sorting the groups.
You got /4 concepts.
    Write a SQL query that groups sales by product category and orders the categories by total sales ascending.
    Use SUM() and ORDER BY with ASC.
    You got /3 concepts.