Given a table sales with columns product_id and amount, what is the output of this query?
SELECT product_id, SUM(amount) AS total_sales FROM sales GROUP BY product_id ORDER BY product_id;
CREATE TABLE sales (product_id INT, amount DECIMAL(10,2)); INSERT INTO sales VALUES (1, 10.00), (1, 15.50), (2, 7.25), (2, 12.75), (3, 20.00);
Remember that SUM() adds values per group defined by GROUP BY.
The query groups rows by product_id and sums the amount for each group. So product 1 sums 10.00 + 15.50 = 25.50, product 2 sums 7.25 + 12.75 = 20.00, and product 3 has one amount 20.00.
What will be the result of the following query if the amount column contains NULL values?
SELECT SUM(amount) FROM sales;
CREATE TABLE sales (amount DECIMAL(10,2)); INSERT INTO sales VALUES (10.00), (NULL), (20.00);
Think about how SUM() treats NULL values in aggregation.
The SUM() function ignores NULL values and sums only non-NULL values. So 10.00 + 20.00 = 30.00.
Which option contains a syntax error when trying to calculate the total amount?
SELECT SUM(amount) FROM sales;
Check the correct syntax for calling functions in SQL.
Option D misses parentheses around the argument for SUM, which is required. The others are valid syntax.
Which query efficiently calculates the total sales amount only for product_id 1?
CREATE TABLE sales (product_id INT, amount DECIMAL(10,2)); INSERT INTO sales VALUES (1, 10.00), (1, 15.50), (2, 7.25);
Think about filtering rows before aggregation for efficiency.
Option B filters rows first with WHERE, then sums. Option B groups all products then filters, which is less efficient. Option B sums all rows. Option B filters by amount, not product.
Given the table orders with column price, why does this query return NULL?
SELECT SUM(price) FROM orders WHERE price < 0;
CREATE TABLE orders (price DECIMAL(10,2)); INSERT INTO orders VALUES (10.00), (20.00), (30.00);
Consider what happens when no rows match the WHERE condition.
If no rows satisfy the WHERE condition, SUM returns NULL because it has no values to add.