Given a sales table with columns product_id and amount, which query correctly calculates the total sales amount per product?
SELECT product_id, SUM(amount) FROM sales GROUP BY product_id;
Think about how to group rows to get totals per product.
Option B groups sales by product and sums the amounts, giving total sales per product. Option B just lists rows without aggregation. Option B counts sales per product but does not sum amounts. Option B tries to sum without grouping, causing an error.
Which statement best explains why aggregation functions like SUM, COUNT, and AVG are important in databases?
Think about what aggregation functions do with many rows of data.
Aggregation functions summarize multiple rows into one value, which helps in understanding overall trends or totals. The other options describe unrelated database operations.
What error does this query produce?
SELECT department, AVG(salary) FROM employees WHERE department = 'Sales';
Check if all non-aggregated columns are grouped.
The query filters rows to only those where department = 'Sales', so the result is a single department. Therefore, no GROUP BY is needed and the query runs correctly. Option C is incorrect because the WHERE clause filters before aggregation. Option C is wrong because salary exists. Option C is false; WHERE can be used before aggregation.
You have a large orders table with millions of rows. Which approach improves performance when calculating total sales per region?
Indexes help queries filter and group data faster.
Indexing the grouping column helps the database quickly locate rows per region, speeding aggregation. Removing GROUP BY or using SELECT * does not help and may slow down. Running without indexes is inefficient.
Given the query:
SELECT category, COUNT(*) FROM products GROUP BY category HAVING COUNT(*) > 5;
Why might some categories be missing from the result?
Consider what HAVING does after grouping.
HAVING filters groups after aggregation. It excludes categories with 5 or fewer products, so only categories with more than 5 products appear. GROUP BY does not remove categories, it groups them. COUNT(*) counts all rows in the group, including nulls in other columns. The syntax is valid.