CodeBlanks Logo Icon CodeBlanks

DISTINCT vs GROUP BY

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

query.sql
-- distinct average
SELECT
FROM products

Sample solution

query.sql
SELECT AVG(DISTINCT price) AS ort
FROM products

Expected 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

Question
SELECT AVG(____ price) FROM products;
Answer
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.

All lessons in Beginner