Consider a table sales with columns region and amount. What is the output of this query?
SELECT region, SUM(amount) FROM sales GROUP BY region ORDER BY region;
CREATE TABLE sales(region TEXT, amount INT); INSERT INTO sales VALUES ('East', 100), ('West', 200), ('East', 150), ('North', 50), ('West', 100);
GROUP BY groups rows by the unique values in the region column, then SUM adds amounts per group.
The query groups all rows by region. For each region, it sums the amount values. East has 100 + 150 = 250, West has 200 + 100 = 300, North has 50.
Given a table orders with columns customer_id, product_id, and quantity, what is the output of this query?
SELECT customer_id, product_id, SUM(quantity) FROM orders GROUP BY customer_id, product_id ORDER BY customer_id, product_id;
CREATE TABLE orders(customer_id INT, product_id INT, quantity INT); INSERT INTO orders VALUES (1, 101, 2), (1, 102, 3), (2, 101, 1), (1, 101, 4), (2, 103, 5);
GROUP BY with two columns groups rows by unique pairs of customer_id and product_id.
The query sums quantity for each unique pair of customer_id and product_id. Customer 1 ordered product 101 twice (2 + 4 = 6), product 102 once (3). Customer 2 ordered product 101 once (1) and product 103 once (5).
Which of the following queries will cause a syntax error in PostgreSQL?
SELECT department, employee_name, COUNT(*) FROM employees GROUP BY department;
CREATE TABLE employees(department TEXT, employee_name TEXT);
In PostgreSQL, all selected columns must be either aggregated or included in GROUP BY.
The query selects employee_name which is neither aggregated nor in the GROUP BY clause. PostgreSQL requires all non-aggregated columns to be in GROUP BY, so this causes a syntax error.
You have a large table transactions with columns user_id, category, and amount. Which index will best optimize this query?
SELECT user_id, category, SUM(amount) FROM transactions GROUP BY user_id, category;
Indexes that match the GROUP BY columns in order help aggregation queries.
An index on (user_id, category) matches the GROUP BY columns and their order, helping PostgreSQL efficiently group and aggregate data.
Given a table products with columns category and price, what will this query return?
SELECT category, COUNT(*) FROM products GROUP BY category ORDER BY category;
Assume some rows have category as NULL.
CREATE TABLE products(category TEXT, price INT); INSERT INTO products VALUES ('Books', 10), (NULL, 20), ('Books', 15), (NULL, 30), ('Games', 25);
GROUP BY treats NULL as a distinct group.
Rows with NULL in category form their own group. So the count for NULL category is 2, Books is 2, Games is 1.