1. Classify customers based on total spend
Table: orders (order_id, customer_id, amount)
Requirement:
- Gold if total_spend >= 100000
- Silver if total_spend between 50000 and 99999
- Bronze otherwise
Solution:
SELECT customer_id,2. Create an age group column for users
CASE
WHEN SUM(amount) >= 100000 THEN 'Gold'
WHEN SUM(amount) >= 50000 THEN 'Silver'
ELSE 'Bronze'
END AS customer_category
FROM orders
GROUP BY customer_id;
Table: users (user_id, age)
Requirement:
- Below 18
- 18 to 30
- Above 30
Solution:
SELECT user_id,3. Replace NULL salary with 0
CASE
WHEN age < 18 THEN 'Below 18'
WHEN age BETWEEN 18 AND 30 THEN '18-30'
ELSE 'Above 30'
END AS age_group
FROM users;
Table: employees (employee_id, salary)
Solution:
SELECT employee_id, COALESCE(salary, 0) AS salary4. Count employees with missing email IDs
FROM employees;
Table: employees (employee_id, email)
Solution:
SELECT COUNT(*) AS missing_email_count5. Remove extra spaces from customer names
FROM employees
WHERE email IS NULL;
Table: customers (customer_id, name)
Solution:
SELECT customer_id, TRIM(name) AS clean_name6. Extract first 3 characters from product code
FROM customers;
Table: products (product_code)
Solution:
SELECT product_code, SUBSTRING(product_code, 1, 3) AS product_prefix7. Standardize date format
FROM products;
Table: orders (order_date)
Requirement: Convert to YYYY-MM-DD
Solution:
SELECT CAST(order_date AS DATE) AS clean_order_date8. Mark inactive users based on last login
FROM orders;
Table: users (user_id, last_login_date)
Requirement: Inactive if last login before 2023-01-01
Solution:
SELECT user_id,9. Handle empty string as NULL
CASE
WHEN last_login_date < '2023-01-01' THEN 'Inactive'
ELSE 'Active'
END AS user_status
FROM users;
Table: customers (phone_number)
Solution:
SELECT NULLIF(phone_number, '') AS phone_number10. Create a clean reporting column using multiple rules
FROM customers;
Table: transactions (amount)
Requirement:
- High if amount >= 10000
- Medium if 5000 to 9999
- Low otherwise
Solution:
SELECT amount,Double Tap ♥️ For More
CASE
WHEN amount >= 10000 THEN 'High'
WHEN amount >= 5000 THEN 'Medium'
ELSE 'Low'
END AS transaction_type
FROM transactions;