SQL - GROUP BY and HAVINGWhich of the following SQL queries correctly groups sales by product and orders the result by total sales descending?ASELECT product, SUM(amount) FROM sales GROUP BY product ORDER BY SUM(amount) DESC;BSELECT product, SUM(amount) FROM sales ORDER BY product GROUP BY SUM(amount) DESC;CSELECT product, SUM(amount) FROM sales GROUP BY product ORDER BY product DESC;DSELECT product, SUM(amount) FROM sales ORDER BY SUM(amount) GROUP BY product DESC;Check Answer
Step-by-Step SolutionSolution:Step 1: Check GROUP BY and ORDER BY orderThe correct syntax is GROUP BY first, then ORDER BY to sort grouped results.Step 2: Verify ordering by aggregated columnOrdering by SUM(amount) DESC sorts by total sales descending, matching the requirement.Final Answer:SELECT product, SUM(amount) FROM sales GROUP BY product ORDER BY SUM(amount) DESC; -> Option AQuick Check:GROUP BY then ORDER BY with aggregate [OK]Quick Trick: GROUP BY before ORDER BY; order by aggregate for totals [OK]Common Mistakes:MISTAKESSwapping GROUP BY and ORDER BY orderOrdering by non-aggregated columns incorrectlyUsing ORDER BY before GROUP BY
Master "GROUP BY and HAVING" in SQL9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More SQL Quizzes Aggregate Functions - AVG function - Quiz 14medium Aggregate Functions - Aggregate with NULL handling - Quiz 7medium Aggregate Functions - MIN and MAX functions - Quiz 11easy LEFT and RIGHT JOIN - Why outer joins are needed - Quiz 4medium Subqueries - Correlated subquery execution model - Quiz 12easy Table Constraints - CHECK constraint - Quiz 14medium Table Relationships - One-to-many relationship design - Quiz 10hard Views - Why views are needed - Quiz 6medium Views - Dropping and altering views - Quiz 7medium Views - Updatable views and limitations - Quiz 12easy