DISTINCT vs GROUP BY
- SQL course
- Beginner
- Lesson 69/115
- 4 min
Learn the difference between DISTINCT and GROUP BY.
DISTINCT with aggregates
DISTINCT can be used inside aggregates like SUM(DISTINCT column) and AVG(DISTINCT column).
SELECT AVG(DISTINCT price) AS ort FROM products;This query averages the non-duplicate prices.
AVG(DISTINCT price) AS ort is selected from products.
DISTINCT with aggregates — details
AVG(DISTINCT) counts duplicates once. SUM(DISTINCT) adds duplicates once. It is rarely used but you should know it.
Practice DISTINCT with aggregates
Compute the average of unique prices aliased as ort from products.
Starter code
-- distinct average
SELECT
FROM productsSample solution
SELECT AVG(DISTINCT price) AS ort
FROM productsExpected output
ort 14.00
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Distinct average
SELECT AVG(____ price) FROM products;
SELECT AVG(DISTINCT price) FROM products;
Explanation: DISTINCT is the right answer.
2 DISTINCT vs GROUP BY: match the terms
| Term | Meaning |
|---|---|
AVG |
average |
DISTINCT |
deduplicate |
SUM |
sum |
COUNT |
count |
3 What does AVG(DISTINCT price) do?
- The lowest price
- The average of all prices
- The highest price
- The average of distinct prices Correct answer
Explanation: AVG(DISTINCT) averages unique values.