A. Ordering by 'name' is invalid because 'name' is not in groupBy
B. Nothing is wrong; this query works fine
C. groupBy requires an aggregate function with orderBy
D. You cannot use orderBy after groupBy
Solution
Step 1: Understand SQL grouping rules
When grouping by a column, all selected columns must be in groupBy or aggregated. Ordering by a column not in groupBy can cause errors.
Step 2: Check if 'name' is grouped or aggregated
The query groups by 'role' but orders by 'name' which is not grouped or aggregated, causing SQL errors.
Final Answer:
Ordering by 'name' is invalid because 'name' is not in groupBy -> Option A
Quick Check:
Order column must be grouped or aggregated [OK]
Hint: Order columns must be in groupBy or aggregated [OK]
Common Mistakes:
Assuming orderBy always works after groupBy
Ignoring SQL strict mode errors
Thinking groupBy requires aggregate with orderBy
5. You want to get the total sales amount per product category, but only for categories with more than 5 sales, ordered by total sales descending. Which Laravel query achieves this?
hard
A. DB::table('sales')->select('category', DB::raw('sum(amount) as total'))
->orderBy('total', 'desc')->groupBy('category')->having('total', '>', 5)
->get();
B. DB::table('sales')->select('category', DB::raw('sum(amount) as total'))
->groupBy('category')->where('total', '>', 5)
->orderBy('total', 'desc')->get();
C. DB::table('sales')->select('category', DB::raw('sum(amount) as total'))
->groupBy('category')->having('total', '>', 5)
->orderBy('total', 'desc')->get();
D. DB::table('sales')->select('category', DB::raw('sum(amount) as total'))
->groupBy('category')->orderBy('total', 'desc')->where('total', '>', 5)
->get();
Solution
Step 1: Use groupBy and sum aggregation
Group sales by category and sum the amount as total.
Step 2: Filter groups with having clause
Use having('total', '>', 5) to filter categories with more than 5 sales. where cannot filter aggregated results.
Step 3: Order results by total descending
Use orderBy('total', 'desc') after grouping and filtering.
Final Answer:
DB::table('sales')->select('category', DB::raw('sum(amount) as total'))
->groupBy('category')->having('total', '>', 5)
->orderBy('total', 'desc')->get(); -> Option C
Quick Check:
Use having for aggregates, orderBy after groupBy [OK]
Hint: Use having() to filter grouped aggregates, not where() [OK]
Common Mistakes:
Using where() instead of having() for aggregate filters
Ordering before grouping
Misplacing having() after where()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.