GROUP BY Single and Multiple Columns in PostgreSQL
📖 Scenario: You are working with a sales database for a small bookstore. The database has a table called sales that records each book sale with the book's title, the genre, and the number of copies sold.Your task is to learn how to group sales data by single and multiple columns to find total copies sold per book and per genre.
🎯 Goal: Build SQL queries using GROUP BY to calculate total copies sold grouped by a single column (title) and by multiple columns (genre and title).
📋 What You'll Learn
Create a sales table with columns title (text), genre (text), and copies_sold (integer).
Insert specific sales data into the sales table.
Write a SQL query to group total copies sold by title.
Write a SQL query to group total copies sold by both genre and title.
💡 Why This Matters
🌍 Real World
Grouping sales data helps businesses understand which books or genres sell best, aiding inventory and marketing decisions.
💼 Career
Database professionals often write GROUP BY queries to summarize and analyze data for reports and dashboards.
Progress0 / 4 steps
1
Create the sales table and insert data
Create a table called sales with columns title (text), genre (text), and copies_sold (integer). Then insert these exact rows into the sales table: ('The Hobbit', 'Fantasy', 10), ('The Hobbit', 'Fantasy', 5), ('1984', 'Dystopian', 8), ('1984', 'Dystopian', 7), ('Dune', 'Science Fiction', 12).
PostgreSQL
Hint
Use CREATE TABLE to define the table and INSERT INTO to add rows.
2
Write a query to group total copies sold by title
Write a SQL query that selects title and the sum of copies_sold as total_copies from the sales table. Use GROUP BY title to group the results by the title column.
PostgreSQL
Hint
Use SUM() to add copies sold and GROUP BY title to group by book title.
3
Write a query to group total copies sold by genre and title
Write a SQL query that selects genre, title, and the sum of copies_sold as total_copies from the sales table. Use GROUP BY genre, title to group the results by both genre and title columns.
PostgreSQL
Hint
Use GROUP BY genre, title to group by both columns.
4
Add an ORDER BY clause to sort the grouped results
Add an ORDER BY clause to the query that groups by genre and title to sort the results by genre ascending and then by total_copies descending.
PostgreSQL
Hint
Use ORDER BY genre ASC, total_copies DESC to sort by genre and then by total copies sold.
Practice
(1/5)
1. What does the GROUP BY clause do in a PostgreSQL query?
easy
A. It updates values in the specified columns.
B. It sorts the rows in ascending order.
C. It deletes duplicate rows from the table.
D. It groups rows that have the same values in specified columns.
Solution
Step 1: Understand the purpose of GROUP BY
The GROUP BY clause collects rows that share the same value in one or more columns into groups.
Step 2: Differentiate from other clauses
Unlike ORDER BY which sorts rows, GROUP BY organizes rows into groups for aggregation.
Final Answer:
It groups rows that have the same values in specified columns. -> Option D
Quick Check:
GROUP BY = groups rows by column values [OK]
Hint: GROUP BY collects rows sharing column values into groups [OK]
Common Mistakes:
Confusing GROUP BY with ORDER BY
Thinking GROUP BY deletes duplicates
Assuming GROUP BY updates data
2. Which of the following is the correct syntax to group data by two columns, category and region?
easy
A. SELECT category, region, COUNT(*) FROM sales GROUP BY category, region;
B. SELECT category, region, COUNT(*) FROM sales GROUP BY category region;
C. SELECT category, region, COUNT(*) FROM sales GROUP BY (category, region);
D. SELECT category, region, COUNT(*) FROM sales GROUP category, region;
Solution
Step 1: Check correct GROUP BY syntax
In PostgreSQL, multiple columns are separated by commas in GROUP BY without parentheses.
Step 2: Validate each option
SELECT category, region, COUNT(*) FROM sales GROUP BY category, region; uses commas correctly; SELECT category, region, COUNT(*) FROM sales GROUP BY category region; misses comma; SELECT category, region, COUNT(*) FROM sales GROUP BY (category, region); uses parentheses incorrectly; SELECT category, region, COUNT(*) FROM sales GROUP category, region; misses BY keyword.
Final Answer:
SELECT category, region, COUNT(*) FROM sales GROUP BY category, region; -> Option A
Quick Check:
GROUP BY columns separated by commas [OK]
Hint: Separate multiple columns with commas in GROUP BY [OK]
Common Mistakes:
Omitting commas between columns
Using parentheses around columns
Forgetting the BY keyword
3. Given the table orders with columns customer_id, product_id, and quantity, what will this query return?
SELECT customer_id, SUM(quantity) FROM orders GROUP BY customer_id;
medium
A. Total quantity ordered by each customer.
B. Total quantity ordered by each product.
C. Total quantity ordered by each customer and product.
D. Syntax error due to missing GROUP BY columns.
Solution
Step 1: Analyze the SELECT and GROUP BY columns
The query groups rows by customer_id and sums quantity for each group.
Step 2: Understand the aggregation result
SUM(quantity) calculates total quantity per customer_id, ignoring product_id.
Final Answer:
Total quantity ordered by each customer. -> Option A
Quick Check:
GROUP BY customer_id sums quantity per customer [OK]
Hint: GROUP BY column matches SELECT non-aggregates [OK]
Common Mistakes:
Assuming product_id affects grouping
Thinking query returns per product totals
Confusing aggregation with filtering
4. Identify the error in this query:
SELECT product_id, region, COUNT(*) FROM sales GROUP BY product_id;
medium
A. COUNT(*) cannot be used with GROUP BY.
B. Missing region in GROUP BY causes error.
C. product_id cannot be grouped alone.
D. Syntax error due to missing FROM clause.
Solution
Step 1: Check SELECT columns vs GROUP BY columns
SELECT includes product_id and region, but GROUP BY only has product_id.
Step 2: Understand PostgreSQL grouping rules
All non-aggregated columns in SELECT must appear in GROUP BY; region is missing.
Final Answer:
Missing region in GROUP BY causes error. -> Option B
Quick Check:
All SELECT non-aggregates must be in GROUP BY [OK]
Hint: Include all non-aggregated SELECT columns in GROUP BY [OK]
Common Mistakes:
Forgetting to add all columns to GROUP BY
Thinking COUNT(*) disallows grouping
Ignoring SELECT and GROUP BY mismatch
5. You want to find the total sales quantity for each product in each region from the sales table with columns product_id, region, and quantity. Which query correctly groups and sums the data?
hard
A. SELECT product_id, SUM(quantity) FROM sales GROUP BY product_id;
B. SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id;
C. SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id, region;
D. SELECT product_id, region, SUM(quantity) FROM sales;
Solution
Step 1: Identify grouping needs
We want totals per product and per region, so both columns must be grouped.
Step 2: Check each option's GROUP BY clause
SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id, region; groups by product_id and region, matching SELECT columns; others miss region or GROUP BY entirely.
Final Answer:
SELECT product_id, region, SUM(quantity) FROM sales GROUP BY product_id, region; -> Option C
Quick Check:
Group by all non-aggregated columns for correct totals [OK]
Hint: Group by all selected non-aggregated columns [OK]
Common Mistakes:
Grouping by only one column when selecting multiple
Omitting GROUP BY causing aggregation errors
Selecting columns without aggregation or grouping
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.