BBampaa

Lessons › SQL › Chapter 9: Data Cleaning

SQL lesson

Data profiling with MIN, MAX, COUNT DISTINCT, and AVG

Before cleaning a table, look at it in numbers: the smallest, biggest and average values, and how many different ones there are. Odd results, like a price of 9999, point to the rows that need fixing.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

A quick health check

SELECT MIN(price) AS min_price,
       MAX(price) AS max_price,
       AVG(price) AS avg_price,
       COUNT(DISTINCT category) AS distinct_categories
FROM products

Result:

min_pricemax_priceavg_pricedistinct_categories
12.759999.02075.454

Step by step

  1. The smallest and biggest show odd values, like 9999.
    SELECT MIN(price) AS min_price, MAX(price) AS max_price, AVG(price) AS avg_price, COUNT(DISTINCT category) AS distinct_categories FROM products
  2. The average. One odd value can pull it a long way.
    SELECT MIN(price) AS min_price, MAX(price) AS max_price, AVG(price) AS avg_price, COUNT(DISTINCT category) AS distinct_categories FROM products
  3. How many different categories there are.
    SELECT MIN(price) AS min_price, MAX(price) AS max_price, AVG(price) AS avg_price, COUNT(DISTINCT category) AS distinct_categories FROM products

Practice

Try each one in your head first, then open the answer.

1. Using orders, profile revenue: the smallest, largest and average, as three columns.
SELECT MIN(revenue), MAX(revenue), AVG(revenue) FROM orders
2. Using products, how many different categories are there? Name it distinct_categories.
SELECT COUNT(DISTINCT category) AS distinct_categories FROM products
3. Using customers, count the customers and the different emails, as two columns. If the second is smaller, some emails repeat.
SELECT COUNT(*), COUNT(DISTINCT email) FROM customers
4. Using store_sales, find the first and last sale_date, as two columns: the dates the data covers.
SELECT MIN(sale_date), MAX(sale_date) FROM store_sales
5. Using returns, profile refund_amount: show its smallest and largest value, as two columns.
SELECT MIN(refund_amount), MAX(refund_amount) FROM returns

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed