Total Items Sold by Product
A company tracks its sales through an orders table. Each row represents a line item in an order, detailing the product sold and its quantity.
Tables:
orders(order_id integer, product_name varchar(50), quantity integer)
Write a query that returns the total quantity sold for each product_name. The results should be ordered alphabetically by product_name. Handle NULL product names by grouping them together. If the table is empty, return an empty result set.
Tables
CREATE TABLE orders (
order_id integer NOT NULL,
product_name varchar(50),
quantity integer NOT NULL CHECK (quantity > 0)
);Example data
INSERT INTO orders (order_id, product_name, quantity) VALUES (101, 'Laptop', 1), (101, 'Mouse', 2), (102, 'Keyboard', 1), (103, 'Laptop', 1), (103, 'Webcam', 1), (104, 'Mouse', 3), (105, 'Keyboard', 2), (106, 'Monitor', 1), (107, 'Laptop', 2);
Your query is also checked on hidden datasets with different data.
Hints
SELECT
Your query runs on the example tables shown with the problem, then on hidden datasets when you submit.
Write standard SQL. MySQL habits work too: IFNULL, IF, YEAR(), DATE_FORMAT, GROUP_CONCAT, `backticks` and LIMIT 5, 10. It runs on PostgreSQL, so integer division keeps whole numbers (5 / 2 = 2): write 5.0 / 2 for 2.5.