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 →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| min_price | max_price | avg_price | distinct_categories |
|---|---|---|---|
| 12.75 | 9999.0 | 2075.45 | 4 |
Step by step
- 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 - 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 - 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
1. Using orders, profile revenue: the smallest, largest and average, as three columns.
SELECT MIN(revenue), MAX(revenue), AVG(revenue) FROM orders2. Using products, how many different categories are there? Name it distinct_categories.
SELECT COUNT(DISTINCT category) AS distinct_categories FROM products3. 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 customers4. 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_sales5. Using returns, profile refund_amount: show its smallest and largest value, as two columns.
SELECT MIN(refund_amount), MAX(refund_amount) FROM returnsLearn 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 →