Lessons › SQL › Deep Dive: Data Cleaning
SQL lesson
Range checks and flagging values outside expected bounds
A range check flags numbers that fall outside a set of realistic boundaries - too low, too high, or outright impossible.
Try this lesson free →Example
Flagging Retail Values Outside Expected Ranges
SELECT order_id, price, discount, quantity,
CASE
WHEN price <= 0 THEN 'Invalid price'
WHEN discount NOT BETWEEN 0 AND 1 THEN 'Invalid discount'
WHEN quantity < 1 THEN 'Invalid quantity'
ELSE 'OK'
END AS data_flag
FROM orders
WHERE price <= 0 OR discount NOT BETWEEN 0 AND 1 OR quantity < 1| order_id | price | discount | quantity | data_flag |
|---|---|---|---|---|
| O2003 | -15.0 | 0.05 | 3 | Invalid price |
| O2004 | 89.5 | 1.75 | 1 | Invalid discount |
| O2005 | 34.0 | 0.0 | 0 | Invalid quantity |
Step by step
- AS gives a column a friendlier name in the result.
SELECT order_id, price, discount, quantity, CASE WHEN price <= 0 THEN 'Invalid price' WHEN discount NOT BETWEEN 0 AND 1 THEN 'Invalid discount' WHEN quantity < 1 THEN 'Invalid quantity' ELSE 'OK' END AS data_flag - FROM tells SQL which table to pull the data from.
SELECT order_id, price, discount, quantity, CASE WHEN price <= 0 THEN 'Invalid price' WHEN discount NOT BETWEEN 0 AND 1 THEN 'Invalid discount' WHEN quantity < 1 THEN 'Invalid quantity' ELSE 'OK' END AS data_flag FROM orders - WHERE keeps only the rows that match your condition.
SELECT order_id, price, discount, quantity, CASE WHEN price <= 0 THEN 'Invalid price' WHEN discount NOT BETWEEN 0 AND 1 THEN 'Invalid discount' WHEN quantity < 1 THEN 'Invalid quantity' ELSE 'OK' END AS data_flag FROM orders WHERE price <= 0 OR discount NOT BETWEEN 0 AND 1 OR quantity < 1;
Practice
1. Using orders, write a query to find rows where revenue is outside the valid range 0 to 100.
SELECT * FROM orders WHERE revenue < 0 OR revenue > 1002. Using store_sales, write a query to find rows where revenue is outside the valid range 0 to 100.
SELECT * FROM store_sales WHERE revenue < 0 OR revenue > 1003. Using products, write a query to find rows where price is outside the valid range 0 to 100.
SELECT * FROM products WHERE price < 0 OR price > 1004. Using employees, write a query to find rows where salary is outside the valid range 0 to 100.
SELECT * FROM employees WHERE salary < 0 OR salary > 1005. Using reviews, find rows where rating is outside the valid range 1 to 5.
SELECT * FROM reviews WHERE rating < 1 OR rating > 5Learn 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 →